blob: 4d4bd059d7b330d235181d17e3b42a9cb1f41966 [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;
56
57enum NamingConvention { NoConvention, CreateRule, InitRule };
58
59static inline bool isWordEnd(char ch, char prev, char next) {
60 return ch == '\0'
61 || (islower(prev) && isupper(ch)) // xxxC
62 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
63 || !isalpha(ch);
64}
65
66static inline const char* parseWord(const char* s) {
67 char ch = *s, prev = '\0';
68 assert(ch != '\0');
69 char next = *(s+1);
70 while (!isWordEnd(ch, prev, next)) {
71 prev = ch;
72 ch = next;
73 next = *((++s)+1);
74 }
75 return s;
76}
77
78static NamingConvention deriveNamingConvention(const char* s) {
79 // A method/function name may contain a prefix. We don't know it is there,
80 // however, until we encounter the first '_'.
81 bool InPossiblePrefix = true;
82 bool AtBeginning = true;
83 NamingConvention C = NoConvention;
84
85 while (*s != '\0') {
86 // Skip '_'.
87 if (*s == '_') {
88 if (InPossiblePrefix) {
89 InPossiblePrefix = false;
90 AtBeginning = true;
91 // Discard whatever 'convention' we
92 // had already derived since it occurs
93 // in the prefix.
94 C = NoConvention;
95 }
96 ++s;
97 continue;
98 }
99
100 // Skip numbers, ':', etc.
101 if (!isalpha(*s)) {
102 ++s;
103 continue;
104 }
105
106 const char *wordEnd = parseWord(s);
107 assert(wordEnd > s);
108 unsigned len = wordEnd - s;
109
110 switch (len) {
111 default:
112 break;
113 case 3:
114 // Methods starting with 'new' follow the create rule.
115 if (AtBeginning && strncasecmp("new", s, len) == 0)
116 C = CreateRule;
117 break;
118 case 4:
119 // Methods starting with 'alloc' or contain 'copy' follow the
120 // create rule
121 if ((AtBeginning && strncasecmp("alloc", s, len) == 0) ||
122 (strncasecmp("copy", s, len) == 0))
123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
125 if (AtBeginning && strncasecmp("init", s, len) == 0)
126 C = InitRule;
127 break;
128 }
129
130 // If we aren't in the prefix and have a derived convention then just
131 // return it now.
132 if (!InPossiblePrefix && C != NoConvention)
133 return C;
134
135 AtBeginning = false;
136 s = wordEnd;
137 }
138
139 // We will get here if there wasn't more than one word
140 // after the prefix.
141 return C;
142}
143
Ted Kremenek5c74d502008-10-24 21:18:08 +0000144static bool followsFundamentalRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000145 return deriveNamingConvention(s) == CreateRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000146}
147
148static bool followsReturnRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000149 NamingConvention C = deriveNamingConvention(s);
150 return C == CreateRule || C == InitRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000151}
Ted Kremenek5c74d502008-10-24 21:18:08 +0000152
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000153//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000154// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000155//===----------------------------------------------------------------------===//
156
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000157static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000158 IdentifierInfo* II = &Ctx.Idents.get(name);
159 return Ctx.Selectors.getSelector(0, &II);
160}
161
Ted Kremenek9c32d082008-05-06 00:30:21 +0000162static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
163 IdentifierInfo* II = &Ctx.Idents.get(name);
164 return Ctx.Selectors.getSelector(1, &II);
165}
166
Ted Kremenek553cf182008-06-25 21:21:56 +0000167//===----------------------------------------------------------------------===//
168// Type querying functions.
169//===----------------------------------------------------------------------===//
170
Ted Kremenek12619382009-01-12 21:45:02 +0000171static bool hasPrefix(const char* s, const char* prefix) {
172 if (!prefix)
173 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000174
Ted Kremenek12619382009-01-12 21:45:02 +0000175 char c = *s;
176 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000177
Ted Kremenek12619382009-01-12 21:45:02 +0000178 while (c != '\0' && cP != '\0') {
179 if (c != cP) break;
180 c = *(++s);
181 cP = *(++prefix);
182 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000183
Ted Kremenek12619382009-01-12 21:45:02 +0000184 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000185}
186
Ted Kremenek12619382009-01-12 21:45:02 +0000187static bool hasSuffix(const char* s, const char* suffix) {
188 const char* loc = strstr(s, suffix);
189 return loc && strcmp(suffix, loc) == 0;
190}
191
192static bool isRefType(QualType RetTy, const char* prefix,
193 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek37d785b2008-07-15 16:50:12 +0000194
Ted Kremenek12619382009-01-12 21:45:02 +0000195 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
196 const char* TDName = TD->getDecl()->getIdentifier()->getName();
197 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
198 }
199
200 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000201 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000202
203 // Is the type void*?
204 const PointerType* PT = RetTy->getAsPointerType();
205 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000206 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000207
208 // Does the name start with the prefix?
209 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000210}
211
Ted Kremenek4fd88972008-04-17 18:12:53 +0000212//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000213// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000214//===----------------------------------------------------------------------===//
215
Ted Kremenek553cf182008-06-25 21:21:56 +0000216namespace {
217/// ArgEffect is used to summarize a function/method call's effect on a
218/// particular argument.
Ted Kremenek1c512f52009-02-18 18:54:33 +0000219enum ArgEffect { IncRefMsg, IncRef,
220 DecRefMsg, DecRef,
Ted Kremenek27019002009-02-18 21:57:45 +0000221 MakeCollectable,
Ted Kremenek1c512f52009-02-18 18:54:33 +0000222 DoNothing, DoNothingByRef,
Ted Kremenek070a8252008-07-09 18:11:16 +0000223 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek553cf182008-06-25 21:21:56 +0000224
225/// ArgEffects summarizes the effects of a function/method call on all of
226/// its arguments.
227typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000228}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000229
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000230namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000231template <> struct FoldingSetTrait<ArgEffects> {
232 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
233 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
234 ID.AddInteger(I->first);
235 ID.AddInteger((unsigned) I->second);
236 }
237 }
238};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000239} // end llvm namespace
240
241namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000242
243/// RetEffect is used to summarize a function/method call's behavior with
244/// respect to its return value.
245class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000246public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000247 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
248 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000249
250 enum ObjKind { CF, ObjC, AnyObj };
251
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000252private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000253 Kind K;
254 ObjKind O;
255 unsigned index;
256
257 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
258 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000259
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000260public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000261 Kind getKind() const { return K; }
262
263 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000264
265 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000266 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000267 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000268 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000269
Ted Kremenek553cf182008-06-25 21:21:56 +0000270 static RetEffect MakeAlias(unsigned Idx) {
271 return RetEffect(Alias, Idx);
272 }
273 static RetEffect MakeReceiverAlias() {
274 return RetEffect(ReceiverAlias);
275 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000276 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
277 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000278 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000279 static RetEffect MakeNotOwned(ObjKind o) {
280 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000281 }
282 static RetEffect MakeNoRet() {
283 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000284 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000285
Ted Kremenek553cf182008-06-25 21:21:56 +0000286 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000287 ID.AddInteger((unsigned)K);
288 ID.AddInteger((unsigned)O);
289 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000290 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000291};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000292
Ted Kremenek553cf182008-06-25 21:21:56 +0000293
294class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000295 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
296 /// specifies the argument (starting from 0). This can be sparsely
297 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000298 ArgEffects* Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000299
300 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
301 /// do not have an entry in Args.
302 ArgEffect DefaultArgEffect;
303
Ted Kremenek553cf182008-06-25 21:21:56 +0000304 /// Receiver - If this summary applies to an Objective-C message expression,
305 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000306 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000307
308 /// Ret - The effect on the return value. Used to indicate if the
309 /// function/method call returns a new tracked symbol, returns an
310 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000311 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000312
Ted Kremenek70a733e2008-07-18 17:24:20 +0000313 /// EndPath - Indicates that execution of this method/function should
314 /// terminate the simulation of a path.
315 bool EndPath;
316
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000317public:
318
Ted Kremenek1bffd742008-05-06 15:44:25 +0000319 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000320 ArgEffect ReceiverEff, bool endpath = false)
321 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
322 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000323
Ted Kremenek553cf182008-06-25 21:21:56 +0000324 /// getArg - Return the argument effect on the argument specified by
325 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000326 ArgEffect getArg(unsigned idx) const {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000327
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000328 if (!Args)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000329 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000330
331 // If Args is present, it is likely to contain only 1 element.
332 // Just do a linear search. Do it from the back because functions with
333 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek553cf182008-06-25 21:21:56 +0000334 // argument they actually modify with respect to the reference count.
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000335 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
336 I!=E; ++I) {
337
338 if (idx > I->first)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000339 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000340
341 if (idx == I->first)
342 return I->second;
343 }
344
Ted Kremenek1bffd742008-05-06 15:44:25 +0000345 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000346 }
347
Ted Kremenek553cf182008-06-25 21:21:56 +0000348 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000349 RetEffect getRetEffect() const {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000350 return Ret;
351 }
352
Ted Kremenek70a733e2008-07-18 17:24:20 +0000353 /// isEndPath - Returns true if executing the given method/function should
354 /// terminate the path.
355 bool isEndPath() const { return EndPath; }
356
Ted Kremenek553cf182008-06-25 21:21:56 +0000357 /// getReceiverEffect - Returns the effect on the receiver of the call.
358 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000359 ArgEffect getReceiverEffect() const {
360 return Receiver;
361 }
362
Ted Kremenek55499762008-06-17 02:43:46 +0000363 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000364
Ted Kremenek55499762008-06-17 02:43:46 +0000365 ExprIterator begin_args() const { return Args->begin(); }
366 ExprIterator end_args() const { return Args->end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000367
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000368 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000369 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000370 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000371 ID.AddPointer(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000372 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000373 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000374 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000375 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000376 }
377
378 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000379 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000380 }
381};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000382} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000383
Ted Kremenek553cf182008-06-25 21:21:56 +0000384//===----------------------------------------------------------------------===//
385// Data structures for constructing summaries.
386//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000387
Ted Kremenek553cf182008-06-25 21:21:56 +0000388namespace {
389class VISIBILITY_HIDDEN ObjCSummaryKey {
390 IdentifierInfo* II;
391 Selector S;
392public:
393 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
394 : II(ii), S(s) {}
395
396 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
397 : II(d ? d->getIdentifier() : 0), S(s) {}
398
399 ObjCSummaryKey(Selector s)
400 : II(0), S(s) {}
401
402 IdentifierInfo* getIdentifier() const { return II; }
403 Selector getSelector() const { return S; }
404};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000405}
406
407namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000408template <> struct DenseMapInfo<ObjCSummaryKey> {
409 static inline ObjCSummaryKey getEmptyKey() {
410 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
411 DenseMapInfo<Selector>::getEmptyKey());
412 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000413
Ted Kremenek553cf182008-06-25 21:21:56 +0000414 static inline ObjCSummaryKey getTombstoneKey() {
415 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
416 DenseMapInfo<Selector>::getTombstoneKey());
417 }
418
419 static unsigned getHashValue(const ObjCSummaryKey &V) {
420 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
421 & 0x88888888)
422 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
423 & 0x55555555);
424 }
425
426 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
427 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
428 RHS.getIdentifier()) &&
429 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
430 RHS.getSelector());
431 }
432
433 static bool isPod() {
434 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
435 DenseMapInfo<Selector>::isPod();
436 }
437};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000438} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000439
Ted Kremenek4f22a782008-06-23 23:30:29 +0000440namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000441class VISIBILITY_HIDDEN ObjCSummaryCache {
442 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
443 MapTy M;
444public:
445 ObjCSummaryCache() {}
446
447 typedef MapTy::iterator iterator;
448
449 iterator find(ObjCInterfaceDecl* D, Selector S) {
450
451 // Do a lookup with the (D,S) pair. If we find a match return
452 // the iterator.
453 ObjCSummaryKey K(D, S);
454 MapTy::iterator I = M.find(K);
455
456 if (I != M.end() || !D)
457 return I;
458
459 // Walk the super chain. If we find a hit with a parent, we'll end
460 // up returning that summary. We actually allow that key (null,S), as
461 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
462 // generate initial summaries without having to worry about NSObject
463 // being declared.
464 // FIXME: We may change this at some point.
465 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
466 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
467 break;
468
469 if (!C)
470 return I;
471 }
472
473 // Cache the summary with original key to make the next lookup faster
474 // and return the iterator.
475 M[K] = I->second;
476 return I;
477 }
478
Ted Kremenek98530452008-08-12 20:41:56 +0000479
Ted Kremenek553cf182008-06-25 21:21:56 +0000480 iterator find(Expr* Receiver, Selector S) {
481 return find(getReceiverDecl(Receiver), S);
482 }
483
484 iterator find(IdentifierInfo* II, Selector S) {
485 // FIXME: Class method lookup. Right now we dont' have a good way
486 // of going between IdentifierInfo* and the class hierarchy.
487 iterator I = M.find(ObjCSummaryKey(II, S));
488 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
489 }
490
491 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
492
493 const PointerType* PT = E->getType()->getAsPointerType();
494 if (!PT) return 0;
495
496 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
497 if (!OI) return 0;
498
499 return OI ? OI->getDecl() : 0;
500 }
501
502 iterator end() { return M.end(); }
503
504 RetainSummary*& operator[](ObjCMessageExpr* ME) {
505
506 Selector S = ME->getSelector();
507
508 if (Expr* Receiver = ME->getReceiver()) {
509 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
510 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
511 }
512
513 return M[ObjCSummaryKey(ME->getClassName(), S)];
514 }
515
516 RetainSummary*& operator[](ObjCSummaryKey K) {
517 return M[K];
518 }
519
520 RetainSummary*& operator[](Selector S) {
521 return M[ ObjCSummaryKey(S) ];
522 }
523};
524} // end anonymous namespace
525
526//===----------------------------------------------------------------------===//
527// Data structures for managing collections of summaries.
528//===----------------------------------------------------------------------===//
529
530namespace {
531class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000532
533 //==-----------------------------------------------------------------==//
534 // Typedefs.
535 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000536
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000537 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
538 ArgEffectsSetTy;
539
540 typedef llvm::FoldingSet<RetainSummary>
541 SummarySetTy;
542
543 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
544 FuncSummariesTy;
545
Ted Kremenek4f22a782008-06-23 23:30:29 +0000546 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000547
548 //==-----------------------------------------------------------------==//
549 // Data.
550 //==-----------------------------------------------------------------==//
551
Ted Kremenek553cf182008-06-25 21:21:56 +0000552 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000553 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000554
Ted Kremenek070a8252008-07-09 18:11:16 +0000555 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
556 /// "CFDictionaryCreate".
557 IdentifierInfo* CFDictionaryCreateII;
558
Ted Kremenek553cf182008-06-25 21:21:56 +0000559 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000560 const bool GCEnabled;
561
Ted Kremenek553cf182008-06-25 21:21:56 +0000562 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +0000563 SummarySetTy SummarySet;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000564
Ted Kremenek553cf182008-06-25 21:21:56 +0000565 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000566 FuncSummariesTy FuncSummaries;
567
Ted Kremenek553cf182008-06-25 21:21:56 +0000568 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
569 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000570 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000571
Ted Kremenek553cf182008-06-25 21:21:56 +0000572 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000573 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000574
Ted Kremenek553cf182008-06-25 21:21:56 +0000575 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000576 ArgEffectsSetTy ArgEffectsSet;
577
Ted Kremenek553cf182008-06-25 21:21:56 +0000578 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
579 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000580 llvm::BumpPtrAllocator BPAlloc;
581
Ted Kremenek553cf182008-06-25 21:21:56 +0000582 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000583 ArgEffects ScratchArgs;
584
Ted Kremenek432af592008-05-06 18:11:36 +0000585 RetainSummary* StopSummary;
586
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000587 //==-----------------------------------------------------------------==//
588 // Methods.
589 //==-----------------------------------------------------------------==//
590
Ted Kremenek553cf182008-06-25 21:21:56 +0000591 /// getArgEffects - Returns a persistent ArgEffects object based on the
592 /// data in ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000593 ArgEffects* getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000594
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000595 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000596
597public:
Ted Kremenek12619382009-01-12 21:45:02 +0000598 RetainSummary* getUnarySummary(FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000599
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000600 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
601 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000602 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000603
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000604 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000605 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000606 ArgEffect DefaultEff = MayEscape,
607 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000608
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000609 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000610 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000611 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000612 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000613 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000614
Ted Kremenek1bffd742008-05-06 15:44:25 +0000615 RetainSummary* getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000616 if (StopSummary)
617 return StopSummary;
618
619 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
620 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000621
Ted Kremenek432af592008-05-06 18:11:36 +0000622 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000623 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000624
Ted Kremenek553cf182008-06-25 21:21:56 +0000625 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000626
Ted Kremenek1f180c32008-06-23 22:21:20 +0000627 void InitializeClassMethodSummaries();
628 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000629
Ted Kremenek234a4c22009-01-07 00:39:56 +0000630 bool isTrackedObjectType(QualType T);
631
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000632private:
633
Ted Kremenek70a733e2008-07-18 17:24:20 +0000634 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
635 RetainSummary* Summ) {
636 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
637 }
638
Ted Kremenek553cf182008-06-25 21:21:56 +0000639 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
640 ObjCClassMethodSummaries[S] = Summ;
641 }
642
643 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
644 ObjCMethodSummaries[S] = Summ;
645 }
646
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000647 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenek70a733e2008-07-18 17:24:20 +0000648
Ted Kremenek9e476de2008-08-12 18:30:56 +0000649 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
650 llvm::SmallVector<IdentifierInfo*, 10> II;
651
652 while (const char* s = va_arg(argp, const char*))
653 II.push_back(&Ctx.Idents.get(s));
654
655 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek70a733e2008-07-18 17:24:20 +0000656 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
657 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000658
659 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
660 va_list argp;
661 va_start(argp, Summ);
662 addInstMethSummary(Cls, Summ, argp);
663 va_end(argp);
664 }
Ted Kremenek9e476de2008-08-12 18:30:56 +0000665
666 void addPanicSummary(const char* Cls, ...) {
667 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
668 DoNothing, DoNothing, true);
669 va_list argp;
670 va_start (argp, Cls);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000671 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000672 va_end(argp);
673 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000674
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000675public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000676
677 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000678 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000679 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek553cf182008-06-25 21:21:56 +0000680 GCEnabled(gcenabled), StopSummary(0) {
681
682 InitializeClassMethodSummaries();
683 InitializeMethodSummaries();
684 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000685
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000686 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000687
Ted Kremenekab592272008-06-24 03:56:45 +0000688 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek553cf182008-06-25 21:21:56 +0000689 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek1f180c32008-06-23 22:21:20 +0000690 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenekb3095252008-05-06 04:20:12 +0000691
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000692 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000693};
694
695} // end anonymous namespace
696
697//===----------------------------------------------------------------------===//
698// Implementation of checker data structures.
699//===----------------------------------------------------------------------===//
700
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000701RetainSummaryManager::~RetainSummaryManager() {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000702
703 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
704 // mitigating the need to do explicit cleanup of the
705 // Argument-Effect summaries.
706
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000707 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
708 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000709 I->getValue().~ArgEffects();
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000710}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000711
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000712ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000713
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000714 if (ScratchArgs.empty())
715 return NULL;
716
717 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000718 llvm::FoldingSetNodeID profile;
719 profile.Add(ScratchArgs);
720 void* InsertPos;
721
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000722 // Look up the uniqued copy, or create a new one.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000723 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000724 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000725
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000726 if (E) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000727 ScratchArgs.clear();
728 return &E->getValue();
729 }
730
731 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek553cf182008-06-25 21:21:56 +0000732 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000733
734 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000735 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000736
737 ScratchArgs.clear();
738 return &E->getValue();
739}
740
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000741RetainSummary*
742RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000743 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000744 ArgEffect DefaultEff,
745 bool isEndPath) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000746
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000747 // Generate a profile for the summary.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000748 llvm::FoldingSetNodeID profile;
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000749 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
750 isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000751
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000752 // Look up the uniqued summary, or create one if it doesn't exist.
753 void* InsertPos;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000754 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000755
756 if (Summ)
757 return Summ;
758
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000759 // Create the summary and return it.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000760 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000761 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000762 SummarySet.InsertNode(Summ, InsertPos);
763
764 return Summ;
765}
766
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000767//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000768// Predicates.
769//===----------------------------------------------------------------------===//
770
771bool RetainSummaryManager::isTrackedObjectType(QualType T) {
772 if (!Ctx.isObjCObjectPointerType(T))
773 return false;
774
775 // Does it subclass NSObject?
776 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
777
778 // We assume that id<..>, id, and "Class" all represent tracked objects.
779 if (!OT)
780 return true;
781
782 // Does the object type subclass NSObject?
783 // FIXME: We can memoize here if this gets too expensive.
784 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
785 ObjCInterfaceDecl* ID = OT->getDecl();
786
787 for ( ; ID ; ID = ID->getSuperClass())
788 if (ID->getIdentifier() == NSObjectII)
789 return true;
790
791 return false;
792}
793
794//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000795// Summary creation for functions (largely uses of Core Foundation).
796//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000797
Ted Kremenek12619382009-01-12 21:45:02 +0000798static bool isRetain(FunctionDecl* FD, const char* FName) {
799 const char* loc = strstr(FName, "Retain");
800 return loc && loc[sizeof("Retain")-1] == '\0';
801}
802
803static bool isRelease(FunctionDecl* FD, const char* FName) {
804 const char* loc = strstr(FName, "Release");
805 return loc && loc[sizeof("Release")-1] == '\0';
806}
807
Ted Kremenekab592272008-06-24 03:56:45 +0000808RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000809
810 SourceLocation Loc = FD->getLocation();
811
812 if (!Loc.isFileID())
813 return NULL;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000814
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000815 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000816 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000817
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000818 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000819 return I->second;
820
821 // No summary. Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000822 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000823
Ted Kremenek37d785b2008-07-15 16:50:12 +0000824 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000825 // We generate "stop" summaries for implicitly defined functions.
826 if (FD->isImplicit()) {
827 S = getPersistentStopSummary();
828 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000829 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000830
Ted Kremenek99890652009-01-16 18:40:33 +0000831 // [PR 3337] Use 'getDesugaredType' to strip away any typedefs on the
832 // function's type.
833 FunctionType* FT = cast<FunctionType>(FD->getType()->getDesugaredType());
Ted Kremenek12619382009-01-12 21:45:02 +0000834 const char* FName = FD->getIdentifier()->getName();
835
836 // Inspect the result type.
837 QualType RetTy = FT->getResultType();
838
839 // FIXME: This should all be refactored into a chain of "summary lookup"
840 // filters.
841 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
842 // FIXES: <rdar://problem/6326900>
843 // This should be addressed using a API table. This strcmp is also
844 // a little gross, but there is no need to super optimize here.
845 assert (ScratchArgs.empty());
846 ScratchArgs.push_back(std::make_pair(1, DecRef));
847 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
848 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000849 }
Ted Kremenek12619382009-01-12 21:45:02 +0000850
851 // Handle: id NSMakeCollectable(CFTypeRef)
852 if (strcmp(FName, "NSMakeCollectable") == 0) {
853 S = (RetTy == Ctx.getObjCIdType())
854 ? getUnarySummary(FT, cfmakecollectable)
855 : getPersistentStopSummary();
856
857 break;
858 }
859
860 if (RetTy->isPointerType()) {
861 // For CoreFoundation ('CF') types.
862 if (isRefType(RetTy, "CF", &Ctx, FName)) {
863 if (isRetain(FD, FName))
864 S = getUnarySummary(FT, cfretain);
865 else if (strstr(FName, "MakeCollectable"))
866 S = getUnarySummary(FT, cfmakecollectable);
867 else
868 S = getCFCreateGetRuleSummary(FD, FName);
869
870 break;
871 }
872
873 // For CoreGraphics ('CG') types.
874 if (isRefType(RetTy, "CG", &Ctx, FName)) {
875 if (isRetain(FD, FName))
876 S = getUnarySummary(FT, cfretain);
877 else
878 S = getCFCreateGetRuleSummary(FD, FName);
879
880 break;
881 }
882
883 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
884 if (isRefType(RetTy, "DADisk") ||
885 isRefType(RetTy, "DADissenter") ||
886 isRefType(RetTy, "DASessionRef")) {
887 S = getCFCreateGetRuleSummary(FD, FName);
888 break;
889 }
890
891 break;
892 }
893
894 // Check for release functions, the only kind of functions that we care
895 // about that don't return a pointer type.
896 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
897 if (isRelease(FD, FName+2))
898 S = getUnarySummary(FT, cfrelease);
899 else {
Ted Kremenek68189282009-01-29 22:45:13 +0000900 assert (ScratchArgs.empty());
901 // Remaining CoreFoundation and CoreGraphics functions.
902 // We use to assume that they all strictly followed the ownership idiom
903 // and that ownership cannot be transferred. While this is technically
904 // correct, many methods allow a tracked object to escape. For example:
905 //
906 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
907 // CFDictionaryAddValue(y, key, x);
908 // CFRelease(x);
909 // ... it is okay to use 'x' since 'y' has a reference to it
910 //
911 // We handle this and similar cases with the follow heuristic. If the
912 // function name contains "InsertValue", "SetValue" or "AddValue" then
913 // we assume that arguments may "escape."
914 //
915 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
916 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +0000917 CStrInCStrNoCase(FName, "SetValue") ||
918 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +0000919 ? MayEscape : DoNothing;
920
921 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +0000922 }
923 }
Ted Kremenek37d785b2008-07-15 16:50:12 +0000924 }
925 while (0);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000926
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000927 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000928 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000929}
930
Ted Kremenek37d785b2008-07-15 16:50:12 +0000931RetainSummary*
932RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
933 const char* FName) {
934
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000935 if (strstr(FName, "Create") || strstr(FName, "Copy"))
936 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000937
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000938 if (strstr(FName, "Get"))
939 return getCFSummaryGetRule(FD);
940
941 return 0;
942}
943
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000944RetainSummary*
Ted Kremenek12619382009-01-12 21:45:02 +0000945RetainSummaryManager::getUnarySummary(FunctionType* FT, UnaryFuncKind func) {
946 // Sanity check that this is *really* a unary function. This can
947 // happen if people do weird things.
948 FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FT);
949 if (!FTP || FTP->getNumArgs() != 1)
950 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000951
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000952 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000953
Ted Kremenek377e2302008-04-29 05:33:51 +0000954 switch (func) {
Ted Kremenek12619382009-01-12 21:45:02 +0000955 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000956 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000957 return getPersistentSummary(RetEffect::MakeAlias(0),
958 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000959 }
960
961 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000962 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000963 return getPersistentSummary(RetEffect::MakeNoRet(),
964 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000965 }
966
967 case cfmakecollectable: {
Ted Kremenek27019002009-02-18 21:57:45 +0000968 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
969 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000970 }
971
972 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000973 assert (false && "Not a supported unary function.");
Ted Kremenek98530452008-08-12 20:41:56 +0000974 return 0;
Ted Kremenek940b1d82008-04-10 23:44:06 +0000975 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000976}
977
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000978RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000979 assert (ScratchArgs.empty());
Ted Kremenek070a8252008-07-09 18:11:16 +0000980
981 if (FD->getIdentifier() == CFDictionaryCreateII) {
982 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
983 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
984 }
985
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000986 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000987}
988
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000989RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000990 assert (ScratchArgs.empty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000991 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
992 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000993}
994
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000995//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000996// Summary creation for Selectors.
997//===----------------------------------------------------------------------===//
998
Ted Kremenek1bffd742008-05-06 15:44:25 +0000999RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001000RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001001 assert(ScratchArgs.empty());
1002
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001003 // 'init' methods only return an alias if the return type is a location type.
1004 QualType T = ME->getType();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001005 RetainSummary* Summ =
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001006 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1007 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001008
Ted Kremenek553cf182008-06-25 21:21:56 +00001009 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001010 return Summ;
1011}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001012
Ted Kremenek553cf182008-06-25 21:21:56 +00001013
Ted Kremenek1bffd742008-05-06 15:44:25 +00001014RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001015RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1016 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001017
1018 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001019
Ted Kremenek553cf182008-06-25 21:21:56 +00001020 // Look up a summary in our summary cache.
1021 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001022
Ted Kremenek1f180c32008-06-23 22:21:20 +00001023 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001024 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001025
Ted Kremenek234a4c22009-01-07 00:39:56 +00001026 // "initXXX": pass-through for receiver.
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001027 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001028 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +00001029
Ted Kremenekb80976c2009-02-21 05:13:43 +00001030 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek234a4c22009-01-07 00:39:56 +00001031 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +00001032
Ted Kremenek234a4c22009-01-07 00:39:56 +00001033 // Look for methods that return an owned object.
1034 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek84060db2008-05-07 04:25:59 +00001035 return 0;
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001036
Ted Kremenek234a4c22009-01-07 00:39:56 +00001037 if (followsFundamentalRule(s)) {
1038 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001039 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001040 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek553cf182008-06-25 21:21:56 +00001041 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek1bffd742008-05-06 15:44:25 +00001042 return Summ;
1043 }
Ted Kremenek1bffd742008-05-06 15:44:25 +00001044
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001045 return 0;
1046}
1047
Ted Kremenekc8395602008-05-06 21:26:51 +00001048RetainSummary*
Ted Kremenek1f180c32008-06-23 22:21:20 +00001049RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1050 Selector S) {
Ted Kremenekc8395602008-05-06 21:26:51 +00001051
Ted Kremenek553cf182008-06-25 21:21:56 +00001052 // FIXME: Eventually we should properly do class method summaries, but
1053 // it requires us being able to walk the type hierarchy. Unfortunately,
1054 // we cannot do this with just an IdentifierInfo* for the class name.
1055
Ted Kremenekc8395602008-05-06 21:26:51 +00001056 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +00001057 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001058
Ted Kremenek1f180c32008-06-23 22:21:20 +00001059 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001060 return I->second;
1061
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00001062 return 0;
Ted Kremenekc8395602008-05-06 21:26:51 +00001063}
1064
Ted Kremenek1f180c32008-06-23 22:21:20 +00001065void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +00001066
1067 assert (ScratchArgs.empty());
1068
Ted Kremeneka7344702008-06-23 18:02:52 +00001069 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001070 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001071
Ted Kremenek9c32d082008-05-06 00:30:21 +00001072 RetainSummary* Summ = getPersistentSummary(E);
1073
Ted Kremenek553cf182008-06-25 21:21:56 +00001074 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1075 // NSObject and its derivatives.
1076 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1077 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1078 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001079
1080 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001081 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001082 GetNullarySelector("currentHandler", Ctx),
1083 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001084
1085 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekabf43972009-01-28 21:44:40 +00001086 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1087 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1088 GetUnarySelector("addObject", Ctx),
1089 getPersistentSummary(RetEffect::MakeNoRet(),
1090 DoNothing, DoNothing));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001091}
1092
Ted Kremenek1f180c32008-06-23 22:21:20 +00001093void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001094
1095 assert (ScratchArgs.empty());
1096
Ted Kremenekc8395602008-05-06 21:26:51 +00001097 // Create the "init" selector. It just acts as a pass-through for the
1098 // receiver.
Ted Kremenek179064e2008-07-01 17:21:27 +00001099 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
1100 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001101
1102 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +00001103 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001104 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001105
Ted Kremenek179064e2008-07-01 17:21:27 +00001106 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +00001107
1108 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001109 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1110
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001111 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001112 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001113
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001114 // Create the "retain" selector.
1115 E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001116 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001117 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001118
1119 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001120 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001121 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001122
1123 // Create the "drain" selector.
1124 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001125 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001126
1127 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001128 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001129 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001130
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001131 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek179064e2008-07-01 17:21:27 +00001132 RetainSummary *NSWindowSumm =
1133 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001134
1135 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1136 "styleMask", "backing", "defer", NULL);
1137
1138 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1139 "styleMask", "backing", "defer", "screen", NULL);
1140
1141 // For NSPanel (which subclasses NSWindow), allocated objects are not
1142 // self-owned.
1143 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1144 "styleMask", "backing", "defer", NULL);
1145
1146 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1147 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001148
Ted Kremenek70a733e2008-07-18 17:24:20 +00001149 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001150 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1151 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001152
Ted Kremenek9e476de2008-08-12 18:30:56 +00001153 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1154 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001155}
1156
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001157//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001158// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001159//===----------------------------------------------------------------------===//
1160
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001161namespace {
1162
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001163class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001164public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001165 enum Kind {
1166 Owned = 0, // Owning reference.
1167 NotOwned, // Reference is not owned by still valid (not freed).
1168 Released, // Object has been released.
1169 ReturnedOwned, // Returned object passes ownership to caller.
1170 ReturnedNotOwned, // Return object does not pass ownership to caller.
1171 ErrorUseAfterRelease, // Object used after released.
1172 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001173 ErrorLeak, // A memory leak due to excessive reference counts.
1174 ErrorLeakReturned // A memory leak due to the returning method not having
1175 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001176 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001177
1178private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001179 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001180 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001181 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001182 QualType T;
1183
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001184 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1185 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001186
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001187 RefVal(Kind k, unsigned cnt = 0)
1188 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1189
1190public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001191 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001192
1193 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001194
Ted Kremenek553cf182008-06-25 21:21:56 +00001195 unsigned getCount() const { return Cnt; }
1196 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001197
1198 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001199
Ted Kremenek73c750b2008-03-11 18:14:09 +00001200 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1201
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001202 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001203
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001204 bool isOwned() const {
1205 return getKind() == Owned;
1206 }
1207
Ted Kremenekdb863712008-04-16 22:32:20 +00001208 bool isNotOwned() const {
1209 return getKind() == NotOwned;
1210 }
1211
Ted Kremenek4fd88972008-04-17 18:12:53 +00001212 bool isReturnedOwned() const {
1213 return getKind() == ReturnedOwned;
1214 }
1215
1216 bool isReturnedNotOwned() const {
1217 return getKind() == ReturnedNotOwned;
1218 }
1219
1220 bool isNonLeakError() const {
1221 Kind k = getKind();
1222 return isError(k) && !isLeak(k);
1223 }
1224
1225 // State creation: normal state.
1226
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001227 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1228 unsigned Count = 1) {
1229 return RefVal(Owned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001230 }
1231
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001232 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1233 unsigned Count = 0) {
1234 return RefVal(NotOwned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001235 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001236
1237 static RefVal makeReturnedOwned(unsigned Count) {
1238 return RefVal(ReturnedOwned, Count);
1239 }
1240
1241 static RefVal makeReturnedNotOwned() {
1242 return RefVal(ReturnedNotOwned);
1243 }
1244
Ted Kremenek4fd88972008-04-17 18:12:53 +00001245 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001246
Ted Kremenek4fd88972008-04-17 18:12:53 +00001247 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001248 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001249 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001250
Ted Kremenek553cf182008-06-25 21:21:56 +00001251 RefVal operator-(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001252 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001253 }
1254
1255 RefVal operator+(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001256 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001257 }
1258
1259 RefVal operator^(Kind k) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001260 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001261 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001262
Ted Kremenek4fd88972008-04-17 18:12:53 +00001263 void Profile(llvm::FoldingSetNodeID& ID) const {
1264 ID.AddInteger((unsigned) kind);
1265 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001266 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001267 }
1268
Ted Kremenekf3948042008-03-11 19:44:10 +00001269 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001270};
Ted Kremenekf3948042008-03-11 19:44:10 +00001271
1272void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001273 if (!T.isNull())
1274 Out << "Tracked Type:" << T.getAsString() << '\n';
1275
Ted Kremenekf3948042008-03-11 19:44:10 +00001276 switch (getKind()) {
1277 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001278 case Owned: {
1279 Out << "Owned";
1280 unsigned cnt = getCount();
1281 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001282 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001283 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001284
Ted Kremenek61b9f872008-04-10 23:09:18 +00001285 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001286 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001287 unsigned cnt = getCount();
1288 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001289 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001290 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001291
Ted Kremenek4fd88972008-04-17 18:12:53 +00001292 case ReturnedOwned: {
1293 Out << "ReturnedOwned";
1294 unsigned cnt = getCount();
1295 if (cnt) Out << " (+ " << cnt << ")";
1296 break;
1297 }
1298
1299 case ReturnedNotOwned: {
1300 Out << "ReturnedNotOwned";
1301 unsigned cnt = getCount();
1302 if (cnt) Out << " (+ " << cnt << ")";
1303 break;
1304 }
1305
Ted Kremenekf3948042008-03-11 19:44:10 +00001306 case Released:
1307 Out << "Released";
1308 break;
1309
Ted Kremenekdb863712008-04-16 22:32:20 +00001310 case ErrorLeak:
1311 Out << "Leaked";
1312 break;
1313
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001314 case ErrorLeakReturned:
1315 Out << "Leaked (Bad naming)";
1316 break;
1317
Ted Kremenekf3948042008-03-11 19:44:10 +00001318 case ErrorUseAfterRelease:
1319 Out << "Use-After-Release [ERROR]";
1320 break;
1321
1322 case ErrorReleaseNotOwned:
1323 Out << "Release of Not-Owned [ERROR]";
1324 break;
1325 }
1326}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001327
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001328} // end anonymous namespace
1329
1330//===----------------------------------------------------------------------===//
1331// RefBindings - State used to track object reference counts.
1332//===----------------------------------------------------------------------===//
1333
Ted Kremenek2dabd432008-12-05 02:27:51 +00001334typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001335static int RefBIndex = 0;
Ted Kremenek33b6f632009-02-19 23:47:02 +00001336static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001337
1338namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001339 template<>
1340 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1341 static inline void* GDMIndex() { return &RefBIndex; }
1342 };
1343}
Ted Kremenek6d348932008-10-21 15:53:15 +00001344
1345//===----------------------------------------------------------------------===//
1346// ARBindings - State used to track objects in autorelease pools.
1347//===----------------------------------------------------------------------===//
1348
Ted Kremenek2dabd432008-12-05 02:27:51 +00001349typedef llvm::ImmutableSet<SymbolRef> ARPoolContents;
1350typedef llvm::ImmutableList< std::pair<SymbolRef, ARPoolContents*> > ARBindings;
Ted Kremenek6d348932008-10-21 15:53:15 +00001351static int AutoRBIndex = 0;
1352
1353namespace clang {
1354 template<>
1355 struct GRStateTrait<ARBindings> : public GRStatePartialTrait<ARBindings> {
1356 static inline void* GDMIndex() { return &AutoRBIndex; }
1357 };
1358}
1359
Ted Kremenek13922612008-04-16 20:40:59 +00001360//===----------------------------------------------------------------------===//
1361// Transfer functions.
1362//===----------------------------------------------------------------------===//
1363
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001364namespace {
1365
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001366class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001367public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001368 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001369 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001370 virtual void Print(std::ostream& Out, const GRState* state,
1371 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001372 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001373
1374private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001375 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1376 SummaryLogTy;
1377
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001378 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001379 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001380 const LangOptions& LOpts;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001381
Ted Kremenekcf701772009-02-05 06:50:21 +00001382 BugType *useAfterRelease, *releaseNotOwned;
1383 BugType *leakWithinFunction, *leakAtReturn;
1384 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001385
Ted Kremenek2dabd432008-12-05 02:27:51 +00001386 RefBindings Update(RefBindings B, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001387 RefVal::Kind& hasErr, RefBindings::Factory& RefBFactory);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001388
Ted Kremenek2dabd432008-12-05 02:27:51 +00001389 RefVal::Kind& Update(GRStateRef& state, SymbolRef sym, RefVal V,
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001390 ArgEffect E, RefVal::Kind& hasErr) {
1391
1392 state = state.set<RefBindings>(Update(state.get<RefBindings>(), sym, V,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001393 E, hasErr,
1394 state.get_context<RefBindings>()));
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001395 return hasErr;
1396 }
1397
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001398 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1399 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001400 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001401 ExplodedNode<GRState>* Pred,
1402 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001403 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001404
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001405 std::pair<GRStateRef, bool>
1406 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001407 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenekdb863712008-04-16 22:32:20 +00001408
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001409public:
Ted Kremenek13922612008-04-16 20:40:59 +00001410
Ted Kremenek78d46242008-07-22 16:21:24 +00001411 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001412 : Summaries(Ctx, gcenabled),
Ted Kremenekcf701772009-02-05 06:50:21 +00001413 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1414 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001415
Ted Kremenekcf701772009-02-05 06:50:21 +00001416 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001417
Ted Kremenekcf118d42009-02-04 23:49:09 +00001418 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001419
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001420 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1421 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001422 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001423
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001424 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001425 const LangOptions& getLangOptions() const { return LOpts; }
1426
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001427 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1428 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1429 return I == SummaryLog.end() ? 0 : I->second;
1430 }
1431
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001432 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001433
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001434 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001435 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001436 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001437 Expr* Ex,
1438 Expr* Receiver,
1439 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001440 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001441 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001442
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001443 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001444 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001445 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001446 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001447 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001448
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001449
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001450 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001451 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001452 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001453 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001454 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001455
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001456 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001457 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001458 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001459 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001460 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001461
Ted Kremenek41573eb2009-02-14 01:43:44 +00001462 // Stores.
1463 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1464
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001465 // End-of-path.
1466
1467 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001468 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001469
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001470 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001471 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001472 GRStmtNodeBuilder<GRState>& Builder,
1473 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001474 Stmt* S, const GRState* state,
1475 SymbolReaper& SymReaper);
1476
Ted Kremenek4fd88972008-04-17 18:12:53 +00001477 // Return statements.
1478
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001479 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001480 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001481 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001482 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001483 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001484
1485 // Assumptions.
1486
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001487 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001488 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001489 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001490};
1491
1492} // end anonymous namespace
1493
Ted Kremenek8dd56462008-04-18 03:39:05 +00001494
Ted Kremenekae6814e2008-08-13 21:24:49 +00001495void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1496 const char* nl, const char* sep) {
1497
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001498 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001499
Ted Kremenekae6814e2008-08-13 21:24:49 +00001500 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001501 Out << sep << nl;
1502
1503 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1504 Out << (*I).first << " : ";
1505 (*I).second.print(Out);
1506 Out << nl;
1507 }
1508}
1509
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001510static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001511 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001512}
1513
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001514static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1515 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001516}
1517
Ted Kremenek14993892008-05-06 02:41:27 +00001518static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1519 return Summ ? Summ->getReceiverEffect() : DoNothing;
1520}
1521
Ted Kremenek70a733e2008-07-18 17:24:20 +00001522static inline bool IsEndPath(RetainSummary* Summ) {
1523 return Summ ? Summ->isEndPath() : false;
1524}
1525
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001526
Ted Kremenek553cf182008-06-25 21:21:56 +00001527/// GetReturnType - Used to get the return type of a message expression or
1528/// function call with the intention of affixing that type to a tracked symbol.
1529/// While the the return type can be queried directly from RetEx, when
1530/// invoking class methods we augment to the return type to be that of
1531/// a pointer to the class (as opposed it just being id).
1532static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1533
1534 QualType RetTy = RetE->getType();
1535
1536 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00001537 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001538 if (!PT)
1539 return RetTy;
1540
1541 // If RetEx is not a message expression just return its type.
1542 // If RetEx is a message expression, return its types if it is something
1543 /// more specific than id.
1544
1545 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1546
Steve Naroff389bf462009-02-12 17:52:19 +00001547 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00001548 return RetTy;
1549
1550 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1551
1552 // At this point we know the return type of the message expression is id.
1553 // If we have an ObjCInterceDecl, we know this is a call to a class method
1554 // whose type we can resolve. In such cases, promote the return type to
1555 // Class*.
1556 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1557}
1558
1559
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001560void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001561 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001562 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001563 Expr* Ex,
1564 Expr* Receiver,
1565 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001566 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001567 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001568
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001569 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001570 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001571 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00001572
1573 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001574 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001575 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001576 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00001577 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001578
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001579 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001580 SVal V = state.GetSVal(*I);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001581
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001582 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001583 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001584 if (RefBindings::data_type* T = state.get<RefBindings>(Sym))
1585 if (Update(state, Sym, *T, GetArgE(Summ, idx), hasErr)) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001586 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001587 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001588 break;
1589 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001590 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001591 else if (isa<Loc>(V)) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001592 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek070a8252008-07-09 18:11:16 +00001593
1594 if (GetArgE(Summ, idx) == DoNothingByRef)
1595 continue;
1596
1597 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001598
1599 // FIXME: Either this logic should also be replicated in GRSimpleVals
1600 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00001601
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001602 // FIXME: We can have collisions on the conjured symbol if the
1603 // expression *I also creates conjured symbols. We probably want
1604 // to identify conjured symbols by an expression pair: the enclosing
1605 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00001606 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00001607
Ted Kremenek993f1c72008-10-17 20:28:54 +00001608 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek90b32362008-12-17 19:42:34 +00001609
1610 // Blast through AnonTypedRegions to get the original region type.
1611 while (R) {
1612 const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R);
1613 if (!ATR) break;
1614 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1615 }
1616
Ted Kremenek9e240492008-10-04 05:50:14 +00001617 if (R) {
Ted Kremenek40e86d92008-12-18 23:34:57 +00001618
1619 // Is the invalidated variable something that we were tracking?
1620 SVal X = state.GetSVal(Loc::MakeVal(R));
1621
1622 if (isa<loc::SymbolVal>(X)) {
1623 SymbolRef Sym = cast<loc::SymbolVal>(X).getSymbol();
1624 state = state.remove<RefBindings>(Sym);
1625 }
1626
Ted Kremenek9e240492008-10-04 05:50:14 +00001627 // Set the value of the variable to be a conjured symbol.
1628 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek6eddeb12008-12-13 21:49:13 +00001629 QualType T = R->getRValueType(Ctx);
Ted Kremenek9e240492008-10-04 05:50:14 +00001630
Ted Kremenekfd301942008-10-17 22:23:12 +00001631 // FIXME: handle structs.
Ted Kremenek062e2f92008-11-13 06:10:40 +00001632 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001633 SymbolRef NewSym =
Ted Kremenekfd301942008-10-17 22:23:12 +00001634 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1635
Ted Kremenek90b32362008-12-17 19:42:34 +00001636 state = state.BindLoc(Loc::MakeVal(R),
Ted Kremenekfd301942008-10-17 22:23:12 +00001637 Loc::IsLocType(T)
1638 ? cast<SVal>(loc::SymbolVal(NewSym))
1639 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1640 }
1641 else {
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001642 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenekfd301942008-10-17 22:23:12 +00001643 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001644 }
1645 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001646 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001647 }
1648 else {
1649 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001650 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001651 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001652 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001653 else if (isa<nonloc::LocAsInteger>(V))
1654 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001655 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001656
Ted Kremenek553cf182008-06-25 21:21:56 +00001657 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001658 if (!ErrorExpr && Receiver) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001659 SVal V = state.GetSVal(Receiver);
1660 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001661 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001662 if (const RefVal* T = state.get<RefBindings>(Sym))
1663 if (Update(state, Sym, *T, GetReceiverE(Summ), hasErr)) {
Ted Kremenek14993892008-05-06 02:41:27 +00001664 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001665 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00001666 }
Ted Kremenek14993892008-05-06 02:41:27 +00001667 }
1668 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001669
Ted Kremenek553cf182008-06-25 21:21:56 +00001670 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001671 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001672 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001673 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001674 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001675 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001676
Ted Kremenek70a733e2008-07-18 17:24:20 +00001677 // Consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001678 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001679
1680 switch (RE.getKind()) {
1681 default:
1682 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001683
Ted Kremenekfd301942008-10-17 22:23:12 +00001684 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001685
Ted Kremenekf9561e52008-04-11 20:23:24 +00001686 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001687 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1688 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001689
Ted Kremenekfd301942008-10-17 22:23:12 +00001690 // FIXME: We eventually should handle structs and other compound types
1691 // that are returned by value.
1692
1693 QualType T = Ex->getType();
1694
Ted Kremenek062e2f92008-11-13 06:10:40 +00001695 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001696 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001697 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001698
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001699 SVal X = Loc::IsLocType(T)
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001700 ? cast<SVal>(loc::SymbolVal(Sym))
1701 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenekf9561e52008-04-11 20:23:24 +00001702
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001703 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001704 }
1705
Ted Kremenek940b1d82008-04-10 23:44:06 +00001706 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00001707 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001708
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001709 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001710 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001711 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001712 assert (idx < (unsigned) (arg_end - arg_beg));
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001713 SVal V = state.GetSVal(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001714 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001715 break;
1716 }
1717
Ted Kremenek14993892008-05-06 02:41:27 +00001718 case RetEffect::ReceiverAlias: {
1719 assert (Receiver);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001720 SVal V = state.GetSVal(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001721 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00001722 break;
1723 }
1724
Ted Kremeneka7344702008-06-23 18:02:52 +00001725 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001726 case RetEffect::OwnedSymbol: {
1727 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001728 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001729 QualType RetT = GetReturnType(Ex, Eng.getContext());
1730 state =
1731 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001732 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001733
Ted Kremeneka7344702008-06-23 18:02:52 +00001734 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00001735 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1736 bool isFeasible;
1737 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1738 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1739 }
Ted Kremeneka7344702008-06-23 18:02:52 +00001740
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001741 break;
1742 }
1743
1744 case RetEffect::NotOwnedSymbol: {
1745 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001746 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek553cf182008-06-25 21:21:56 +00001747 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001748
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001749 state =
1750 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001751 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001752 break;
1753 }
1754 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001755
Ted Kremenekf5b34b12009-02-18 02:00:25 +00001756 // Generate a sink node if we are at the end of a path.
1757 GRExprEngine::NodeTy *NewNode =
1758 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1759 : Builder.MakeNode(Dst, Ex, Pred, state);
1760
1761 // Annotate the edge with summary we used.
1762 // FIXME: This assumes that we always use the same summary when generating
1763 // this node.
1764 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001765}
1766
1767
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001768void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001769 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001770 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001771 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001772 ExplodedNode<GRState>* Pred) {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001773
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001774 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1775 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001776
1777 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1778 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001779}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001780
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001781void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001782 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001783 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001784 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001785 ExplodedNode<GRState>* Pred) {
Ted Kremenekb3095252008-05-06 04:20:12 +00001786 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001787
Ted Kremenek553cf182008-06-25 21:21:56 +00001788 if (Expr* Receiver = ME->getReceiver()) {
1789 // We need the type-information of the tracked receiver object
1790 // Retrieve it from the state.
1791 ObjCInterfaceDecl* ID = 0;
1792
1793 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1794 // a chain of lookups.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001795 const GRState* St = Builder.GetState(Pred);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001796 SVal V = Eng.getStateManager().GetSVal(St, Receiver );
Ted Kremenek553cf182008-06-25 21:21:56 +00001797
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001798 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001799 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek553cf182008-06-25 21:21:56 +00001800
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001801 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001802 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001803
1804 if (const PointerType* PT = Ty->getAsPointerType()) {
1805 QualType PointeeTy = PT->getPointeeType();
1806
1807 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1808 ID = IT->getDecl();
1809 }
1810 }
1811 }
1812
1813 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001814
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001815 // Special-case: are we sending a mesage to "self"?
1816 // This is a hack. When we have full-IP this should be removed.
1817 if (!Summ) {
1818 ObjCMethodDecl* MD =
1819 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1820
1821 if (MD) {
1822 if (Expr* Receiver = ME->getReceiver()) {
1823 SVal X = Eng.getStateManager().GetSVal(St, Receiver);
1824 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001825 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1826 // Create a summmary where all of the arguments "StopTracking".
1827 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1828 DoNothing,
1829 StopTracking);
1830 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001831 }
1832 }
1833 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001834 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001835 else
Ted Kremenek1f180c32008-06-23 22:21:20 +00001836 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1837 ME->getSelector());
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001838
Ted Kremenekb3095252008-05-06 04:20:12 +00001839 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1840 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001841}
Ted Kremenek5216ad72009-02-14 03:16:10 +00001842
1843namespace {
1844class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1845 GRStateRef state;
1846public:
1847 StopTrackingCallback(GRStateRef st) : state(st) {}
1848 GRStateRef getState() { return state; }
1849
1850 bool VisitSymbol(SymbolRef sym) {
1851 state = state.remove<RefBindings>(sym);
1852 return true;
1853 }
Ted Kremenekb3095252008-05-06 04:20:12 +00001854
Ted Kremenek5216ad72009-02-14 03:16:10 +00001855 const GRState* getState() const { return state.getState(); }
1856};
1857} // end anonymous namespace
1858
1859
Ted Kremenek41573eb2009-02-14 01:43:44 +00001860void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001861 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00001862 bool escapes = false;
1863
Ted Kremeneka496d162008-10-18 03:49:51 +00001864 // A value escapes in three possible cases (this may change):
1865 //
1866 // (1) we are binding to something that is not a memory region.
1867 // (2) we are binding to a memregion that does not have stack storage
1868 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00001869 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00001870 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00001871
Ted Kremenek41573eb2009-02-14 01:43:44 +00001872 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00001873 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00001874 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001875 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1876 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00001877
1878 if (!escapes) {
1879 // To test (3), generate a new state with the binding removed. If it is
1880 // the same state, then it escapes (since the store cannot represent
1881 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00001882 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00001883 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001884 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00001885
Ted Kremenek5216ad72009-02-14 03:16:10 +00001886 // If our store can represent the binding and we aren't storing to something
1887 // that doesn't have local storage then just return and have the simulation
1888 // state continue as is.
1889 if (!escapes)
1890 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00001891
Ted Kremenek5216ad72009-02-14 03:16:10 +00001892 // Otherwise, find all symbols referenced by 'val' that we are tracking
1893 // and stop tracking them.
1894 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00001895}
1896
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001897std::pair<GRStateRef,bool>
1898CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1899 const GRState* St, const Decl* CD,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001900 SymbolRef sid,
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001901 RefVal V, bool& hasLeak) {
Ted Kremenekdb863712008-04-16 22:32:20 +00001902
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001903 GRStateRef state(St, VMgr);
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001904 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001905 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001906
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001907 if (V.isReturnedOwned() && V.getCount() == 0)
1908 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00001909 std::string s = MD->getSelector().getAsString();
Ted Kremenek4c79e552008-11-05 16:54:44 +00001910 if (!followsReturnRule(s.c_str())) {
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001911 hasLeak = true;
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001912 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
1913 return std::make_pair(state, true);
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001914 }
1915 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001916
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001917 // All other cases.
1918
1919 hasLeak = V.isOwned() ||
1920 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001921
Ted Kremenekdb863712008-04-16 22:32:20 +00001922 if (!hasLeak)
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001923 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001924
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001925 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
1926 false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001927}
1928
Ted Kremenek652adc62008-04-24 23:57:27 +00001929
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001930
Ted Kremenek652adc62008-04-24 23:57:27 +00001931// Dead symbols.
1932
Ted Kremenekcf701772009-02-05 06:50:21 +00001933
Ted Kremenek652adc62008-04-24 23:57:27 +00001934
Ted Kremenek4fd88972008-04-17 18:12:53 +00001935 // Return statements.
1936
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001937void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001938 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001939 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001940 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001941 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001942
1943 Expr* RetE = S->getRetValue();
1944 if (!RetE) return;
1945
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001946 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001947 SVal V = state.GetSVal(RetE);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001948
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001949 if (!isa<loc::SymbolVal>(V))
Ted Kremenek4fd88972008-04-17 18:12:53 +00001950 return;
1951
1952 // Get the reference count binding (if any).
Ted Kremenek2dabd432008-12-05 02:27:51 +00001953 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001954 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001955
1956 if (!T)
1957 return;
1958
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001959 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001960 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001961
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001962 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001963 case RefVal::Owned: {
1964 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001965 assert (cnt > 0);
1966 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001967 break;
1968 }
1969
1970 case RefVal::NotOwned: {
1971 unsigned cnt = X.getCount();
1972 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1973 : RefVal::makeReturnedNotOwned();
1974 break;
1975 }
1976
1977 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001978 return;
1979 }
1980
1981 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001982 state = state.set<RefBindings>(Sym, X);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001983 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001984}
1985
Ted Kremenekcb612922008-04-18 19:23:43 +00001986// Assumptions.
1987
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001988const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
1989 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001990 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00001991 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00001992
1993 // FIXME: We may add to the interface of EvalAssume the list of symbols
1994 // whose assumptions have changed. For now we just iterate through the
1995 // bindings and check if any of the tracked symbols are NULL. This isn't
1996 // too bad since the number of symbols we will track in practice are
1997 // probably small and EvalAssume is only called at branches and a few
1998 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001999 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002000
2001 if (B.isEmpty())
2002 return St;
2003
2004 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002005
2006 GRStateRef state(St, VMgr);
2007 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002008
2009 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002010 // Check if the symbol is null (or equal to any constant).
2011 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00002012 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002013 changed = true;
2014 B = RefBFactory.Remove(B, I.getKey());
2015 }
2016 }
2017
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002018 if (changed)
2019 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00002020
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002021 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00002022}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002023
Ted Kremenek2dabd432008-12-05 02:27:51 +00002024RefBindings CFRefCount::Update(RefBindings B, SymbolRef sym,
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002025 RefVal V, ArgEffect E,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002026 RefVal::Kind& hasErr,
2027 RefBindings::Factory& RefBFactory) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00002028
2029 // In GC mode [... release] and [... retain] do nothing.
2030 switch (E) {
2031 default: break;
2032 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2033 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00002034 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002035 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002036
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002037 switch (E) {
2038 default:
2039 assert (false && "Unhandled CFRef transition.");
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002040
2041 case MayEscape:
2042 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002043 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002044 break;
2045 }
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002046 // Fall-through.
Ted Kremenek070a8252008-07-09 18:11:16 +00002047 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002048 case DoNothing:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002049 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002050 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002051 hasErr = V.getKind();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002052 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002053 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002054 return B;
Ted Kremeneke19f4492008-06-30 16:57:41 +00002055
Ted Kremenekabf43972009-01-28 21:44:40 +00002056 case Autorelease:
2057 if (isGCEnabled()) return B;
2058 // Fall-through.
Ted Kremenek14993892008-05-06 02:41:27 +00002059 case StopTracking:
2060 return RefBFactory.Remove(B, sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002061
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002062 case IncRef:
2063 switch (V.getKind()) {
2064 default:
2065 assert(false);
2066
2067 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002068 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00002069 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002070 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002071 case RefVal::Released:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002072 if (isGCEnabled())
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002073 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek65c91652008-04-29 05:44:10 +00002074 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002075 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek65c91652008-04-29 05:44:10 +00002076 hasErr = V.getKind();
2077 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002078 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002079 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002080 break;
2081
Ted Kremenek553cf182008-06-25 21:21:56 +00002082 case SelfOwn:
2083 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002084 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002085 case DecRef:
2086 switch (V.getKind()) {
2087 default:
2088 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002089
Ted Kremenek553cf182008-06-25 21:21:56 +00002090 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002091 assert(V.getCount() > 0);
2092 if (V.getCount() == 1) V = V ^ RefVal::Released;
2093 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002094 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002095
Ted Kremenek553cf182008-06-25 21:21:56 +00002096 case RefVal::NotOwned:
2097 if (V.getCount() > 0)
2098 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00002099 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002100 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002101 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00002102 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002103 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002104
2105 case RefVal::Released:
Ted Kremenek553cf182008-06-25 21:21:56 +00002106 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002107 hasErr = V.getKind();
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002108 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002109 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002110 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002111 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002112 return RefBFactory.Add(B, sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002113}
2114
Ted Kremenekfa34b332008-04-09 01:10:13 +00002115//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002116// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00002117//===----------------------------------------------------------------------===//
2118
Ted Kremenek8dd56462008-04-18 03:39:05 +00002119namespace {
2120
2121 //===-------------===//
2122 // Bug Descriptions. //
2123 //===-------------===//
2124
Ted Kremenekcf118d42009-02-04 23:49:09 +00002125 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002126 protected:
2127 CFRefCount& TF;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002128
2129 CFRefBug(CFRefCount* tf, const char* name)
2130 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002131 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002132
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002133 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00002134 const CFRefCount& getTF() const { return TF; }
2135
Ted Kremenekcf118d42009-02-04 23:49:09 +00002136 // FIXME: Eventually remove.
2137 virtual const char* getDescription() const = 0;
2138
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002139 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002140 };
2141
2142 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2143 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002144 UseAfterRelease(CFRefCount* tf)
2145 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002146
Ted Kremenekcf118d42009-02-04 23:49:09 +00002147 const char* getDescription() const {
Ted Kremenek9e476de2008-08-12 18:30:56 +00002148 return "Reference-counted object is used after it is released.";
Ted Kremenekcf701772009-02-05 06:50:21 +00002149 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002150 };
2151
2152 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2153 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002154 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2155
2156 const char* getDescription() const {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002157 return "Incorrect decrement of the reference count of a "
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002158 "CoreFoundation object: "
Ted Kremenek8dd56462008-04-18 03:39:05 +00002159 "The object is not owned at this point by the caller.";
2160 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002161 };
2162
2163 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002164 const bool isReturn;
2165 protected:
2166 Leak(CFRefCount* tf, const char* name, bool isRet)
2167 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002168 public:
Ted Kremenek8dd56462008-04-18 03:39:05 +00002169
Ted Kremenekd3057212009-02-07 22:38:00 +00002170 const char* getDescription() const { return ""; }
Ted Kremenek3148eb42009-01-24 00:55:43 +00002171
Ted Kremeneke45e57f2009-02-05 00:38:00 +00002172 bool isLeak() const { return true; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002173 };
Ted Kremenekcf118d42009-02-04 23:49:09 +00002174
2175 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2176 public:
2177 LeakAtReturn(CFRefCount* tf, const char* name)
2178 : Leak(tf, name, true) {}
2179 };
2180
2181 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2182 public:
2183 LeakWithinFunction(CFRefCount* tf, const char* name)
2184 : Leak(tf, name, false) {}
2185 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002186
2187 //===---------===//
2188 // Bug Reports. //
2189 //===---------===//
2190
2191 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek66d97062009-02-07 22:04:05 +00002192 protected:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002193 SymbolRef Sym;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002194 const CFRefCount &TF;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002195 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002196 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2197 ExplodedNode<GRState> *n, SymbolRef sym)
2198 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002199
2200 virtual ~CFRefReport() {}
2201
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002202 CFRefBug& getBugType() {
2203 return (CFRefBug&) RangedBugReport::getBugType();
2204 }
2205 const CFRefBug& getBugType() const {
2206 return (const CFRefBug&) RangedBugReport::getBugType();
2207 }
2208
2209 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2210 const SourceRange*& end) {
2211
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002212 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002213 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002214 else
2215 beg = end = 0;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002216 }
2217
Ted Kremenek2dabd432008-12-05 02:27:51 +00002218 SymbolRef getSymbol() const { return Sym; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002219
Ted Kremenek3148eb42009-01-24 00:55:43 +00002220 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2221 const ExplodedNode<GRState>* N);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002222
Ted Kremenek3148eb42009-01-24 00:55:43 +00002223 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002224
Ted Kremenek3148eb42009-01-24 00:55:43 +00002225 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2226 const ExplodedNode<GRState>* PrevN,
2227 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002228 BugReporter& BR,
2229 NodeResolver& NR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002230 };
2231
Ted Kremenekcf118d42009-02-04 23:49:09 +00002232 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremeneke469fa02009-02-07 22:19:59 +00002233 SourceLocation AllocSite;
2234 const MemRegion* AllocBinding;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002235 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002236 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2237 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenekd3057212009-02-07 22:38:00 +00002238 GRExprEngine& Eng);
Ted Kremenek66d97062009-02-07 22:04:05 +00002239
2240 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2241 const ExplodedNode<GRState>* N);
2242
Ted Kremeneke469fa02009-02-07 22:19:59 +00002243 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekcf118d42009-02-04 23:49:09 +00002244 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002245} // end anonymous namespace
2246
Ted Kremenekcf118d42009-02-04 23:49:09 +00002247void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenekcf701772009-02-05 06:50:21 +00002248 useAfterRelease = new UseAfterRelease(this);
2249 BR.Register(useAfterRelease);
2250
2251 releaseNotOwned = new BadRelease(this);
2252 BR.Register(releaseNotOwned);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002253
2254 // First register "return" leaks.
2255 const char* name = 0;
2256
2257 if (isGCEnabled())
2258 name = "[naming convention] leak of returned object (GC)";
2259 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2260 name = "[naming convention] leak of returned object (hybrid MM, "
2261 "non-GC)";
2262 else {
2263 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2264 name = "[naming convention] leak of returned object";
2265 }
2266
Ted Kremenekcf701772009-02-05 06:50:21 +00002267 leakAtReturn = new LeakAtReturn(this, name);
2268 BR.Register(leakAtReturn);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002269
Ted Kremenekcf118d42009-02-04 23:49:09 +00002270 // Second, register leaks within a function/method.
2271 if (isGCEnabled())
2272 name = "leak (GC)";
2273 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2274 name = "leak (hybrid MM, non-GC)";
2275 else {
2276 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2277 name = "leak";
2278 }
2279
Ted Kremenekcf701772009-02-05 06:50:21 +00002280 leakWithinFunction = new LeakWithinFunction(this, name);
2281 BR.Register(leakWithinFunction);
2282
2283 // Save the reference to the BugReporter.
2284 this->BR = &BR;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002285}
Ted Kremenek072192b2008-04-30 23:47:44 +00002286
2287static const char* Msgs[] = {
2288 "Code is compiled in garbage collection only mode" // GC only
2289 " (the bug occurs with garbage collection enabled).",
2290
2291 "Code is compiled without garbage collection.", // No GC.
2292
2293 "Code is compiled for use with and without garbage collection (GC)."
2294 " The bug occurs with GC enabled.", // Hybrid, with GC.
2295
2296 "Code is compiled for use with and without garbage collection (GC)."
2297 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2298};
2299
2300std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2301 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2302
2303 switch (TF.getLangOptions().getGCMode()) {
2304 default:
2305 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002306
2307 case LangOptions::GCOnly:
2308 assert (TF.isGCEnabled());
Ted Kremenek9e476de2008-08-12 18:30:56 +00002309 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2310
Ted Kremenek072192b2008-04-30 23:47:44 +00002311 case LangOptions::NonGC:
2312 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002313 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2314
2315 case LangOptions::HybridGC:
2316 if (TF.isGCEnabled())
2317 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2318 else
2319 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2320 }
2321}
2322
Ted Kremenek27019002009-02-18 21:57:45 +00002323static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2324 ArgEffect X) {
2325 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2326 I!=E; ++I)
2327 if (*I == X) return true;
2328
2329 return false;
2330}
2331
Ted Kremenek3148eb42009-01-24 00:55:43 +00002332PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2333 const ExplodedNode<GRState>* PrevN,
2334 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002335 BugReporter& BR,
2336 NodeResolver& NR) {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002337
Ted Kremenek611a15a2009-01-28 05:29:13 +00002338 // Check if the type state has changed.
2339 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2340 GRStateRef PrevSt(PrevN->getState(), StMgr);
2341 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek20982802009-01-28 05:06:46 +00002342
Ted Kremenek611a15a2009-01-28 05:29:13 +00002343 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2344 if (!CurrT) return NULL;
2345
2346 const RefVal& CurrV = *CurrT;
2347 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenekce48e002008-05-05 17:53:17 +00002348
Ted Kremenek27019002009-02-18 21:57:45 +00002349 // Create a string buffer to constain all the useful things we want
2350 // to tell the user.
2351 std::string sbuf;
2352 llvm::raw_string_ostream os(sbuf);
2353
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002354 // This is the allocation site since the previous node had no bindings
2355 // for this symbol.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002356 if (!PrevT) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002357 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2358
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002359 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2360 // Get the name of the callee (if it is available).
2361 SVal X = CurrSt.GetSVal(CE->getCallee());
2362 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2363 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2364 else
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002365 os << "function call";
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002366 }
2367 else {
2368 assert (isa<ObjCMessageExpr>(S));
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002369 os << "Method";
Ted Kremenekce48e002008-05-05 17:53:17 +00002370 }
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002371
Ted Kremenek961b61d2009-01-28 06:06:36 +00002372 if (CurrV.getObjKind() == RetEffect::CF) {
2373 os << " returns a Core Foundation object with a ";
2374 }
2375 else {
2376 assert (CurrV.getObjKind() == RetEffect::ObjC);
2377 os << " returns an Objective-C object with a ";
2378 }
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002379
Ted Kremenek23b8eaa2009-01-28 06:25:48 +00002380 if (CurrV.isOwned()) {
2381 os << "+1 retain count (owning reference).";
2382
2383 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2384 assert(CurrV.getObjKind() == RetEffect::CF);
2385 os << " "
2386 "Core Foundation objects are not automatically garbage collected.";
2387 }
2388 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002389 else {
2390 assert (CurrV.isNotOwned());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002391 os << "+0 retain count (non-owning reference).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002392 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002393
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002394 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002395 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002396
2397 if (Expr* Exp = dyn_cast<Expr>(S))
2398 P->addRange(Exp->getSourceRange());
2399
2400 return P;
2401 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002402
Ted Kremenek27019002009-02-18 21:57:45 +00002403 // Gather up the effects that were performed on the object at this
2404 // program point
2405 llvm::SmallVector<ArgEffect, 2> AEffects;
2406
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002407 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2408 // We only have summaries attached to nodes after evaluating CallExpr and
2409 // ObjCMessageExprs.
2410 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2411
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002412 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2413 // Iterate through the parameter expressions and see if the symbol
2414 // was ever passed as an argument.
2415 unsigned i = 0;
2416
2417 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2418 AI!=AE; ++AI, ++i) {
Ted Kremenek27019002009-02-18 21:57:45 +00002419
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002420 // Retrieve the value of the arugment.
2421 SVal X = CurrSt.GetSVal(*AI);
Ted Kremenek27019002009-02-18 21:57:45 +00002422
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002423 // Is it the symbol we're interested in?
2424 if (!isa<loc::SymbolVal>(X) ||
2425 Sym != cast<loc::SymbolVal>(X).getSymbol())
2426 continue;
Ted Kremenek79c140b2008-04-18 05:32:44 +00002427
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002428 // We have an argument. Get the effect!
2429 AEffects.push_back(Summ->getArg(i));
Ted Kremenek79c140b2008-04-18 05:32:44 +00002430 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002431 }
2432 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2433 if (Expr *receiver = ME->getReceiver()) {
Ted Kremenek27019002009-02-18 21:57:45 +00002434 SVal RetV = CurrSt.GetSVal(receiver);
2435 if (isa<loc::SymbolVal>(RetV) &&
2436 Sym == cast<loc::SymbolVal>(RetV).getSymbol()) {
2437 // The symbol we are tracking is the receiver.
2438 AEffects.push_back(Summ->getReceiverEffect());
2439 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002440 }
2441 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002442 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002443
Ted Kremenek27019002009-02-18 21:57:45 +00002444 do {
2445 // Get the previous type state.
2446 RefVal PrevV = *PrevT;
2447
2448 // Specially handle CFMakeCollectable and friends.
2449 if (contains(AEffects, MakeCollectable)) {
2450 // Get the name of the function.
2451 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2452 loc::FuncVal FV =
2453 cast<loc::FuncVal>(CurrSt.GetSVal(cast<CallExpr>(S)->getCallee()));
2454 const std::string& FName = FV.getDecl()->getNameAsString();
2455
2456 if (TF.isGCEnabled()) {
2457 // Determine if the object's reference count was pushed to zero.
2458 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2459
2460 os << "In GC mode a call to '" << FName
2461 << "' decrements an object's retain count and registers the "
2462 "object with the garbage collector. ";
2463
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002464 if (CurrV.getKind() == RefVal::Released) {
2465 assert(CurrV.getCount() == 0);
2466 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek27019002009-02-18 21:57:45 +00002467 "automatically collected by the garbage collector.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002468 }
Ted Kremenek27019002009-02-18 21:57:45 +00002469 else
2470 os << "An object must have a 0 retain count to be garbage collected. "
2471 "After this call its retain count is +" << CurrV.getCount()
2472 << '.';
2473 }
2474 else
2475 os << "When GC is not enabled a call to '" << FName
2476 << "' has no effect on its argument.";
2477
2478 // Nothing more to say.
2479 break;
2480 }
2481
2482 // Determine if the typestate has changed.
2483 if (!(PrevV == CurrV))
2484 switch (CurrV.getKind()) {
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002485 case RefVal::Owned:
2486 case RefVal::NotOwned:
2487
2488 if (PrevV.getCount() == CurrV.getCount())
2489 return 0;
2490
2491 if (PrevV.getCount() > CurrV.getCount())
2492 os << "Reference count decremented.";
2493 else
2494 os << "Reference count incremented.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002495
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002496 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002497 os << " The object now has +" << Count;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002498
2499 if (Count > 1)
2500 os << " retain counts.";
2501 else
2502 os << " retain count.";
2503 }
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002504
2505 if (PrevV.getKind() == RefVal::Released) {
2506 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2507 os << " The object is not eligible for garbage collection until the "
2508 "retain count reaches 0 again.";
2509 }
2510
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002511 break;
2512
2513 case RefVal::Released:
2514 os << "Object released.";
2515 break;
2516
2517 case RefVal::ReturnedOwned:
2518 os << "Object returned to caller as an owning reference (single retain "
2519 "count transferred to caller).";
2520 break;
2521
2522 case RefVal::ReturnedNotOwned:
2523 os << "Object returned to caller with a +0 (non-owning) retain count.";
2524 break;
2525
2526 default:
2527 return NULL;
Ted Kremenek27019002009-02-18 21:57:45 +00002528 }
2529
2530 // Emit any remaining diagnostics for the argument effects (if any).
2531 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2532 E=AEffects.end(); I != E; ++I) {
2533
2534 // A bunch of things have alternate behavior under GC.
2535 if (TF.isGCEnabled())
2536 switch (*I) {
2537 default: break;
2538 case Autorelease:
2539 os << "In GC mode an 'autorelease' has no effect.";
2540 continue;
2541 case IncRefMsg:
2542 os << "In GC mode the 'retain' message has no effect.";
2543 continue;
2544 case DecRefMsg:
2545 os << "In GC mode the 'release' message has no effect.";
2546 continue;
2547 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002548 }
Ted Kremenek27019002009-02-18 21:57:45 +00002549 } while(0);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002550
2551 if (os.str().empty())
2552 return 0; // We have nothing to say!
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002553
2554 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2555 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002556 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002557
2558 // Add the range by scanning the children of the statement for any bindings
2559 // to Sym.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002560 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2561 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek20982802009-01-28 05:06:46 +00002562 SVal X = CurrSt.GetSVal(Exp);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002563 if (loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&X))
Ted Kremenek1f62ef32009-02-18 22:17:20 +00002564 if (SV->getSymbol() == Sym) {
2565 P->addRange(Exp->getSourceRange());
2566 break;
2567 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002568 }
2569
2570 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002571}
2572
Ted Kremenek9e240492008-10-04 05:50:14 +00002573namespace {
2574class VISIBILITY_HIDDEN FindUniqueBinding :
2575 public StoreManager::BindingsHandler {
Ted Kremenek2dabd432008-12-05 02:27:51 +00002576 SymbolRef Sym;
Ted Kremenek9e240492008-10-04 05:50:14 +00002577 MemRegion* Binding;
2578 bool First;
2579
2580 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002581 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenek9e240492008-10-04 05:50:14 +00002582
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002583 bool HandleBinding(StoreManager& SMgr, Store store, MemRegion* R, SVal val) {
2584 if (const loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002585 if (SV->getSymbol() != Sym)
2586 return true;
2587 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002588 else if (const nonloc::SymbolVal* SV=dyn_cast<nonloc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002589 if (SV->getSymbol() != Sym)
2590 return true;
2591 }
2592 else
2593 return true;
2594
2595 if (Binding) {
2596 First = false;
2597 return false;
2598 }
2599 else
2600 Binding = R;
2601
2602 return true;
2603 }
2604
2605 operator bool() { return First && Binding; }
2606 MemRegion* getRegion() { return Binding; }
2607};
2608}
2609
Ted Kremenek3148eb42009-01-24 00:55:43 +00002610static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremeneke469fa02009-02-07 22:19:59 +00002611GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002612 SymbolRef Sym) {
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002613
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002614 // Find both first node that referred to the tracked symbol and the
2615 // memory location that value was store to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002616 const ExplodedNode<GRState>* Last = N;
2617 const MemRegion* FirstBinding = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002618
2619 while (N) {
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002620 const GRState* St = N->getState();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002621 RefBindings B = St->get<RefBindings>();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002622
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002623 if (!B.lookup(Sym))
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002624 break;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002625
Ted Kremeneke469fa02009-02-07 22:19:59 +00002626 FindUniqueBinding FB(Sym);
2627 StateMgr.iterBindings(St, FB);
2628 if (FB) FirstBinding = FB.getRegion();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002629
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002630 Last = N;
2631 N = N->pred_empty() ? NULL : *(N->pred_begin());
2632 }
2633
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002634 return std::make_pair(Last, FirstBinding);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002635}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002636
Ted Kremenek3148eb42009-01-24 00:55:43 +00002637PathDiagnosticPiece*
2638CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002639
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002640 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002641 // Tell the BugReporter to report cases when the tracked symbol is
2642 // assigned to different variables, etc.
Ted Kremenekc0959972008-07-02 21:24:01 +00002643 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek66d97062009-02-07 22:04:05 +00002644 return RangedBugReport::getEndPath(BR, EndN);
2645}
2646
2647PathDiagnosticPiece*
2648CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2649
2650 GRBugReporter& BR = cast<GRBugReporter>(br);
2651 // Tell the BugReporter to report cases when the tracked symbol is
2652 // assigned to different variables, etc.
2653 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2654
2655 // We are reporting a leak. Walk up the graph to get to the first node where
2656 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002657 // is stored to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002658 const ExplodedNode<GRState>* AllocNode = 0;
2659 const MemRegion* FirstBinding = 0;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002660
2661 llvm::tie(AllocNode, FirstBinding) =
Ted Kremeneke469fa02009-02-07 22:19:59 +00002662 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002663
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002664 // Get the allocate site.
2665 assert (AllocNode);
2666 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002667
Ted Kremeneke28565b2008-05-05 18:50:19 +00002668 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002669 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002670
Ted Kremenekd5597922009-02-18 23:28:26 +00002671 // Get the leak site. We want to find the last place where the symbol
2672 // was used in an expression.
2673 const ExplodedNode<GRState>* LeakN = EndN;
2674 Stmt *S = 0;
Ted Kremeneke28565b2008-05-05 18:50:19 +00002675
Ted Kremenekd5597922009-02-18 23:28:26 +00002676 while (LeakN) {
2677 ProgramPoint P = LeakN->getLocation();
Ted Kremenekd5597922009-02-18 23:28:26 +00002678
2679 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2680 S = PS->getStmt();
2681 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
2682 S = BE->getSrc()->getTerminator();
2683
2684 if (S) {
2685 // Scan 'S' for uses of Sym.
2686 GRStateRef state(LeakN->getState(), BR.getStateManager());
2687 bool foundSymbol = false;
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002688
2689 // First check if 'S' itself binds to the symbol.
2690 if (Expr *Ex = dyn_cast<Expr>(S)) {
2691 SVal X = state.GetSVal(Ex);
2692 if (isa<loc::SymbolVal>(X) &&
2693 cast<loc::SymbolVal>(X).getSymbol() == Sym)
2694 foundSymbol = true;
2695 }
2696
2697 if (!foundSymbol)
2698 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2699 I!=E; ++I)
2700 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
2701 SVal X = state.GetSVal(Ex);
2702 if (isa<loc::SymbolVal>(X) &&
2703 cast<loc::SymbolVal>(X).getSymbol() == Sym){
2704 foundSymbol = true;
2705 break;
2706 }
Ted Kremenekd5597922009-02-18 23:28:26 +00002707 }
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002708
Ted Kremenekd5597922009-02-18 23:28:26 +00002709 if (foundSymbol)
2710 break;
2711 }
2712
2713 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2714 }
2715
2716 assert(LeakN && S && "No leak site found.");
Ted Kremeneke28565b2008-05-05 18:50:19 +00002717
Ted Kremeneke28565b2008-05-05 18:50:19 +00002718 // Generate the diagnostic.
Ted Kremenek572b2782009-02-18 22:59:04 +00002719 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenekc9e3d862009-02-07 21:59:45 +00002720 std::string sbuf;
2721 llvm::raw_string_ostream os(sbuf);
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002722
Ted Kremeneke28565b2008-05-05 18:50:19 +00002723 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002724
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002725 if (FirstBinding)
Ted Kremenek9e240492008-10-04 05:50:14 +00002726 os << " and stored into '" << FirstBinding->getString() << '\'';
2727
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002728 // Get the retain count.
2729 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2730
2731 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenek04f9d462008-12-02 01:26:07 +00002732 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2733 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2734 // to the caller for NS objects.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002735 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2736 os << " is returned from a method whose name ('"
Chris Lattner077bf5e2008-11-24 03:33:13 +00002737 << MD.getSelector().getAsString()
Ted Kremenek234a4c22009-01-07 00:39:56 +00002738 << "') does not contain 'copy' or otherwise starts with"
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002739 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002740 " in the Memory Management Guide for Cocoa (object leaked).";
2741 }
2742 else
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002743 os << " is no longer referenced after this point and has a retain count of"
2744 " +"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002745 << RV->getCount() << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002746
Ted Kremenek572b2782009-02-18 22:59:04 +00002747 return new PathDiagnosticPiece(L, os.str());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002748}
2749
Ted Kremenek989d5192008-04-17 23:43:50 +00002750
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002751CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2752 ExplodedNode<GRState> *n,
Ted Kremenekd3057212009-02-07 22:38:00 +00002753 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002754 : CFRefReport(D, tf, n, sym)
Ted Kremeneke469fa02009-02-07 22:19:59 +00002755{
2756
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002757 // Most bug reports are cached at the location where they occured.
2758 // With leaks, we want to unique them by the location where they were
Ted Kremeneke469fa02009-02-07 22:19:59 +00002759 // allocated, and only report a single path. To do this, we need to find
2760 // the allocation site of a piece of tracked memory, which we do via a
2761 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2762 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2763 // that all ancestor nodes that represent the allocation site have the
2764 // same SourceLocation.
2765 const ExplodedNode<GRState>* AllocNode = 0;
2766
2767 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekd3057212009-02-07 22:38:00 +00002768 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremeneke469fa02009-02-07 22:19:59 +00002769
Ted Kremeneke469fa02009-02-07 22:19:59 +00002770 // Get the SourceLocation for the allocation site.
Ted Kremenekd3057212009-02-07 22:38:00 +00002771 ProgramPoint P = AllocNode->getLocation();
Ted Kremeneke469fa02009-02-07 22:19:59 +00002772 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenekd3057212009-02-07 22:38:00 +00002773
2774 // Fill in the description of the bug.
2775 Description.clear();
2776 llvm::raw_string_ostream os(Description);
2777 SourceManager& SMgr = Eng.getContext().getSourceManager();
2778 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekc5c60002009-02-07 22:54:59 +00002779 os << "Potential leak of object allocated on line " << AllocLine;
2780
2781 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2782 if (AllocBinding)
2783 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002784}
2785
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002786//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00002787// Handle dead symbols and end-of-path.
2788//===----------------------------------------------------------------------===//
2789
2790void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2791 GREndPathNodeBuilder<GRState>& Builder) {
2792
2793 const GRState* St = Builder.getState();
2794 RefBindings B = St->get<RefBindings>();
2795
2796 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2797 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2798
2799 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2800 bool hasLeak = false;
2801
2802 std::pair<GRStateRef, bool> X =
2803 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2804 (*I).first, (*I).second, hasLeak);
2805
2806 St = X.first;
2807 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2808 }
2809
2810 if (Leaked.empty())
2811 return;
2812
2813 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2814
2815 if (!N)
2816 return;
2817
2818 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2819 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2820
2821 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2822 : leakWithinFunction);
2823 assert(BT && "BugType not initialized.");
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002824 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00002825 BR->EmitReport(report);
2826 }
2827}
2828
2829void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2830 GRExprEngine& Eng,
2831 GRStmtNodeBuilder<GRState>& Builder,
2832 ExplodedNode<GRState>* Pred,
2833 Stmt* S,
2834 const GRState* St,
2835 SymbolReaper& SymReaper) {
2836
Ted Kremenek33b6f632009-02-19 23:47:02 +00002837 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenekcf701772009-02-05 06:50:21 +00002838 RefBindings B = St->get<RefBindings>();
2839 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2840
2841 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2842 E = SymReaper.dead_end(); I != E; ++I) {
2843
2844 const RefVal* T = B.lookup(*I);
2845 if (!T) continue;
2846
2847 bool hasLeak = false;
2848
2849 std::pair<GRStateRef, bool> X
Ted Kremenek33b6f632009-02-19 23:47:02 +00002850 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00002851
2852 St = X.first;
2853
2854 if (hasLeak)
2855 Leaked.push_back(std::make_pair(*I,X.second));
2856 }
2857
Ted Kremenek33b6f632009-02-19 23:47:02 +00002858 if (!Leaked.empty()) {
2859 // Create a new intermediate node representing the leak point. We
2860 // use a special program point that represents this checker-specific
2861 // transition. We use the address of RefBIndex as a unique tag for this
2862 // checker. We will create another node (if we don't cache out) that
2863 // removes the retain-count bindings from the state.
2864 // NOTE: We use 'generateNode' so that it does interplay with the
2865 // auto-transition logic.
2866 ExplodedNode<GRState>* N =
2867 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00002868
Ted Kremenek33b6f632009-02-19 23:47:02 +00002869 if (!N)
2870 return;
2871
2872 // Generate the bug reports.
2873 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
2874 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2875
2876 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2877 : leakWithinFunction);
2878 assert(BT && "BugType not initialized.");
2879 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
2880 BR->EmitReport(report);
2881 }
Ted Kremenekcf701772009-02-05 06:50:21 +00002882
Ted Kremenek33b6f632009-02-19 23:47:02 +00002883 Pred = N;
Ted Kremenekcf701772009-02-05 06:50:21 +00002884 }
Ted Kremenek33b6f632009-02-19 23:47:02 +00002885
2886 // Now generate a new node that nukes the old bindings.
2887 GRStateRef state(St, Eng.getStateManager());
2888 RefBindings::Factory& F = state.get_context<RefBindings>();
2889
2890 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2891 E = SymReaper.dead_end(); I!=E; ++I)
2892 B = F.Remove(B, *I);
2893
2894 state = state.set<RefBindings>(B);
2895 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00002896}
2897
2898void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2899 GRStmtNodeBuilder<GRState>& Builder,
2900 Expr* NodeExpr, Expr* ErrorExpr,
2901 ExplodedNode<GRState>* Pred,
2902 const GRState* St,
2903 RefVal::Kind hasErr, SymbolRef Sym) {
2904 Builder.BuildSinks = true;
2905 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2906
2907 if (!N) return;
2908
2909 CFRefBug *BT = 0;
2910
2911 if (hasErr == RefVal::ErrorUseAfterRelease)
2912 BT = static_cast<CFRefBug*>(useAfterRelease);
2913 else {
2914 assert(hasErr == RefVal::ErrorReleaseNotOwned);
2915 BT = static_cast<CFRefBug*>(releaseNotOwned);
2916 }
2917
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002918 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00002919 report->addRange(ErrorExpr->getSourceRange());
2920 BR->EmitReport(report);
2921}
2922
2923//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00002924// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002925//===----------------------------------------------------------------------===//
2926
Ted Kremenek072192b2008-04-30 23:47:44 +00002927GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2928 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00002929 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00002930}