blob: b63078b691be895f714a5629b6fb0860e10c2cbd [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-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 Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-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 Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
152static bool followsReturnRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000153 NamingConvention C = deriveNamingConvention(s);
154 return C == CreateRule || C == InitRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000155}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000156
Ted Kremenek7d421f32008-04-09 23:49:11 +0000157//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000158// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000159//===----------------------------------------------------------------------===//
160
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000161static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000162 IdentifierInfo* II = &Ctx.Idents.get(name);
163 return Ctx.Selectors.getSelector(0, &II);
164}
165
Ted Kremenek0e344d42008-05-06 00:30:21 +0000166static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(1, &II);
169}
170
Ted Kremenek272aa852008-06-25 21:21:56 +0000171//===----------------------------------------------------------------------===//
172// Type querying functions.
173//===----------------------------------------------------------------------===//
174
Ted Kremenek17144e82009-01-12 21:45:02 +0000175static bool hasPrefix(const char* s, const char* prefix) {
176 if (!prefix)
177 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000178
Ted Kremenek17144e82009-01-12 21:45:02 +0000179 char c = *s;
180 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000181
Ted Kremenek17144e82009-01-12 21:45:02 +0000182 while (c != '\0' && cP != '\0') {
183 if (c != cP) break;
184 c = *(++s);
185 cP = *(++prefix);
186 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000187
Ted Kremenek17144e82009-01-12 21:45:02 +0000188 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000189}
190
Ted Kremenek17144e82009-01-12 21:45:02 +0000191static bool hasSuffix(const char* s, const char* suffix) {
192 const char* loc = strstr(s, suffix);
193 return loc && strcmp(suffix, loc) == 0;
194}
195
196static bool isRefType(QualType RetTy, const char* prefix,
197 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000198
Ted Kremenek17144e82009-01-12 21:45:02 +0000199 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
200 const char* TDName = TD->getDecl()->getIdentifier()->getName();
201 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
202 }
203
204 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000205 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000206
207 // Is the type void*?
208 const PointerType* PT = RetTy->getAsPointerType();
209 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Does the name start with the prefix?
213 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000214}
215
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000216//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000217// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000218//===----------------------------------------------------------------------===//
219
Ted Kremenek272aa852008-06-25 21:21:56 +0000220namespace {
221/// ArgEffect is used to summarize a function/method call's effect on a
222/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000223enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
224 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
225 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000226
227/// ArgEffects summarizes the effects of a function/method call on all of
228/// its arguments.
229typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000230}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000231
Ted Kremeneka7338b42008-03-11 06:39:11 +0000232namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000233template <> struct FoldingSetTrait<ArgEffects> {
234 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
235 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
236 ID.AddInteger(I->first);
237 ID.AddInteger((unsigned) I->second);
238 }
239 }
240};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000241} // end llvm namespace
242
243namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000244
245/// RetEffect is used to summarize a function/method call's behavior with
246/// respect to its return value.
247class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000248public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000249 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
250 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000251
252 enum ObjKind { CF, ObjC, AnyObj };
253
Ted Kremeneka7338b42008-03-11 06:39:11 +0000254private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000255 Kind K;
256 ObjKind O;
257 unsigned index;
258
259 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
260 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000261
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000263 Kind getKind() const { return K; }
264
265 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000266
267 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000268 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000269 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000271
Ted Kremenek272aa852008-06-25 21:21:56 +0000272 static RetEffect MakeAlias(unsigned Idx) {
273 return RetEffect(Alias, Idx);
274 }
275 static RetEffect MakeReceiverAlias() {
276 return RetEffect(ReceiverAlias);
277 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000278 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
279 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000280 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000281 static RetEffect MakeNotOwned(ObjKind o) {
282 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000283 }
284 static RetEffect MakeNoRet() {
285 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000286 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000287
Ted Kremenek272aa852008-06-25 21:21:56 +0000288 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000289 ID.AddInteger((unsigned)K);
290 ID.AddInteger((unsigned)O);
291 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000293};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000294
Ted Kremenek272aa852008-06-25 21:21:56 +0000295
296class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000297 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
298 /// specifies the argument (starting from 0). This can be sparsely
299 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000300 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000301
302 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
303 /// do not have an entry in Args.
304 ArgEffect DefaultArgEffect;
305
Ted Kremenek272aa852008-06-25 21:21:56 +0000306 /// Receiver - If this summary applies to an Objective-C message expression,
307 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000308 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000309
310 /// Ret - The effect on the return value. Used to indicate if the
311 /// function/method call returns a new tracked symbol, returns an
312 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000313 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000314
Ted Kremenekf2717b02008-07-18 17:24:20 +0000315 /// EndPath - Indicates that execution of this method/function should
316 /// terminate the simulation of a path.
317 bool EndPath;
318
Ted Kremeneka7338b42008-03-11 06:39:11 +0000319public:
320
Ted Kremenekbcaff792008-05-06 15:44:25 +0000321 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000322 ArgEffect ReceiverEff, bool endpath = false)
323 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
324 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000325
Ted Kremenek272aa852008-06-25 21:21:56 +0000326 /// getArg - Return the argument effect on the argument specified by
327 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000328 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000329
Ted Kremenekae855d42008-04-24 17:22:33 +0000330 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000331 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000332
333 // If Args is present, it is likely to contain only 1 element.
334 // Just do a linear search. Do it from the back because functions with
335 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000336 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000337 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
338 I!=E; ++I) {
339
340 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000341 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000342
343 if (idx == I->first)
344 return I->second;
345 }
346
Ted Kremenekbcaff792008-05-06 15:44:25 +0000347 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000348 }
349
Ted Kremenek272aa852008-06-25 21:21:56 +0000350 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000351 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000352 return Ret;
353 }
354
Ted Kremenekf2717b02008-07-18 17:24:20 +0000355 /// isEndPath - Returns true if executing the given method/function should
356 /// terminate the path.
357 bool isEndPath() const { return EndPath; }
358
Ted Kremenek272aa852008-06-25 21:21:56 +0000359 /// getReceiverEffect - Returns the effect on the receiver of the call.
360 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000361 ArgEffect getReceiverEffect() const {
362 return Receiver;
363 }
364
Ted Kremenek2719e982008-06-17 02:43:46 +0000365 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000366
Ted Kremenek2719e982008-06-17 02:43:46 +0000367 ExprIterator begin_args() const { return Args->begin(); }
368 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000369
Ted Kremenek266d8b62008-05-06 02:26:56 +0000370 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000371 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000372 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000374 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000375 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000376 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000377 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000378 }
379
380 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000381 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000382 }
383};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000384} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000385
Ted Kremenek272aa852008-06-25 21:21:56 +0000386//===----------------------------------------------------------------------===//
387// Data structures for constructing summaries.
388//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390namespace {
391class VISIBILITY_HIDDEN ObjCSummaryKey {
392 IdentifierInfo* II;
393 Selector S;
394public:
395 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
396 : II(ii), S(s) {}
397
398 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
399 : II(d ? d->getIdentifier() : 0), S(s) {}
400
401 ObjCSummaryKey(Selector s)
402 : II(0), S(s) {}
403
404 IdentifierInfo* getIdentifier() const { return II; }
405 Selector getSelector() const { return S; }
406};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000407}
408
409namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000410template <> struct DenseMapInfo<ObjCSummaryKey> {
411 static inline ObjCSummaryKey getEmptyKey() {
412 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
413 DenseMapInfo<Selector>::getEmptyKey());
414 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000415
Ted Kremenek272aa852008-06-25 21:21:56 +0000416 static inline ObjCSummaryKey getTombstoneKey() {
417 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
418 DenseMapInfo<Selector>::getTombstoneKey());
419 }
420
421 static unsigned getHashValue(const ObjCSummaryKey &V) {
422 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
423 & 0x88888888)
424 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
425 & 0x55555555);
426 }
427
428 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
429 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
430 RHS.getIdentifier()) &&
431 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
432 RHS.getSelector());
433 }
434
435 static bool isPod() {
436 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
437 DenseMapInfo<Selector>::isPod();
438 }
439};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000440} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000441
Ted Kremenek84f010c2008-06-23 23:30:29 +0000442namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000443class VISIBILITY_HIDDEN ObjCSummaryCache {
444 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
445 MapTy M;
446public:
447 ObjCSummaryCache() {}
448
449 typedef MapTy::iterator iterator;
450
451 iterator find(ObjCInterfaceDecl* D, Selector S) {
452
453 // Do a lookup with the (D,S) pair. If we find a match return
454 // the iterator.
455 ObjCSummaryKey K(D, S);
456 MapTy::iterator I = M.find(K);
457
458 if (I != M.end() || !D)
459 return I;
460
461 // Walk the super chain. If we find a hit with a parent, we'll end
462 // up returning that summary. We actually allow that key (null,S), as
463 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
464 // generate initial summaries without having to worry about NSObject
465 // being declared.
466 // FIXME: We may change this at some point.
467 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
468 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
469 break;
470
471 if (!C)
472 return I;
473 }
474
475 // Cache the summary with original key to make the next lookup faster
476 // and return the iterator.
477 M[K] = I->second;
478 return I;
479 }
480
Ted Kremenek9449ca92008-08-12 20:41:56 +0000481
Ted Kremenek272aa852008-06-25 21:21:56 +0000482 iterator find(Expr* Receiver, Selector S) {
483 return find(getReceiverDecl(Receiver), S);
484 }
485
486 iterator find(IdentifierInfo* II, Selector S) {
487 // FIXME: Class method lookup. Right now we dont' have a good way
488 // of going between IdentifierInfo* and the class hierarchy.
489 iterator I = M.find(ObjCSummaryKey(II, S));
490 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
491 }
492
493 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
494
495 const PointerType* PT = E->getType()->getAsPointerType();
496 if (!PT) return 0;
497
498 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
499 if (!OI) return 0;
500
501 return OI ? OI->getDecl() : 0;
502 }
503
504 iterator end() { return M.end(); }
505
506 RetainSummary*& operator[](ObjCMessageExpr* ME) {
507
508 Selector S = ME->getSelector();
509
510 if (Expr* Receiver = ME->getReceiver()) {
511 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
512 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
513 }
514
515 return M[ObjCSummaryKey(ME->getClassName(), S)];
516 }
517
518 RetainSummary*& operator[](ObjCSummaryKey K) {
519 return M[K];
520 }
521
522 RetainSummary*& operator[](Selector S) {
523 return M[ ObjCSummaryKey(S) ];
524 }
525};
526} // end anonymous namespace
527
528//===----------------------------------------------------------------------===//
529// Data structures for managing collections of summaries.
530//===----------------------------------------------------------------------===//
531
532namespace {
533class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000534
535 //==-----------------------------------------------------------------==//
536 // Typedefs.
537 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000538
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000539 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
540 ArgEffectsSetTy;
541
542 typedef llvm::FoldingSet<RetainSummary>
543 SummarySetTy;
544
545 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
546 FuncSummariesTy;
547
Ted Kremenek84f010c2008-06-23 23:30:29 +0000548 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000549
550 //==-----------------------------------------------------------------==//
551 // Data.
552 //==-----------------------------------------------------------------==//
553
Ted Kremenek272aa852008-06-25 21:21:56 +0000554 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000555 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000556
Ted Kremenekede40b72008-07-09 18:11:16 +0000557 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
558 /// "CFDictionaryCreate".
559 IdentifierInfo* CFDictionaryCreateII;
560
Ted Kremenek272aa852008-06-25 21:21:56 +0000561 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000562 const bool GCEnabled;
563
Ted Kremenek272aa852008-06-25 21:21:56 +0000564 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000565 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000566
Ted Kremenek272aa852008-06-25 21:21:56 +0000567 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000568 FuncSummariesTy FuncSummaries;
569
Ted Kremenek272aa852008-06-25 21:21:56 +0000570 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
571 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000572 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000573
Ted Kremenek272aa852008-06-25 21:21:56 +0000574 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000575 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000576
Ted Kremenek272aa852008-06-25 21:21:56 +0000577 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000578 ArgEffectsSetTy ArgEffectsSet;
579
Ted Kremenek272aa852008-06-25 21:21:56 +0000580 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
581 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000582 llvm::BumpPtrAllocator BPAlloc;
583
Ted Kremenek272aa852008-06-25 21:21:56 +0000584 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000585 ArgEffects ScratchArgs;
586
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000587 RetainSummary* StopSummary;
588
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000589 //==-----------------------------------------------------------------==//
590 // Methods.
591 //==-----------------------------------------------------------------==//
592
Ted Kremenek272aa852008-06-25 21:21:56 +0000593 /// getArgEffects - Returns a persistent ArgEffects object based on the
594 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000595 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000596
Ted Kremenek562c1302008-05-05 16:51:50 +0000597 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000598
599public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000600 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000601
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000602 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
603 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000604 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000605
Ted Kremenek266d8b62008-05-06 02:26:56 +0000606 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000607 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000608 ArgEffect DefaultEff = MayEscape,
609 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000610
Ted Kremenek266d8b62008-05-06 02:26:56 +0000611 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000612 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000613 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000614 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000615 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000616
Ted Kremenekbcaff792008-05-06 15:44:25 +0000617 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000618 if (StopSummary)
619 return StopSummary;
620
621 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
622 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000623
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000624 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000625 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000626
Ted Kremenek272aa852008-06-25 21:21:56 +0000627 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000628
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000629 void InitializeClassMethodSummaries();
630 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000631
Ted Kremenek35920ed2009-01-07 00:39:56 +0000632 bool isTrackedObjectType(QualType T);
633
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000634private:
635
Ted Kremenekf2717b02008-07-18 17:24:20 +0000636 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
637 RetainSummary* Summ) {
638 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
639 }
640
Ted Kremenek272aa852008-06-25 21:21:56 +0000641 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
642 ObjCClassMethodSummaries[S] = Summ;
643 }
644
645 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
646 ObjCMethodSummaries[S] = Summ;
647 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000648
649 void addClassMethSummary(const char* Cls, const char* nullaryName,
650 RetainSummary *Summ) {
651 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
652 Selector S = GetNullarySelector(nullaryName, Ctx);
653 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
654 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000655
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000656 void addInstMethSummary(const char* Cls, const char* nullaryName,
657 RetainSummary *Summ) {
658 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
659 Selector S = GetNullarySelector(nullaryName, Ctx);
660 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
661 }
662
Ted Kremenek45642a42008-08-12 18:48:50 +0000663 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenekf2717b02008-07-18 17:24:20 +0000664
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000665 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
666 llvm::SmallVector<IdentifierInfo*, 10> II;
667
668 while (const char* s = va_arg(argp, const char*))
669 II.push_back(&Ctx.Idents.get(s));
670
671 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000672 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
673 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000674
675 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
676 va_list argp;
677 va_start(argp, Summ);
678 addInstMethSummary(Cls, Summ, argp);
679 va_end(argp);
680 }
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000681
682 void addPanicSummary(const char* Cls, ...) {
683 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
684 DoNothing, DoNothing, true);
685 va_list argp;
686 va_start (argp, Cls);
Ted Kremenek45642a42008-08-12 18:48:50 +0000687 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000688 va_end(argp);
689 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000690
Ted Kremeneka7338b42008-03-11 06:39:11 +0000691public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000692
693 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000694 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000695 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000696 GCEnabled(gcenabled), StopSummary(0) {
697
698 InitializeClassMethodSummaries();
699 InitializeMethodSummaries();
700 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000701
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000702 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000703
Ted Kremenekd13c1872008-06-24 03:56:45 +0000704 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000705 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenekb17fa952009-04-23 21:25:57 +0000706 RetainSummary* getClassMethodSummary(ObjCMessageExpr *ME);
Ted Kremenek174a0772009-04-23 23:08:22 +0000707 RetainSummary* getCommonMethodSummary(ObjCMessageExpr *ME, const char *s);
Ted Kremenek926abf22008-05-06 04:20:12 +0000708
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000709 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000710};
711
712} // end anonymous namespace
713
714//===----------------------------------------------------------------------===//
715// Implementation of checker data structures.
716//===----------------------------------------------------------------------===//
717
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000718RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000719
720 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
721 // mitigating the need to do explicit cleanup of the
722 // Argument-Effect summaries.
723
Ted Kremenek42ea0322008-05-05 23:55:01 +0000724 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
725 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000726 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000727}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000728
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000729ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000730
Ted Kremenekae855d42008-04-24 17:22:33 +0000731 if (ScratchArgs.empty())
732 return NULL;
733
734 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000735 llvm::FoldingSetNodeID profile;
736 profile.Add(ScratchArgs);
737 void* InsertPos;
738
Ted Kremenekae855d42008-04-24 17:22:33 +0000739 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000740 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000741 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000742
Ted Kremenekae855d42008-04-24 17:22:33 +0000743 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000744 ScratchArgs.clear();
745 return &E->getValue();
746 }
747
748 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000749 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000750
751 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000752 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000753
754 ScratchArgs.clear();
755 return &E->getValue();
756}
757
Ted Kremenek266d8b62008-05-06 02:26:56 +0000758RetainSummary*
759RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000760 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000761 ArgEffect DefaultEff,
762 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000763
Ted Kremenekae855d42008-04-24 17:22:33 +0000764 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000765 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000766 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
767 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000768
Ted Kremenekae855d42008-04-24 17:22:33 +0000769 // Look up the uniqued summary, or create one if it doesn't exist.
770 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000771 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000772
773 if (Summ)
774 return Summ;
775
Ted Kremenekae855d42008-04-24 17:22:33 +0000776 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000777 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000778 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000779 SummarySet.InsertNode(Summ, InsertPos);
780
781 return Summ;
782}
783
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000784//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000785// Predicates.
786//===----------------------------------------------------------------------===//
787
Ted Kremenek0d813552009-04-23 22:11:07 +0000788bool RetainSummaryManager::isTrackedObjectType(QualType Ty) {
789 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000790 return false;
791
Ted Kremenek0d813552009-04-23 22:11:07 +0000792 // We assume that id<..>, id, and "Class" all represent tracked objects.
793 const PointerType *PT = Ty->getAsPointerType();
794 if (PT == 0)
795 return true;
796
797 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000798
799 // We assume that id<..>, id, and "Class" all represent tracked objects.
800 if (!OT)
801 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000802
803 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000804 // FIXME: We can memoize here if this gets too expensive.
805 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
806 ObjCInterfaceDecl* ID = OT->getDecl();
807
808 for ( ; ID ; ID = ID->getSuperClass())
809 if (ID->getIdentifier() == NSObjectII)
810 return true;
811
812 return false;
813}
814
815//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000816// Summary creation for functions (largely uses of Core Foundation).
817//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000818
Ted Kremenek17144e82009-01-12 21:45:02 +0000819static bool isRetain(FunctionDecl* FD, const char* FName) {
820 const char* loc = strstr(FName, "Retain");
821 return loc && loc[sizeof("Retain")-1] == '\0';
822}
823
824static bool isRelease(FunctionDecl* FD, const char* FName) {
825 const char* loc = strstr(FName, "Release");
826 return loc && loc[sizeof("Release")-1] == '\0';
827}
828
Ted Kremenekd13c1872008-06-24 03:56:45 +0000829RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000830
831 SourceLocation Loc = FD->getLocation();
832
833 if (!Loc.isFileID())
834 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000835
Ted Kremenekae855d42008-04-24 17:22:33 +0000836 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000837 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000838
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000839 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000840 return I->second;
841
842 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000843 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000844
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000845 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000846 // We generate "stop" summaries for implicitly defined functions.
847 if (FD->isImplicit()) {
848 S = getPersistentStopSummary();
849 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000850 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000851
Ted Kremenek064ef322009-02-23 16:51:39 +0000852 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000853 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000854 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000855 const char* FName = FD->getIdentifier()->getName();
856
Ted Kremenek38c6f022009-03-05 22:11:14 +0000857 // Strip away preceding '_'. Doing this here will effect all the checks
858 // down below.
859 while (*FName == '_') ++FName;
860
Ted Kremenek17144e82009-01-12 21:45:02 +0000861 // Inspect the result type.
862 QualType RetTy = FT->getResultType();
863
864 // FIXME: This should all be refactored into a chain of "summary lookup"
865 // filters.
866 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
867 // FIXES: <rdar://problem/6326900>
868 // This should be addressed using a API table. This strcmp is also
869 // a little gross, but there is no need to super optimize here.
870 assert (ScratchArgs.empty());
871 ScratchArgs.push_back(std::make_pair(1, DecRef));
872 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
873 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000874 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000875
876 // Enable this code once the semantics of NSDeallocateObject are resolved
877 // for GC. <rdar://problem/6619988>
878#if 0
879 // Handle: NSDeallocateObject(id anObject);
880 // This method does allow 'nil' (although we don't check it now).
881 if (strcmp(FName, "NSDeallocateObject") == 0) {
882 return RetTy == Ctx.VoidTy
883 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
884 : getPersistentStopSummary();
885 }
886#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000887
888 // Handle: id NSMakeCollectable(CFTypeRef)
889 if (strcmp(FName, "NSMakeCollectable") == 0) {
890 S = (RetTy == Ctx.getObjCIdType())
891 ? getUnarySummary(FT, cfmakecollectable)
892 : getPersistentStopSummary();
893
894 break;
895 }
896
897 if (RetTy->isPointerType()) {
898 // For CoreFoundation ('CF') types.
899 if (isRefType(RetTy, "CF", &Ctx, FName)) {
900 if (isRetain(FD, FName))
901 S = getUnarySummary(FT, cfretain);
902 else if (strstr(FName, "MakeCollectable"))
903 S = getUnarySummary(FT, cfmakecollectable);
904 else
905 S = getCFCreateGetRuleSummary(FD, FName);
906
907 break;
908 }
909
910 // For CoreGraphics ('CG') types.
911 if (isRefType(RetTy, "CG", &Ctx, FName)) {
912 if (isRetain(FD, FName))
913 S = getUnarySummary(FT, cfretain);
914 else
915 S = getCFCreateGetRuleSummary(FD, FName);
916
917 break;
918 }
919
920 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
921 if (isRefType(RetTy, "DADisk") ||
922 isRefType(RetTy, "DADissenter") ||
923 isRefType(RetTy, "DASessionRef")) {
924 S = getCFCreateGetRuleSummary(FD, FName);
925 break;
926 }
927
928 break;
929 }
930
931 // Check for release functions, the only kind of functions that we care
932 // about that don't return a pointer type.
933 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000934 // Test for 'CGCF'.
935 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
936 FName += 4;
937 else
938 FName += 2;
939
940 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000941 S = getUnarySummary(FT, cfrelease);
942 else {
Ted Kremenek7b293682009-01-29 22:45:13 +0000943 assert (ScratchArgs.empty());
944 // Remaining CoreFoundation and CoreGraphics functions.
945 // We use to assume that they all strictly followed the ownership idiom
946 // and that ownership cannot be transferred. While this is technically
947 // correct, many methods allow a tracked object to escape. For example:
948 //
949 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
950 // CFDictionaryAddValue(y, key, x);
951 // CFRelease(x);
952 // ... it is okay to use 'x' since 'y' has a reference to it
953 //
954 // We handle this and similar cases with the follow heuristic. If the
955 // function name contains "InsertValue", "SetValue" or "AddValue" then
956 // we assume that arguments may "escape."
957 //
958 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
959 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000960 CStrInCStrNoCase(FName, "SetValue") ||
961 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000962 ? MayEscape : DoNothing;
963
964 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000965 }
966 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000967 }
968 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000969
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000970 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000971 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000972}
973
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000974RetainSummary*
975RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
976 const char* FName) {
977
Ted Kremenek562c1302008-05-05 16:51:50 +0000978 if (strstr(FName, "Create") || strstr(FName, "Copy"))
979 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000980
Ted Kremenek562c1302008-05-05 16:51:50 +0000981 if (strstr(FName, "Get"))
982 return getCFSummaryGetRule(FD);
983
984 return 0;
985}
986
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000987RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +0000988RetainSummaryManager::getUnarySummary(const FunctionType* FT,
989 UnaryFuncKind func) {
990
Ted Kremenek17144e82009-01-12 21:45:02 +0000991 // Sanity check that this is *really* a unary function. This can
992 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000993 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +0000994 if (!FTP || FTP->getNumArgs() != 1)
995 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000996
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000997 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000998
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000999 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +00001000 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001001 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001002 return getPersistentSummary(RetEffect::MakeAlias(0),
1003 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001004 }
1005
1006 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001007 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001008 return getPersistentSummary(RetEffect::MakeNoRet(),
1009 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001010 }
1011
1012 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +00001013 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1014 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001015 }
1016
1017 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001018 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001019 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001020 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001021}
1022
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001023RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001024 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001025
1026 if (FD->getIdentifier() == CFDictionaryCreateII) {
1027 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1028 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1029 }
1030
Ted Kremenek68621b92009-01-28 05:56:51 +00001031 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001032}
1033
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001034RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001035 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001036 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1037 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001038}
1039
Ted Kremeneka7338b42008-03-11 06:39:11 +00001040//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001041// Summary creation for Selectors.
1042//===----------------------------------------------------------------------===//
1043
Ted Kremenekbcaff792008-05-06 15:44:25 +00001044RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001045RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001046 assert(ScratchArgs.empty());
1047
Ted Kremenek802cfc72009-02-20 00:05:35 +00001048 // 'init' methods only return an alias if the return type is a location type.
1049 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001050 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +00001051 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1052 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001053
Ted Kremenek272aa852008-06-25 21:21:56 +00001054 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001055 return Summ;
1056}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001057
Ted Kremenek272aa852008-06-25 21:21:56 +00001058
Ted Kremenekbcaff792008-05-06 15:44:25 +00001059RetainSummary*
Ted Kremenek174a0772009-04-23 23:08:22 +00001060RetainSummaryManager::getCommonMethodSummary(ObjCMessageExpr* ME, const char *s)
1061{
1062 // Look for methods that return an owned object.
1063 if (!isTrackedObjectType(ME->getType()))
1064 return 0;
1065
1066 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1067 // by instance methods.
1068
1069 RetEffect E =
1070 followsFundamentalRule(s)
1071 ? (isGCEnabled() ? RetEffect::MakeNotOwned(RetEffect::ObjC)
1072 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1073 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1074
1075 return getPersistentSummary(E);
1076}
1077
1078RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001079RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1080 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001081
1082 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001083
Ted Kremenek272aa852008-06-25 21:21:56 +00001084 // Look up a summary in our summary cache.
1085 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001086
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001087 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001088 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001089
Ted Kremenek35920ed2009-01-07 00:39:56 +00001090 // "initXXX": pass-through for receiver.
Ted Kremenek42ea0322008-05-05 23:55:01 +00001091 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek174a0772009-04-23 23:08:22 +00001092 assert(ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001093
Ted Kremenek4395b452009-02-21 05:13:43 +00001094 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek35920ed2009-01-07 00:39:56 +00001095 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +00001096
Ted Kremenek174a0772009-04-23 23:08:22 +00001097 RetainSummary *Summ = getCommonMethodSummary(ME, s);
Ted Kremeneke4158502009-04-23 19:11:35 +00001098 ObjCMethodSummaries[ME] = Summ;
1099 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001100}
1101
Ted Kremeneka7722b72008-05-06 21:26:51 +00001102RetainSummary*
Ted Kremenekb17fa952009-04-23 21:25:57 +00001103RetainSummaryManager::getClassMethodSummary(ObjCMessageExpr* ME) {
Ted Kremeneka7722b72008-05-06 21:26:51 +00001104
Ted Kremenek272aa852008-06-25 21:21:56 +00001105 // FIXME: Eventually we should properly do class method summaries, but
1106 // it requires us being able to walk the type hierarchy. Unfortunately,
Ted Kremenek20227b22009-04-23 20:02:30 +00001107 // we cannot do this with just an IdentifierInfo* for the class name.
1108 IdentifierInfo* ClsName = ME->getClassName();
Ted Kremenekb17fa952009-04-23 21:25:57 +00001109 Selector S = ME->getSelector();
Ted Kremenek272aa852008-06-25 21:21:56 +00001110
Ted Kremeneka7722b72008-05-06 21:26:51 +00001111 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +00001112 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001113
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001114 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001115 return I->second;
1116
Ted Kremenek174a0772009-04-23 23:08:22 +00001117 RetainSummary* Summ =
1118 getCommonMethodSummary(ME, S.getIdentifierInfoForSlot(0)->getName());
Ted Kremeneke4158502009-04-23 19:11:35 +00001119 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
1120 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001121}
1122
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001123void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001124
1125 assert (ScratchArgs.empty());
1126
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001127 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001128 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001129
Ted Kremenek0e344d42008-05-06 00:30:21 +00001130 RetainSummary* Summ = getPersistentSummary(E);
1131
Ted Kremenek272aa852008-06-25 21:21:56 +00001132 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1133 // NSObject and its derivatives.
1134 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1135 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1136 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001137
1138 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001139 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001140 GetNullarySelector("currentHandler", Ctx),
1141 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001142
1143 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001144 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1145 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1146 GetUnarySelector("addObject", Ctx),
1147 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001148 DoNothing, Autorelease));
Ted Kremenek0e344d42008-05-06 00:30:21 +00001149}
1150
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001151void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001152
1153 assert (ScratchArgs.empty());
1154
Ted Kremeneka7722b72008-05-06 21:26:51 +00001155 // Create the "init" selector. It just acts as a pass-through for the
1156 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001157 RetainSummary* InitSumm =
1158 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001159 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001160
1161 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001162 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001163 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001164
Ted Kremeneke44927e2008-07-01 17:21:27 +00001165 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001166
1167 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001168 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1169
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001170 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001171 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001172
Ted Kremenek266d8b62008-05-06 02:26:56 +00001173 // Create the "retain" selector.
1174 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001175 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001176 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001177
1178 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001179 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001180 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001181
1182 // Create the "drain" selector.
1183 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001184 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001185
1186 // Create the -dealloc summary.
1187 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1188 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001189
1190 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001191 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001192 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001193
Ted Kremenekaac82832009-02-23 17:45:03 +00001194 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001195 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001196 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001197 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001198
Ted Kremenek45642a42008-08-12 18:48:50 +00001199 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001200 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1201 // self-own themselves. However, they only do this once they are displayed.
1202 // Thus, we need to track an NSWindow's display status.
1203 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001204 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001205 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1206
1207 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1208
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001209
1210#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001211 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001212 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001213
1214 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1215 "styleMask", "backing", "defer", NULL);
1216
1217 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1218 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001219#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001220
1221 // For NSPanel (which subclasses NSWindow), allocated objects are not
1222 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001223 // FIXME: For now we don't track NSPanels. object for the same reason
1224 // as for NSWindow objects.
1225 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1226
Ted Kremenek45642a42008-08-12 18:48:50 +00001227 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1228 "styleMask", "backing", "defer", NULL);
1229
1230 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1231 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001232
Ted Kremenekf2717b02008-07-18 17:24:20 +00001233 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001234 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1235 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001236
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001237 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1238 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001239}
1240
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001241//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001242// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001243//===----------------------------------------------------------------------===//
1244
Ted Kremeneka7338b42008-03-11 06:39:11 +00001245namespace {
1246
Ted Kremenek7d421f32008-04-09 23:49:11 +00001247class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001248public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001249 enum Kind {
1250 Owned = 0, // Owning reference.
1251 NotOwned, // Reference is not owned by still valid (not freed).
1252 Released, // Object has been released.
1253 ReturnedOwned, // Returned object passes ownership to caller.
1254 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001255 ERROR_START,
1256 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1257 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001258 ErrorUseAfterRelease, // Object used after released.
1259 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001260 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001261 ErrorLeak, // A memory leak due to excessive reference counts.
1262 ErrorLeakReturned // A memory leak due to the returning method not having
1263 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001264 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001265
1266private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001267 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001268 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001269 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001270 QualType T;
1271
Ted Kremenek68621b92009-01-28 05:56:51 +00001272 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1273 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001274
Ted Kremenek68621b92009-01-28 05:56:51 +00001275 RefVal(Kind k, unsigned cnt = 0)
1276 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1277
1278public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001279 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001280
1281 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001282
Ted Kremenek6537a642009-03-17 19:42:23 +00001283 unsigned getCount() const { return Cnt; }
1284 void clearCounts() { Cnt = 0; }
1285
Ted Kremenek272aa852008-06-25 21:21:56 +00001286 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001287
1288 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001289
Ted Kremenek6537a642009-03-17 19:42:23 +00001290 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001291
Ted Kremenek6537a642009-03-17 19:42:23 +00001292 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001293
Ted Kremenekffefc352008-04-11 22:25:11 +00001294 bool isOwned() const {
1295 return getKind() == Owned;
1296 }
1297
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001298 bool isNotOwned() const {
1299 return getKind() == NotOwned;
1300 }
1301
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001302 bool isReturnedOwned() const {
1303 return getKind() == ReturnedOwned;
1304 }
1305
1306 bool isReturnedNotOwned() const {
1307 return getKind() == ReturnedNotOwned;
1308 }
1309
1310 bool isNonLeakError() const {
1311 Kind k = getKind();
1312 return isError(k) && !isLeak(k);
1313 }
1314
Ted Kremenek68621b92009-01-28 05:56:51 +00001315 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1316 unsigned Count = 1) {
1317 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001318 }
1319
Ted Kremenek68621b92009-01-28 05:56:51 +00001320 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1321 unsigned Count = 0) {
1322 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001323 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001324
1325 static RefVal makeReturnedOwned(unsigned Count) {
1326 return RefVal(ReturnedOwned, Count);
1327 }
1328
1329 static RefVal makeReturnedNotOwned() {
1330 return RefVal(ReturnedNotOwned);
1331 }
1332
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001333 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001334
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001335 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001336 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001337 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001338
Ted Kremenek272aa852008-06-25 21:21:56 +00001339 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001340 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001341 }
1342
1343 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001344 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001345 }
1346
1347 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001348 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001349 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001350
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001351 void Profile(llvm::FoldingSetNodeID& ID) const {
1352 ID.AddInteger((unsigned) kind);
1353 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001354 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001355 }
1356
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001357 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001358};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001359
1360void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001361 if (!T.isNull())
1362 Out << "Tracked Type:" << T.getAsString() << '\n';
1363
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001364 switch (getKind()) {
1365 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001366 case Owned: {
1367 Out << "Owned";
1368 unsigned cnt = getCount();
1369 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001370 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001371 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001372
Ted Kremenekc4f81022008-04-10 23:09:18 +00001373 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001374 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001375 unsigned cnt = getCount();
1376 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001377 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001378 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001379
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001380 case ReturnedOwned: {
1381 Out << "ReturnedOwned";
1382 unsigned cnt = getCount();
1383 if (cnt) Out << " (+ " << cnt << ")";
1384 break;
1385 }
1386
1387 case ReturnedNotOwned: {
1388 Out << "ReturnedNotOwned";
1389 unsigned cnt = getCount();
1390 if (cnt) Out << " (+ " << cnt << ")";
1391 break;
1392 }
1393
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001394 case Released:
1395 Out << "Released";
1396 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001397
1398 case ErrorDeallocGC:
1399 Out << "-dealloc (GC)";
1400 break;
1401
1402 case ErrorDeallocNotOwned:
1403 Out << "-dealloc (not-owned)";
1404 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001405
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001406 case ErrorLeak:
1407 Out << "Leaked";
1408 break;
1409
Ted Kremenek311f3d42008-10-22 23:56:21 +00001410 case ErrorLeakReturned:
1411 Out << "Leaked (Bad naming)";
1412 break;
1413
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001414 case ErrorUseAfterRelease:
1415 Out << "Use-After-Release [ERROR]";
1416 break;
1417
1418 case ErrorReleaseNotOwned:
1419 Out << "Release of Not-Owned [ERROR]";
1420 break;
1421 }
1422}
Ted Kremenek0d721572008-03-11 17:48:22 +00001423
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001424} // end anonymous namespace
1425
1426//===----------------------------------------------------------------------===//
1427// RefBindings - State used to track object reference counts.
1428//===----------------------------------------------------------------------===//
1429
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001430typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001431static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001432static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001433
1434namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001435 template<>
1436 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1437 static inline void* GDMIndex() { return &RefBIndex; }
1438 };
1439}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001440
1441//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001442// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001443//===----------------------------------------------------------------------===//
1444
Ted Kremenekb6578942009-02-24 19:15:11 +00001445typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1446typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1447typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001448
Ted Kremenekb6578942009-02-24 19:15:11 +00001449static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001450static int AutoRBIndex = 0;
1451
Ted Kremenekb6578942009-02-24 19:15:11 +00001452namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001453namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001454
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001455namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001456template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001457 : public GRStatePartialTrait<ARStack> {
1458 static inline void* GDMIndex() { return &AutoRBIndex; }
1459};
1460
1461template<> struct GRStateTrait<AutoreleasePoolContents>
1462 : public GRStatePartialTrait<ARPoolContents> {
1463 static inline void* GDMIndex() { return &AutoRCIndex; }
1464};
1465} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001466
Ted Kremenek681fb352009-03-20 17:34:15 +00001467static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1468 ARStack stack = state->get<AutoreleaseStack>();
1469 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1470}
1471
1472static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1473 SymbolRef sym) {
1474
1475 SymbolRef pool = GetCurrentAutoreleasePool(state);
1476 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1477 ARCounts newCnts(0);
1478
1479 if (cnts) {
1480 const unsigned *cnt = (*cnts).lookup(sym);
1481 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1482 }
1483 else
1484 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1485
1486 return state.set<AutoreleasePoolContents>(pool, newCnts);
1487}
1488
Ted Kremenek7aef4842008-04-16 20:40:59 +00001489//===----------------------------------------------------------------------===//
1490// Transfer functions.
1491//===----------------------------------------------------------------------===//
1492
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001493namespace {
1494
Ted Kremenek7d421f32008-04-09 23:49:11 +00001495class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001496public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001497 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001498 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001499 virtual void Print(std::ostream& Out, const GRState* state,
1500 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001501 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001502
1503private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001504 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1505 SummaryLogTy;
1506
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001507 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001508 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001509 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001510 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001511
Ted Kremenek708af042009-02-05 06:50:21 +00001512 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001513 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001514 BugType *leakWithinFunction, *leakAtReturn;
1515 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001516
Ted Kremenekb6578942009-02-24 19:15:11 +00001517 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1518 RefVal::Kind& hasErr);
1519
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001520 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1521 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001522 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001523 ExplodedNode<GRState>* Pred,
1524 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001525 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001526
Ted Kremenek0106e202008-10-24 20:32:50 +00001527 std::pair<GRStateRef, bool>
1528 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001529 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001530
Ted Kremenekb6578942009-02-24 19:15:11 +00001531public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001532 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001533 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001534 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1535 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001536 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001537
Ted Kremenek708af042009-02-05 06:50:21 +00001538 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001539
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001540 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001541
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001542 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1543 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001544 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001545
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001546 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001547 const LangOptions& getLangOptions() const { return LOpts; }
1548
Ted Kremenekc26c4692009-02-18 03:48:14 +00001549 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1550 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1551 return I == SummaryLog.end() ? 0 : I->second;
1552 }
1553
Ted Kremeneka7338b42008-03-11 06:39:11 +00001554 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001555
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001556 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001557 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001558 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001559 Expr* Ex,
1560 Expr* Receiver,
1561 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001562 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001563 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001564
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001565 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001566 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001567 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001568 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001569 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001570
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001571
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001572 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001573 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001574 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001575 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001576 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001577
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001578 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001579 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001580 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001581 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001582 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001583
Ted Kremeneka42be302009-02-14 01:43:44 +00001584 // Stores.
1585 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1586
Ted Kremenekffefc352008-04-11 22:25:11 +00001587 // End-of-path.
1588
1589 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001590 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001591
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001592 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001593 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001594 GRStmtNodeBuilder<GRState>& Builder,
1595 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001596 Stmt* S, const GRState* state,
1597 SymbolReaper& SymReaper);
1598
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001599 // Return statements.
1600
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001601 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001602 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001603 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001604 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001605 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001606
1607 // Assumptions.
1608
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001609 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001610 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001611 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001612};
1613
1614} // end anonymous namespace
1615
Ted Kremenek681fb352009-03-20 17:34:15 +00001616static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1617 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001618 if (Sym)
1619 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001620 else
1621 Out << "<pool>";
1622 Out << ":{";
1623
1624 // Get the contents of the pool.
1625 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1626 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1627 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1628
1629 Out << '}';
1630}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001631
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001632void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1633 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001634
1635
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001636
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001637 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001638
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001639 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001640 Out << sep << nl;
1641
1642 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1643 Out << (*I).first << " : ";
1644 (*I).second.print(Out);
1645 Out << nl;
1646 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001647
1648 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001649 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001650 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001651
Ted Kremenek681fb352009-03-20 17:34:15 +00001652 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1653 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1654 PrintPool(Out, *I, state);
1655
1656 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001657}
1658
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001659static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001660 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001661}
1662
Ted Kremenek266d8b62008-05-06 02:26:56 +00001663static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1664 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001665}
1666
Ted Kremenek227c5372008-05-06 02:41:27 +00001667static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1668 return Summ ? Summ->getReceiverEffect() : DoNothing;
1669}
1670
Ted Kremenekf2717b02008-07-18 17:24:20 +00001671static inline bool IsEndPath(RetainSummary* Summ) {
1672 return Summ ? Summ->isEndPath() : false;
1673}
1674
Ted Kremenek1feab292008-04-16 04:28:53 +00001675
Ted Kremenek272aa852008-06-25 21:21:56 +00001676/// GetReturnType - Used to get the return type of a message expression or
1677/// function call with the intention of affixing that type to a tracked symbol.
1678/// While the the return type can be queried directly from RetEx, when
1679/// invoking class methods we augment to the return type to be that of
1680/// a pointer to the class (as opposed it just being id).
1681static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1682
1683 QualType RetTy = RetE->getType();
1684
1685 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001686 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001687 if (!PT)
1688 return RetTy;
1689
1690 // If RetEx is not a message expression just return its type.
1691 // If RetEx is a message expression, return its types if it is something
1692 /// more specific than id.
1693
1694 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1695
Steve Naroff17c03822009-02-12 17:52:19 +00001696 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001697 return RetTy;
1698
1699 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1700
1701 // At this point we know the return type of the message expression is id.
1702 // If we have an ObjCInterceDecl, we know this is a call to a class method
1703 // whose type we can resolve. In such cases, promote the return type to
1704 // Class*.
1705 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1706}
1707
1708
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001709void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001710 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001711 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001712 Expr* Ex,
1713 Expr* Receiver,
1714 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00001715 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001716 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001717
Ted Kremeneka7338b42008-03-11 06:39:11 +00001718 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001719 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001720 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001721
1722 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001723 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001724 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001725 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001726 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001727
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001728 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001729 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001730 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001731
Ted Kremenek74556a12009-03-26 03:35:11 +00001732 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00001733 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1734 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1735 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001736 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001737 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001738 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001739 }
1740 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00001741 }
Ted Kremenekede40b72008-07-09 18:11:16 +00001742
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001743 if (isa<Loc>(V)) {
1744 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001745 if (GetArgE(Summ, idx) == DoNothingByRef)
1746 continue;
1747
1748 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001749
1750 // FIXME: Either this logic should also be replicated in GRSimpleVals
1751 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001752
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001753 // FIXME: We can have collisions on the conjured symbol if the
1754 // expression *I also creates conjured symbols. We probably want
1755 // to identify conjured symbols by an expression pair: the enclosing
1756 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001757 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001758
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001759 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001760
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001761 // Blast through TypedViewRegions to get the original region type.
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001762 while (R) {
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001763 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001764 if (!ATR) break;
1765 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1766 }
1767
Ted Kremenek53b24182009-03-04 22:56:43 +00001768 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001769 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001770 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001771
Ted Kremenek53b24182009-03-04 22:56:43 +00001772 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00001773 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001774
Ted Kremenek53b24182009-03-04 22:56:43 +00001775 if (R->isBoundable(Ctx)) {
1776 // Set the value of the variable to be a conjured symbol.
1777 unsigned Count = Builder.getCurrentBlockCount();
1778 QualType T = R->getRValueType(Ctx);
1779
Zhongxing Xu079dc352009-04-09 06:03:54 +00001780 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001781 ValueManager &ValMgr = Eng.getValueManager();
1782 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00001783 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00001784 }
1785 else if (const RecordType *RT = T->getAsStructureType()) {
1786 // Handle structs in a not so awesome way. Here we just
1787 // eagerly bind new symbols to the fields. In reality we
1788 // should have the store manager handle this. The idea is just
1789 // to prototype some basic functionality here. All of this logic
1790 // should one day soon just go away.
1791 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1792
1793 // No record definition. There is nothing we can do.
1794 if (!RD)
1795 continue;
1796
1797 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1798
1799 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001800 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
1801 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00001802
1803 // For now just handle scalar fields.
1804 FieldDecl *FD = *FI;
1805 QualType FT = FD->getType();
1806
1807 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001808 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00001809 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001810 ValueManager &ValMgr = Eng.getValueManager();
1811 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00001812 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00001813 }
1814 }
1815 }
1816 else {
1817 // Just blast away other values.
1818 state = state.BindLoc(*MR, UnknownVal());
1819 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00001820 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001821 }
1822 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001823 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001824 }
1825 else {
1826 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001827 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001828 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001829 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001830 else if (isa<nonloc::LocAsInteger>(V))
1831 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001832 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001833
Ted Kremenek272aa852008-06-25 21:21:56 +00001834 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001835 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001836 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00001837 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00001838 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1839 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1840 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00001841 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001842 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001843 }
Ted Kremenekb6578942009-02-24 19:15:11 +00001844 }
Ted Kremenek227c5372008-05-06 02:41:27 +00001845 }
1846 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001847
Ted Kremenek272aa852008-06-25 21:21:56 +00001848 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001849 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001850 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001851 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001852 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001853 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001854
Ted Kremenekf2717b02008-07-18 17:24:20 +00001855 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001856 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001857
1858 switch (RE.getKind()) {
1859 default:
1860 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001861
Ted Kremenek8f90e712008-10-17 22:23:12 +00001862 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001863
Ted Kremenek455dd862008-04-11 20:23:24 +00001864 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001865 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1866 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001867
Ted Kremenek8f90e712008-10-17 22:23:12 +00001868 // FIXME: We eventually should handle structs and other compound types
1869 // that are returned by value.
1870
1871 QualType T = Ex->getType();
1872
Ted Kremenek79413a52008-11-13 06:10:40 +00001873 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001874 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001875 ValueManager &ValMgr = Eng.getValueManager();
1876 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00001877 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001878 }
1879
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001880 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00001881 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001882
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001883 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001884 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001885 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001886 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001887 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00001888 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001889 break;
1890 }
1891
Ted Kremenek227c5372008-05-06 02:41:27 +00001892 case RetEffect::ReceiverAlias: {
1893 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001894 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00001895 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00001896 break;
1897 }
1898
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001899 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001900 case RetEffect::OwnedSymbol: {
1901 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00001902 ValueManager &ValMgr = Eng.getValueManager();
1903 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
1904 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
1905 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
1906 RetT));
1907 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00001908
1909 // FIXME: Add a flag to the checker where allocations are assumed to
1910 // *not fail.
1911#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00001912 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1913 bool isFeasible;
1914 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1915 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1916 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00001917#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001918
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001919 break;
1920 }
1921
1922 case RetEffect::NotOwnedSymbol: {
1923 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00001924 ValueManager &ValMgr = Eng.getValueManager();
1925 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
1926 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
1927 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
1928 RetT));
1929 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001930 break;
1931 }
1932 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001933
Ted Kremenek0dd65012009-02-18 02:00:25 +00001934 // Generate a sink node if we are at the end of a path.
1935 GRExprEngine::NodeTy *NewNode =
1936 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1937 : Builder.MakeNode(Dst, Ex, Pred, state);
1938
1939 // Annotate the edge with summary we used.
1940 // FIXME: This assumes that we always use the same summary when generating
1941 // this node.
1942 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001943}
1944
1945
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001946void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001947 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001948 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001949 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001950 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00001951 const FunctionDecl* FD = L.getAsFunctionDecl();
1952 RetainSummary* Summ = !FD ? 0
1953 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001954
1955 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1956 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001957}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001958
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001959void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001960 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001961 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001962 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001963 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00001964 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001965
Ted Kremenek272aa852008-06-25 21:21:56 +00001966 if (Expr* Receiver = ME->getReceiver()) {
1967 // We need the type-information of the tracked receiver object
1968 // Retrieve it from the state.
1969 ObjCInterfaceDecl* ID = 0;
1970
1971 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1972 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001973 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001974 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00001975
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001976 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00001977 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001978 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00001979 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001980
1981 if (const PointerType* PT = Ty->getAsPointerType()) {
1982 QualType PointeeTy = PT->getPointeeType();
1983
1984 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1985 ID = IT->getDecl();
1986 }
1987 }
1988 }
1989
1990 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00001991
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001992 // Special-case: are we sending a mesage to "self"?
1993 // This is a hack. When we have full-IP this should be removed.
1994 if (!Summ) {
1995 ObjCMethodDecl* MD =
1996 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1997
1998 if (MD) {
1999 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002000 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002001 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002002 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2003 // Create a summmary where all of the arguments "StopTracking".
2004 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2005 DoNothing,
2006 StopTracking);
2007 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002008 }
2009 }
2010 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002011 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002012 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002013 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002014
Ted Kremenek926abf22008-05-06 04:20:12 +00002015 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2016 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002017}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002018
2019namespace {
2020class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2021 GRStateRef state;
2022public:
2023 StopTrackingCallback(GRStateRef st) : state(st) {}
2024 GRStateRef getState() { return state; }
2025
2026 bool VisitSymbol(SymbolRef sym) {
2027 state = state.remove<RefBindings>(sym);
2028 return true;
2029 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002030
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002031 const GRState* getState() const { return state.getState(); }
2032};
2033} // end anonymous namespace
2034
2035
Ted Kremeneka42be302009-02-14 01:43:44 +00002036void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002037 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002038 bool escapes = false;
2039
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002040 // A value escapes in three possible cases (this may change):
2041 //
2042 // (1) we are binding to something that is not a memory region.
2043 // (2) we are binding to a memregion that does not have stack storage
2044 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002045 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002046 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002047
Ted Kremeneka42be302009-02-14 01:43:44 +00002048 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002049 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002050 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002051 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2052 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002053
2054 if (!escapes) {
2055 // To test (3), generate a new state with the binding removed. If it is
2056 // the same state, then it escapes (since the store cannot represent
2057 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002058 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002059 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002060 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002061
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002062 // If our store can represent the binding and we aren't storing to something
2063 // that doesn't have local storage then just return and have the simulation
2064 // state continue as is.
2065 if (!escapes)
2066 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002067
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002068 // Otherwise, find all symbols referenced by 'val' that we are tracking
2069 // and stop tracking them.
2070 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002071}
2072
Ted Kremenek0106e202008-10-24 20:32:50 +00002073std::pair<GRStateRef,bool>
2074CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2075 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002076 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002077 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002078
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002079 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00002080 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00002081 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002082
Ted Kremenek311f3d42008-10-22 23:56:21 +00002083 if (V.isReturnedOwned() && V.getCount() == 0)
2084 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00002085 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00002086 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00002087 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00002088 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2089 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00002090 }
2091 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002092
Ted Kremenek311f3d42008-10-22 23:56:21 +00002093 // All other cases.
2094
2095 hasLeak = V.isOwned() ||
2096 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002097
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002098 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002099 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002100
Ted Kremenek0106e202008-10-24 20:32:50 +00002101 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2102 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002103}
2104
Ted Kremenek541db372008-04-24 23:57:27 +00002105
Ted Kremenekffefc352008-04-11 22:25:11 +00002106
Ted Kremenek541db372008-04-24 23:57:27 +00002107// Dead symbols.
2108
Ted Kremenek708af042009-02-05 06:50:21 +00002109
Ted Kremenek541db372008-04-24 23:57:27 +00002110
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002111 // Return statements.
2112
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002113void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002114 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002115 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002116 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002117 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002118
2119 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002120 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002121 return;
2122
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002123 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002124 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002125
Ted Kremenek74556a12009-03-26 03:35:11 +00002126 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002127 return;
2128
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002129 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002130 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002131
2132 if (!T)
2133 return;
2134
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002135 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002136 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002137
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002138 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002139 case RefVal::Owned: {
2140 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002141 assert (cnt > 0);
2142 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002143 break;
2144 }
2145
2146 case RefVal::NotOwned: {
2147 unsigned cnt = X.getCount();
2148 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2149 : RefVal::makeReturnedNotOwned();
2150 break;
2151 }
2152
2153 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002154 return;
2155 }
2156
2157 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002158 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002159 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002160}
2161
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002162// Assumptions.
2163
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002164const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2165 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002166 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002167 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002168
2169 // FIXME: We may add to the interface of EvalAssume the list of symbols
2170 // whose assumptions have changed. For now we just iterate through the
2171 // bindings and check if any of the tracked symbols are NULL. This isn't
2172 // too bad since the number of symbols we will track in practice are
2173 // probably small and EvalAssume is only called at branches and a few
2174 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002175 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002176
2177 if (B.isEmpty())
2178 return St;
2179
2180 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002181
2182 GRStateRef state(St, VMgr);
2183 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002184
2185 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002186 // Check if the symbol is null (or equal to any constant).
2187 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002188 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002189 changed = true;
2190 B = RefBFactory.Remove(B, I.getKey());
2191 }
2192 }
2193
Ted Kremenek91781202008-08-17 03:20:02 +00002194 if (changed)
2195 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002196
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002197 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002198}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002199
Ted Kremenekb6578942009-02-24 19:15:11 +00002200GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2201 RefVal V, ArgEffect E,
2202 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002203
2204 // In GC mode [... release] and [... retain] do nothing.
2205 switch (E) {
2206 default: break;
2207 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2208 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002209 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00002210 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2211 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002212 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002213
Ted Kremenek6537a642009-03-17 19:42:23 +00002214 // Handle all use-after-releases.
2215 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
2216 V = V ^ RefVal::ErrorUseAfterRelease;
2217 hasErr = V.getKind();
2218 return state.set<RefBindings>(sym, V);
2219 }
2220
Ted Kremenek0d721572008-03-11 17:48:22 +00002221 switch (E) {
2222 default:
2223 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00002224
2225 case Dealloc:
2226 // Any use of -dealloc in GC is *bad*.
2227 if (isGCEnabled()) {
2228 V = V ^ RefVal::ErrorDeallocGC;
2229 hasErr = V.getKind();
2230 break;
2231 }
2232
2233 switch (V.getKind()) {
2234 default:
2235 assert(false && "Invalid case.");
2236 case RefVal::Owned:
2237 // The object immediately transitions to the released state.
2238 V = V ^ RefVal::Released;
2239 V.clearCounts();
2240 return state.set<RefBindings>(sym, V);
2241 case RefVal::NotOwned:
2242 V = V ^ RefVal::ErrorDeallocNotOwned;
2243 hasErr = V.getKind();
2244 break;
2245 }
2246 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002247
Ted Kremenekb7826ab2009-02-25 23:11:49 +00002248 case NewAutoreleasePool:
2249 assert(!isGCEnabled());
2250 return state.add<AutoreleaseStack>(sym);
2251
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002252 case MayEscape:
2253 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002254 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002255 break;
2256 }
Ted Kremenek6537a642009-03-17 19:42:23 +00002257
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002258 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00002259
Ted Kremenekede40b72008-07-09 18:11:16 +00002260 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002261 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00002262 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002263
Ted Kremenek9b112d22009-01-28 21:44:40 +00002264 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00002265 if (isGCEnabled())
2266 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00002267
2268 // Update the autorelease counts.
2269 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00002270
2271 // Fall-through.
2272
Ted Kremenek227c5372008-05-06 02:41:27 +00002273 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00002274 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002275
Ted Kremenek0d721572008-03-11 17:48:22 +00002276 case IncRef:
2277 switch (V.getKind()) {
2278 default:
2279 assert(false);
2280
2281 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002282 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002283 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002284 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002285 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002286 // Non-GC cases are handled above.
2287 assert(isGCEnabled());
2288 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002289 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002290 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002291 break;
2292
Ted Kremenek272aa852008-06-25 21:21:56 +00002293 case SelfOwn:
2294 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002295 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002296 case DecRef:
2297 switch (V.getKind()) {
2298 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00002299 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00002300 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002301
Ted Kremenek272aa852008-06-25 21:21:56 +00002302 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002303 assert(V.getCount() > 0);
2304 if (V.getCount() == 1) V = V ^ RefVal::Released;
2305 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002306 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002307
Ted Kremenek272aa852008-06-25 21:21:56 +00002308 case RefVal::NotOwned:
2309 if (V.getCount() > 0)
2310 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002311 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002312 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002313 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002314 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002315 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00002316
Ted Kremenek0d721572008-03-11 17:48:22 +00002317 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002318 // Non-GC cases are handled above.
2319 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00002320 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002321 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00002322 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002323 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002324 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002325 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002326 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002327}
2328
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002329//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002330// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002331//===----------------------------------------------------------------------===//
2332
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002333namespace {
2334
2335 //===-------------===//
2336 // Bug Descriptions. //
2337 //===-------------===//
2338
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002339 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002340 protected:
2341 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002342
2343 CFRefBug(CFRefCount* tf, const char* name)
2344 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002345 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002346
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002347 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002348 const CFRefCount& getTF() const { return TF; }
2349
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002350 // FIXME: Eventually remove.
2351 virtual const char* getDescription() const = 0;
2352
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002353 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002354 };
2355
2356 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2357 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002358 UseAfterRelease(CFRefCount* tf)
Ted Kremenek5b1ab102009-04-03 21:10:31 +00002359 : CFRefBug(tf, "Use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002360
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002361 const char* getDescription() const {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002362 return "Reference-counted object is used after it is released";
Ted Kremenek708af042009-02-05 06:50:21 +00002363 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002364 };
2365
2366 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2367 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002368 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2369
2370 const char* getDescription() const {
Ted Kremeneke4158502009-04-23 19:11:35 +00002371 return "Incorrect decrement of the reference count of an "
2372 "object is not owned at this point by the caller";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002373 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002374 };
2375
Ted Kremenek6537a642009-03-17 19:42:23 +00002376 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2377 public:
2378 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
2379 "-dealloc called while using GC") {}
2380
2381 const char *getDescription() const {
2382 return "-dealloc called while using GC";
2383 }
2384 };
2385
2386 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2387 public:
2388 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
2389 "-dealloc sent to non-exclusively owned object") {}
2390
2391 const char *getDescription() const {
2392 return "-dealloc sent to object that may be referenced elsewhere";
2393 }
2394 };
2395
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002396 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002397 const bool isReturn;
2398 protected:
2399 Leak(CFRefCount* tf, const char* name, bool isRet)
2400 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002401 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002402
Ted Kremenek44274e62009-02-07 22:38:00 +00002403 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002404
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002405 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002406 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002407
2408 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2409 public:
2410 LeakAtReturn(CFRefCount* tf, const char* name)
2411 : Leak(tf, name, true) {}
2412 };
2413
2414 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2415 public:
2416 LeakWithinFunction(CFRefCount* tf, const char* name)
2417 : Leak(tf, name, false) {}
2418 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002419
2420 //===---------===//
2421 // Bug Reports. //
2422 //===---------===//
2423
2424 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002425 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002426 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002427 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002428 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002429 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2430 ExplodedNode<GRState> *n, SymbolRef sym)
2431 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002432
2433 virtual ~CFRefReport() {}
2434
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002435 CFRefBug& getBugType() {
2436 return (CFRefBug&) RangedBugReport::getBugType();
2437 }
2438 const CFRefBug& getBugType() const {
2439 return (const CFRefBug&) RangedBugReport::getBugType();
2440 }
2441
2442 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2443 const SourceRange*& end) {
2444
Ted Kremenek198cae02008-05-02 20:53:50 +00002445 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002446 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002447 else
2448 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002449 }
2450
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002451 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002452
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002453 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2454 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002455
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002456 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002457
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002458 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2459 const ExplodedNode<GRState>* PrevN,
2460 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002461 BugReporter& BR,
2462 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002463 };
2464
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002465 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002466 SourceLocation AllocSite;
2467 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002468 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002469 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2470 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002471 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002472
2473 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2474 const ExplodedNode<GRState>* N);
2475
Ted Kremenek86617f42009-02-07 22:19:59 +00002476 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002477 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002478} // end anonymous namespace
2479
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002480void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002481 useAfterRelease = new UseAfterRelease(this);
2482 BR.Register(useAfterRelease);
2483
2484 releaseNotOwned = new BadRelease(this);
2485 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002486
Ted Kremenek6537a642009-03-17 19:42:23 +00002487 deallocGC = new DeallocGC(this);
2488 BR.Register(deallocGC);
2489
2490 deallocNotOwned = new DeallocNotOwned(this);
2491 BR.Register(deallocNotOwned);
2492
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002493 // First register "return" leaks.
2494 const char* name = 0;
2495
2496 if (isGCEnabled())
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002497 name = "Leak of returned object when using garbage collection";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002498 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002499 name = "Leak of returned object when not using garbage collection (GC) in "
2500 "dual GC/non-GC code";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002501 else {
2502 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002503 name = "Leak of returned object";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002504 }
2505
Ted Kremenek708af042009-02-05 06:50:21 +00002506 leakAtReturn = new LeakAtReturn(this, name);
2507 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002508
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002509 // Second, register leaks within a function/method.
2510 if (isGCEnabled())
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002511 name = "Leak of object when using garbage collection";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002512 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002513 name = "Leak of object when not using garbage collection (GC) in "
2514 "dual GC/non-GC code";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002515 else {
2516 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002517 name = "Leak";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002518 }
2519
Ted Kremenek708af042009-02-05 06:50:21 +00002520 leakWithinFunction = new LeakWithinFunction(this, name);
2521 BR.Register(leakWithinFunction);
2522
2523 // Save the reference to the BugReporter.
2524 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002525}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002526
2527static const char* Msgs[] = {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002528 // GC only
2529 "Code is compiled to only use garbage collection",
2530 // No GC.
Ted Kremeneka9203882009-03-05 00:12:45 +00002531 "Code is compiled to use reference counts",
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002532 // Hybrid, with GC.
2533 "Code is compiled to use either garbage collection (GC) or reference counts"
2534 " (non-GC). The bug occurs with GC enabled",
2535 // Hybrid, without GC
2536 "Code is compiled to use either garbage collection (GC) or reference counts"
2537 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002538};
2539
2540std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2541 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2542
2543 switch (TF.getLangOptions().getGCMode()) {
2544 default:
2545 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002546
2547 case LangOptions::GCOnly:
2548 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002549 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2550
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002551 case LangOptions::NonGC:
2552 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002553 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2554
2555 case LangOptions::HybridGC:
2556 if (TF.isGCEnabled())
2557 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2558 else
2559 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2560 }
2561}
2562
Ted Kremenek2126bef2009-02-18 21:57:45 +00002563static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2564 ArgEffect X) {
2565 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2566 I!=E; ++I)
2567 if (*I == X) return true;
2568
2569 return false;
2570}
2571
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002572PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2573 const ExplodedNode<GRState>* PrevN,
2574 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002575 BugReporter& BR,
2576 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002577
Ted Kremenek71745d92009-01-28 05:29:13 +00002578 // Check if the type state has changed.
2579 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2580 GRStateRef PrevSt(PrevN->getState(), StMgr);
2581 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002582
Ted Kremenek71745d92009-01-28 05:29:13 +00002583 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2584 if (!CurrT) return NULL;
2585
2586 const RefVal& CurrV = *CurrT;
2587 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002588
Ted Kremenek2126bef2009-02-18 21:57:45 +00002589 // Create a string buffer to constain all the useful things we want
2590 // to tell the user.
2591 std::string sbuf;
2592 llvm::raw_string_ostream os(sbuf);
2593
Ted Kremenekc26c4692009-02-18 03:48:14 +00002594 // This is the allocation site since the previous node had no bindings
2595 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002596 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002597 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2598
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002599 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2600 // Get the name of the callee (if it is available).
Zhongxing Xucac107a2009-04-20 05:24:46 +00002601 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2602 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2603 os << "Call to function '" << FD->getNameAsString() <<'\'';
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002604 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002605 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002606 }
2607 else {
2608 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002609 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002610 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002611
Ted Kremenek18878b12009-01-28 06:06:36 +00002612 if (CurrV.getObjKind() == RetEffect::CF) {
2613 os << " returns a Core Foundation object with a ";
2614 }
2615 else {
2616 assert (CurrV.getObjKind() == RetEffect::ObjC);
2617 os << " returns an Objective-C object with a ";
2618 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002619
Ted Kremenekabe30922009-01-28 06:25:48 +00002620 if (CurrV.isOwned()) {
2621 os << "+1 retain count (owning reference).";
2622
2623 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2624 assert(CurrV.getObjKind() == RetEffect::CF);
2625 os << " "
2626 "Core Foundation objects are not automatically garbage collected.";
2627 }
2628 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002629 else {
2630 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002631 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002632 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002633
Ted Kremenek2fba6152009-04-01 06:13:56 +00002634 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2635 return new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002636 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002637
Ted Kremenek2126bef2009-02-18 21:57:45 +00002638 // Gather up the effects that were performed on the object at this
2639 // program point
2640 llvm::SmallVector<ArgEffect, 2> AEffects;
2641
Ted Kremenekc26c4692009-02-18 03:48:14 +00002642 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2643 // We only have summaries attached to nodes after evaluating CallExpr and
2644 // ObjCMessageExprs.
2645 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2646
Ted Kremenekc26c4692009-02-18 03:48:14 +00002647 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2648 // Iterate through the parameter expressions and see if the symbol
2649 // was ever passed as an argument.
2650 unsigned i = 0;
2651
2652 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2653 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002654
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002655 // Retrieve the value of the argument. Is it the symbol
2656 // we are interested in?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002657 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002658 continue;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002659
Ted Kremenekc26c4692009-02-18 03:48:14 +00002660 // We have an argument. Get the effect!
2661 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002662 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002663 }
2664 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002665 if (Expr *receiver = ME->getReceiver())
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002666 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002667 // The symbol we are tracking is the receiver.
2668 AEffects.push_back(Summ->getReceiverEffect());
2669 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002670 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002671 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002672
Ted Kremenek2126bef2009-02-18 21:57:45 +00002673 do {
2674 // Get the previous type state.
2675 RefVal PrevV = *PrevT;
Ted Kremenek6537a642009-03-17 19:42:23 +00002676
2677 // Specially handle -dealloc.
2678 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2679 // Determine if the object's reference count was pushed to zero.
2680 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2681 // We may not have transitioned to 'release' if we hit an error.
2682 // This case is handled elsewhere.
2683 if (CurrV.getKind() == RefVal::Released) {
2684 assert(CurrV.getCount() == 0);
2685 os << "Object released by directly sending the '-dealloc' message";
2686 break;
2687 }
2688 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002689
2690 // Specially handle CFMakeCollectable and friends.
2691 if (contains(AEffects, MakeCollectable)) {
2692 // Get the name of the function.
2693 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Zhongxing Xucac107a2009-04-20 05:24:46 +00002694 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2695 const FunctionDecl* FD = X.getAsFunctionDecl();
2696 const std::string& FName = FD->getNameAsString();
Ted Kremenek2126bef2009-02-18 21:57:45 +00002697
2698 if (TF.isGCEnabled()) {
2699 // Determine if the object's reference count was pushed to zero.
2700 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2701
2702 os << "In GC mode a call to '" << FName
2703 << "' decrements an object's retain count and registers the "
2704 "object with the garbage collector. ";
2705
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002706 if (CurrV.getKind() == RefVal::Released) {
2707 assert(CurrV.getCount() == 0);
2708 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002709 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002710 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002711 else
2712 os << "An object must have a 0 retain count to be garbage collected. "
2713 "After this call its retain count is +" << CurrV.getCount()
2714 << '.';
2715 }
2716 else
2717 os << "When GC is not enabled a call to '" << FName
2718 << "' has no effect on its argument.";
2719
2720 // Nothing more to say.
2721 break;
2722 }
2723
2724 // Determine if the typestate has changed.
2725 if (!(PrevV == CurrV))
2726 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002727 case RefVal::Owned:
2728 case RefVal::NotOwned:
2729
2730 if (PrevV.getCount() == CurrV.getCount())
2731 return 0;
2732
2733 if (PrevV.getCount() > CurrV.getCount())
2734 os << "Reference count decremented.";
2735 else
2736 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002737
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002738 if (unsigned Count = CurrV.getCount())
2739 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002740
2741 if (PrevV.getKind() == RefVal::Released) {
2742 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2743 os << " The object is not eligible for garbage collection until the "
2744 "retain count reaches 0 again.";
2745 }
2746
Ted Kremenekc26c4692009-02-18 03:48:14 +00002747 break;
2748
2749 case RefVal::Released:
2750 os << "Object released.";
2751 break;
2752
2753 case RefVal::ReturnedOwned:
2754 os << "Object returned to caller as an owning reference (single retain "
2755 "count transferred to caller).";
2756 break;
2757
2758 case RefVal::ReturnedNotOwned:
2759 os << "Object returned to caller with a +0 (non-owning) retain count.";
2760 break;
2761
2762 default:
2763 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002764 }
2765
2766 // Emit any remaining diagnostics for the argument effects (if any).
2767 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2768 E=AEffects.end(); I != E; ++I) {
2769
2770 // A bunch of things have alternate behavior under GC.
2771 if (TF.isGCEnabled())
2772 switch (*I) {
2773 default: break;
2774 case Autorelease:
2775 os << "In GC mode an 'autorelease' has no effect.";
2776 continue;
2777 case IncRefMsg:
2778 os << "In GC mode the 'retain' message has no effect.";
2779 continue;
2780 case DecRefMsg:
2781 os << "In GC mode the 'release' message has no effect.";
2782 continue;
2783 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002784 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002785 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002786
2787 if (os.str().empty())
2788 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002789
2790 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek2fba6152009-04-01 06:13:56 +00002791 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
Ted Kremenek23563642009-03-06 23:58:11 +00002792 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002793
2794 // Add the range by scanning the children of the statement for any bindings
2795 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002796 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002797 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002798 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002799 P->addRange(Exp->getSourceRange());
2800 break;
2801 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002802
2803 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002804}
2805
Ted Kremenekb15eba42008-10-04 05:50:14 +00002806namespace {
2807class VISIBILITY_HIDDEN FindUniqueBinding :
2808 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002809 SymbolRef Sym;
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002810 const MemRegion* Binding;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002811 bool First;
2812
2813 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002814 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002815
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002816 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2817 SVal val) {
Ted Kremenek74556a12009-03-26 03:35:11 +00002818
2819 SymbolRef SymV = val.getAsSymbol();
2820 if (!SymV || SymV != Sym)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002821 return true;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002822
Ted Kremenekb15eba42008-10-04 05:50:14 +00002823 if (Binding) {
2824 First = false;
2825 return false;
2826 }
2827 else
2828 Binding = R;
2829
2830 return true;
2831 }
2832
2833 operator bool() { return First && Binding; }
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002834 const MemRegion* getRegion() { return Binding; }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002835};
2836}
2837
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002838static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00002839GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002840 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00002841
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002842 // Find both first node that referred to the tracked symbol and the
2843 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002844 const ExplodedNode<GRState>* Last = N;
2845 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002846
2847 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002848 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002849 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002850
Ted Kremenek6064a362008-07-07 16:21:19 +00002851 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002852 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002853
Ted Kremenek86617f42009-02-07 22:19:59 +00002854 FindUniqueBinding FB(Sym);
2855 StateMgr.iterBindings(St, FB);
2856 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002857
Ted Kremenekd7e26782008-05-16 18:33:44 +00002858 Last = N;
2859 N = N->pred_empty() ? NULL : *(N->pred_begin());
2860 }
2861
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002862 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002863}
Ted Kremenek4c479322008-05-06 23:07:13 +00002864
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002865PathDiagnosticPiece*
2866CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002867 // Tell the BugReporter to report cases when the tracked symbol is
2868 // assigned to different variables, etc.
Ted Kremenek6537a642009-03-17 19:42:23 +00002869 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002870 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002871 return RangedBugReport::getEndPath(BR, EndN);
2872}
2873
2874PathDiagnosticPiece*
2875CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2876
2877 GRBugReporter& BR = cast<GRBugReporter>(br);
2878 // Tell the BugReporter to report cases when the tracked symbol is
2879 // assigned to different variables, etc.
2880 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2881
2882 // We are reporting a leak. Walk up the graph to get to the first node where
2883 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00002884 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002885 const ExplodedNode<GRState>* AllocNode = 0;
2886 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002887
2888 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00002889 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002890
Ted Kremenekd7e26782008-05-16 18:33:44 +00002891 // Get the allocate site.
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00002892 assert(AllocNode);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002893 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002894
Ted Kremenekea794e92008-05-05 18:50:19 +00002895 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00002896 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002897
Ted Kremenek505dc672009-04-07 04:54:20 +00002898 // Compute an actual location for the leak. Sometimes a leak doesn't
2899 // occur at an actual statement (e.g., transition between blocks; end
2900 // of function) so we need to walk the graph and compute a real location.
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00002901 const ExplodedNode<GRState>* LeakN = EndN;
2902 PathDiagnosticLocation L;
2903
2904 while (LeakN) {
2905 ProgramPoint P = LeakN->getLocation();
2906
2907 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2908 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2909 break;
2910 }
2911 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2912 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2913 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2914 break;
2915 }
2916 }
2917
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00002918 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2919 }
2920
2921 if (!L.isValid()) {
Douglas Gregore3241e92009-04-18 00:02:19 +00002922 CompoundStmt *CS
2923 = BR.getStateManager().getCodeDecl().getBody(BR.getContext());
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00002924 L = PathDiagnosticLocation(CS->getRBracLoc(), SMgr);
2925 }
2926
Ted Kremenek59f9fe12009-02-07 21:59:45 +00002927 std::string sbuf;
2928 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00002929
Ted Kremenekea794e92008-05-05 18:50:19 +00002930 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002931
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002932 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002933 os << " and stored into '" << FirstBinding->getString() << '\'';
2934
Ted Kremenek311f3d42008-10-22 23:56:21 +00002935 // Get the retain count.
2936 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2937
2938 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00002939 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2940 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2941 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00002942 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2943 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00002944 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00002945 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00002946 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002947 " in the Memory Management Guide for Cocoa (object leaked).";
2948 }
2949 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00002950 os << " is no longer referenced after this point and has a retain count of"
2951 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002952 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002953
Ted Kremenek23563642009-03-06 23:58:11 +00002954 return new PathDiagnosticEventPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002955}
2956
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002957
Ted Kremenekc26c4692009-02-18 03:48:14 +00002958CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2959 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00002960 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002961 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00002962{
2963
Ted Kremenekd7e26782008-05-16 18:33:44 +00002964 // Most bug reports are cached at the location where they occured.
2965 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00002966 // allocated, and only report a single path. To do this, we need to find
2967 // the allocation site of a piece of tracked memory, which we do via a
2968 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2969 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2970 // that all ancestor nodes that represent the allocation site have the
2971 // same SourceLocation.
2972 const ExplodedNode<GRState>* AllocNode = 0;
2973
2974 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00002975 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00002976
Ted Kremenek86617f42009-02-07 22:19:59 +00002977 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00002978 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00002979 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00002980
2981 // Fill in the description of the bug.
2982 Description.clear();
2983 llvm::raw_string_ostream os(Description);
2984 SourceManager& SMgr = Eng.getContext().getSourceManager();
2985 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00002986 os << "Potential leak of object allocated on line " << AllocLine;
2987
2988 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2989 if (AllocBinding)
Ted Kremenek5ee01662009-04-02 03:42:38 +00002990 os << " and stored into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00002991}
2992
Ted Kremeneka7338b42008-03-11 06:39:11 +00002993//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00002994// Handle dead symbols and end-of-path.
2995//===----------------------------------------------------------------------===//
2996
2997void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2998 GREndPathNodeBuilder<GRState>& Builder) {
2999
3000 const GRState* St = Builder.getState();
3001 RefBindings B = St->get<RefBindings>();
3002
3003 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3004 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3005
3006 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3007 bool hasLeak = false;
3008
3009 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003010 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3011 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003012
3013 St = X.first;
3014 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3015 }
3016
3017 if (Leaked.empty())
3018 return;
3019
3020 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3021
3022 if (!N)
3023 return;
3024
3025 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3026 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3027
3028 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3029 : leakWithinFunction);
3030 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003031 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003032 BR->EmitReport(report);
3033 }
3034}
3035
3036void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3037 GRExprEngine& Eng,
3038 GRStmtNodeBuilder<GRState>& Builder,
3039 ExplodedNode<GRState>* Pred,
3040 Stmt* S,
3041 const GRState* St,
3042 SymbolReaper& SymReaper) {
3043
Ted Kremenek876d8df2009-02-19 23:47:02 +00003044 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003045 RefBindings B = St->get<RefBindings>();
3046 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3047
3048 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3049 E = SymReaper.dead_end(); I != E; ++I) {
3050
3051 const RefVal* T = B.lookup(*I);
3052 if (!T) continue;
3053
3054 bool hasLeak = false;
3055
3056 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003057 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003058
3059 St = X.first;
3060
3061 if (hasLeak)
3062 Leaked.push_back(std::make_pair(*I,X.second));
3063 }
3064
Ted Kremenek876d8df2009-02-19 23:47:02 +00003065 if (!Leaked.empty()) {
3066 // Create a new intermediate node representing the leak point. We
3067 // use a special program point that represents this checker-specific
3068 // transition. We use the address of RefBIndex as a unique tag for this
3069 // checker. We will create another node (if we don't cache out) that
3070 // removes the retain-count bindings from the state.
3071 // NOTE: We use 'generateNode' so that it does interplay with the
3072 // auto-transition logic.
3073 ExplodedNode<GRState>* N =
3074 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003075
Ted Kremenek876d8df2009-02-19 23:47:02 +00003076 if (!N)
3077 return;
3078
3079 // Generate the bug reports.
3080 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3081 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3082
3083 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3084 : leakWithinFunction);
3085 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003086 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3087 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003088 BR->EmitReport(report);
3089 }
Ted Kremenek708af042009-02-05 06:50:21 +00003090
Ted Kremenek876d8df2009-02-19 23:47:02 +00003091 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003092 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003093
3094 // Now generate a new node that nukes the old bindings.
3095 GRStateRef state(St, Eng.getStateManager());
3096 RefBindings::Factory& F = state.get_context<RefBindings>();
3097
3098 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3099 E = SymReaper.dead_end(); I!=E; ++I)
3100 B = F.Remove(B, *I);
3101
3102 state = state.set<RefBindings>(B);
3103 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003104}
3105
3106void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3107 GRStmtNodeBuilder<GRState>& Builder,
3108 Expr* NodeExpr, Expr* ErrorExpr,
3109 ExplodedNode<GRState>* Pred,
3110 const GRState* St,
3111 RefVal::Kind hasErr, SymbolRef Sym) {
3112 Builder.BuildSinks = true;
3113 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3114
3115 if (!N) return;
3116
3117 CFRefBug *BT = 0;
3118
Ted Kremenek6537a642009-03-17 19:42:23 +00003119 switch (hasErr) {
3120 default:
3121 assert(false && "Unhandled error.");
3122 return;
3123 case RefVal::ErrorUseAfterRelease:
3124 BT = static_cast<CFRefBug*>(useAfterRelease);
3125 break;
3126 case RefVal::ErrorReleaseNotOwned:
3127 BT = static_cast<CFRefBug*>(releaseNotOwned);
3128 break;
3129 case RefVal::ErrorDeallocGC:
3130 BT = static_cast<CFRefBug*>(deallocGC);
3131 break;
3132 case RefVal::ErrorDeallocNotOwned:
3133 BT = static_cast<CFRefBug*>(deallocNotOwned);
3134 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003135 }
3136
Ted Kremenekc26c4692009-02-18 03:48:14 +00003137 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003138 report->addRange(ErrorExpr->getSourceRange());
3139 BR->EmitReport(report);
3140}
3141
3142//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003143// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003144//===----------------------------------------------------------------------===//
3145
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003146GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3147 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003148 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003149}