blob: c2369abb2cf6bb35a28b78869110bfbb677f935d [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 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000662
663 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000664 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000665
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000666 while (const char* s = va_arg(argp, const char*))
667 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000668
669 return Ctx.Selectors.getSelector(II.size(), &II[0]);
670 }
671
672 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
673 RetainSummary* Summ, va_list argp) {
674 Selector S = generateSelector(argp);
675 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000676 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000677
678 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
679 va_list argp;
680 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000681 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000682 va_end(argp);
683 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000684
685 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
686 va_list argp;
687 va_start(argp, Summ);
688 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
689 va_end(argp);
690 }
691
692 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
693 va_list argp;
694 va_start(argp, Summ);
695 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
696 va_end(argp);
697 }
698
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000699 void addPanicSummary(const char* Cls, ...) {
700 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
701 DoNothing, DoNothing, true);
702 va_list argp;
703 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000704 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000705 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000706 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000707
Ted Kremeneka7338b42008-03-11 06:39:11 +0000708public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000709
710 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000711 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000712 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000713 GCEnabled(gcenabled), StopSummary(0) {
714
715 InitializeClassMethodSummaries();
716 InitializeMethodSummaries();
717 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000718
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000719 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000720
Ted Kremenekd13c1872008-06-24 03:56:45 +0000721 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000722 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenekb17fa952009-04-23 21:25:57 +0000723 RetainSummary* getClassMethodSummary(ObjCMessageExpr *ME);
Ted Kremenekaca0b452009-04-24 18:19:07 +0000724 RetainSummary* getCommonMethodSummary(ObjCMessageExpr *ME, Selector S);
Ted Kremenek923fc392009-04-24 23:32:32 +0000725 RetainSummary* getMethodSummaryFromAnnotations(ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000726
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000727 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000728};
729
730} // end anonymous namespace
731
732//===----------------------------------------------------------------------===//
733// Implementation of checker data structures.
734//===----------------------------------------------------------------------===//
735
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000736RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000737
738 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
739 // mitigating the need to do explicit cleanup of the
740 // Argument-Effect summaries.
741
Ted Kremenek42ea0322008-05-05 23:55:01 +0000742 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
743 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000744 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000745}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000746
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000747ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000748
Ted Kremenekae855d42008-04-24 17:22:33 +0000749 if (ScratchArgs.empty())
750 return NULL;
751
752 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000753 llvm::FoldingSetNodeID profile;
754 profile.Add(ScratchArgs);
755 void* InsertPos;
756
Ted Kremenekae855d42008-04-24 17:22:33 +0000757 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000758 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000759 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000760
Ted Kremenekae855d42008-04-24 17:22:33 +0000761 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000762 ScratchArgs.clear();
763 return &E->getValue();
764 }
765
766 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000767 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000768
769 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000770 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000771
772 ScratchArgs.clear();
773 return &E->getValue();
774}
775
Ted Kremenek266d8b62008-05-06 02:26:56 +0000776RetainSummary*
777RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000778 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000779 ArgEffect DefaultEff,
780 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000781
Ted Kremenekae855d42008-04-24 17:22:33 +0000782 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000783 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000784 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
785 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000786
Ted Kremenekae855d42008-04-24 17:22:33 +0000787 // Look up the uniqued summary, or create one if it doesn't exist.
788 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000789 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000790
791 if (Summ)
792 return Summ;
793
Ted Kremenekae855d42008-04-24 17:22:33 +0000794 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000795 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000796 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000797 SummarySet.InsertNode(Summ, InsertPos);
798
799 return Summ;
800}
801
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000802//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000803// Predicates.
804//===----------------------------------------------------------------------===//
805
Ted Kremenek0d813552009-04-23 22:11:07 +0000806bool RetainSummaryManager::isTrackedObjectType(QualType Ty) {
807 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000808 return false;
809
Ted Kremenek0d813552009-04-23 22:11:07 +0000810 // We assume that id<..>, id, and "Class" all represent tracked objects.
811 const PointerType *PT = Ty->getAsPointerType();
812 if (PT == 0)
813 return true;
814
815 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000816
817 // We assume that id<..>, id, and "Class" all represent tracked objects.
818 if (!OT)
819 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000820
821 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000822 // FIXME: We can memoize here if this gets too expensive.
823 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
824 ObjCInterfaceDecl* ID = OT->getDecl();
825
826 for ( ; ID ; ID = ID->getSuperClass())
827 if (ID->getIdentifier() == NSObjectII)
828 return true;
829
830 return false;
831}
832
833//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000834// Summary creation for functions (largely uses of Core Foundation).
835//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000836
Ted Kremenek17144e82009-01-12 21:45:02 +0000837static bool isRetain(FunctionDecl* FD, const char* FName) {
838 const char* loc = strstr(FName, "Retain");
839 return loc && loc[sizeof("Retain")-1] == '\0';
840}
841
842static bool isRelease(FunctionDecl* FD, const char* FName) {
843 const char* loc = strstr(FName, "Release");
844 return loc && loc[sizeof("Release")-1] == '\0';
845}
846
Ted Kremenekd13c1872008-06-24 03:56:45 +0000847RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000848
849 SourceLocation Loc = FD->getLocation();
850
851 if (!Loc.isFileID())
852 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000853
Ted Kremenekae855d42008-04-24 17:22:33 +0000854 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000855 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000856
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000857 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000858 return I->second;
859
860 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000861 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000862
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000863 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000864 // We generate "stop" summaries for implicitly defined functions.
865 if (FD->isImplicit()) {
866 S = getPersistentStopSummary();
867 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000868 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000869
Ted Kremenek064ef322009-02-23 16:51:39 +0000870 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000871 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000872 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000873 const char* FName = FD->getIdentifier()->getName();
874
Ted Kremenek38c6f022009-03-05 22:11:14 +0000875 // Strip away preceding '_'. Doing this here will effect all the checks
876 // down below.
877 while (*FName == '_') ++FName;
878
Ted Kremenek17144e82009-01-12 21:45:02 +0000879 // Inspect the result type.
880 QualType RetTy = FT->getResultType();
881
882 // FIXME: This should all be refactored into a chain of "summary lookup"
883 // filters.
884 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
885 // FIXES: <rdar://problem/6326900>
886 // This should be addressed using a API table. This strcmp is also
887 // a little gross, but there is no need to super optimize here.
888 assert (ScratchArgs.empty());
889 ScratchArgs.push_back(std::make_pair(1, DecRef));
890 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
891 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000892 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000893
894 // Enable this code once the semantics of NSDeallocateObject are resolved
895 // for GC. <rdar://problem/6619988>
896#if 0
897 // Handle: NSDeallocateObject(id anObject);
898 // This method does allow 'nil' (although we don't check it now).
899 if (strcmp(FName, "NSDeallocateObject") == 0) {
900 return RetTy == Ctx.VoidTy
901 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
902 : getPersistentStopSummary();
903 }
904#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000905
906 // Handle: id NSMakeCollectable(CFTypeRef)
907 if (strcmp(FName, "NSMakeCollectable") == 0) {
908 S = (RetTy == Ctx.getObjCIdType())
909 ? getUnarySummary(FT, cfmakecollectable)
910 : getPersistentStopSummary();
911
912 break;
913 }
914
915 if (RetTy->isPointerType()) {
916 // For CoreFoundation ('CF') types.
917 if (isRefType(RetTy, "CF", &Ctx, FName)) {
918 if (isRetain(FD, FName))
919 S = getUnarySummary(FT, cfretain);
920 else if (strstr(FName, "MakeCollectable"))
921 S = getUnarySummary(FT, cfmakecollectable);
922 else
923 S = getCFCreateGetRuleSummary(FD, FName);
924
925 break;
926 }
927
928 // For CoreGraphics ('CG') types.
929 if (isRefType(RetTy, "CG", &Ctx, FName)) {
930 if (isRetain(FD, FName))
931 S = getUnarySummary(FT, cfretain);
932 else
933 S = getCFCreateGetRuleSummary(FD, FName);
934
935 break;
936 }
937
938 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
939 if (isRefType(RetTy, "DADisk") ||
940 isRefType(RetTy, "DADissenter") ||
941 isRefType(RetTy, "DASessionRef")) {
942 S = getCFCreateGetRuleSummary(FD, FName);
943 break;
944 }
945
946 break;
947 }
948
949 // Check for release functions, the only kind of functions that we care
950 // about that don't return a pointer type.
951 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000952 // Test for 'CGCF'.
953 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
954 FName += 4;
955 else
956 FName += 2;
957
958 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000959 S = getUnarySummary(FT, cfrelease);
960 else {
Ted Kremenek7b293682009-01-29 22:45:13 +0000961 assert (ScratchArgs.empty());
962 // Remaining CoreFoundation and CoreGraphics functions.
963 // We use to assume that they all strictly followed the ownership idiom
964 // and that ownership cannot be transferred. While this is technically
965 // correct, many methods allow a tracked object to escape. For example:
966 //
967 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
968 // CFDictionaryAddValue(y, key, x);
969 // CFRelease(x);
970 // ... it is okay to use 'x' since 'y' has a reference to it
971 //
972 // We handle this and similar cases with the follow heuristic. If the
973 // function name contains "InsertValue", "SetValue" or "AddValue" then
974 // we assume that arguments may "escape."
975 //
976 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
977 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000978 CStrInCStrNoCase(FName, "SetValue") ||
979 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000980 ? MayEscape : DoNothing;
981
982 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000983 }
984 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000985 }
986 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000987
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000988 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000989 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000990}
991
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000992RetainSummary*
993RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
994 const char* FName) {
995
Ted Kremenek562c1302008-05-05 16:51:50 +0000996 if (strstr(FName, "Create") || strstr(FName, "Copy"))
997 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000998
Ted Kremenek562c1302008-05-05 16:51:50 +0000999 if (strstr(FName, "Get"))
1000 return getCFSummaryGetRule(FD);
1001
1002 return 0;
1003}
1004
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001005RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001006RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1007 UnaryFuncKind func) {
1008
Ted Kremenek17144e82009-01-12 21:45:02 +00001009 // Sanity check that this is *really* a unary function. This can
1010 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001011 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001012 if (!FTP || FTP->getNumArgs() != 1)
1013 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001014
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001015 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001016
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001017 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +00001018 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001019 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001020 return getPersistentSummary(RetEffect::MakeAlias(0),
1021 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001022 }
1023
1024 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001025 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001026 return getPersistentSummary(RetEffect::MakeNoRet(),
1027 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001028 }
1029
1030 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +00001031 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1032 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001033 }
1034
1035 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001036 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001037 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001038 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001039}
1040
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001041RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001042 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001043
1044 if (FD->getIdentifier() == CFDictionaryCreateII) {
1045 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1046 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1047 }
1048
Ted Kremenek68621b92009-01-28 05:56:51 +00001049 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001050}
1051
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001052RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001053 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001054 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1055 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001056}
1057
Ted Kremeneka7338b42008-03-11 06:39:11 +00001058//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001059// Summary creation for Selectors.
1060//===----------------------------------------------------------------------===//
1061
Ted Kremenekbcaff792008-05-06 15:44:25 +00001062RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001063RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001064 assert(ScratchArgs.empty());
1065
Ted Kremenek802cfc72009-02-20 00:05:35 +00001066 // 'init' methods only return an alias if the return type is a location type.
1067 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001068 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +00001069 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1070 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001071
Ted Kremenek272aa852008-06-25 21:21:56 +00001072 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001073 return Summ;
1074}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001075
Ted Kremenek923fc392009-04-24 23:32:32 +00001076RetainSummary*
1077RetainSummaryManager::getMethodSummaryFromAnnotations(ObjCMethodDecl *MD) {
1078 if (!MD)
1079 return 0;
1080
1081 assert(ScratchArgs.empty());
1082
1083 // Determine if there is a special return effect for this method.
1084 bool hasRetEffect = false;
1085 RetEffect RE = RetEffect::MakeNoRet();
1086
1087 if (isTrackedObjectType(MD->getResultType())) {
1088 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
1089 RE = RetEffect::MakeOwned(RetEffect::ObjC, true);
1090 hasRetEffect = true;
1091 }
1092 else {
1093 // Default to 'not owned'.
1094 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1095 }
1096 }
1097
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001098 // Determine if there are any arguments with a specific ArgEffect.
1099 bool hasArgEffect = false;
1100 unsigned i = 0;
1101 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1102 E = MD->param_end(); I != E; ++I, ++i) {
1103 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
1104 ScratchArgs.push_back(std::make_pair(i, IncRefMsg));
1105 hasArgEffect = true;
1106 }
1107}
1108
1109 if (!hasRetEffect && !hasArgEffect)
Ted Kremenek923fc392009-04-24 23:32:32 +00001110 return 0;
1111
1112 return getPersistentSummary(RE);
1113}
Ted Kremenek272aa852008-06-25 21:21:56 +00001114
Ted Kremenekbcaff792008-05-06 15:44:25 +00001115RetainSummary*
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001116RetainSummaryManager::getCommonMethodSummary(ObjCMessageExpr* ME, Selector S) {
1117
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001118 if (ObjCMethodDecl *MD = ME->getMethodDecl()) {
1119 // Scan the method decl for 'void*' arguments. These should be treated
1120 // as 'StopTracking' because they are often used with delegates.
1121 // Delegates are a frequent form of false positives with the retain
1122 // count checker.
1123 unsigned i = 0;
1124 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1125 E = MD->param_end(); I != E; ++I, ++i)
1126 if (ParmVarDecl *PD = *I) {
1127 QualType Ty = Ctx.getCanonicalType(PD->getType());
1128 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
1129 ScratchArgs.push_back(std::make_pair(i, StopTracking));
1130 }
1131 }
1132
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001133 // Any special effect for the receiver?
1134 ArgEffect ReceiverEff = DoNothing;
1135
1136 // If one of the arguments in the selector has the keyword 'delegate' we
1137 // should stop tracking the reference count for the receiver. This is
1138 // because the reference count is quite possibly handled by a delegate
1139 // method.
1140 if (S.isKeywordSelector()) {
1141 const std::string &str = S.getAsString();
1142 assert(!str.empty());
1143 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1144 }
1145
Ted Kremenek174a0772009-04-23 23:08:22 +00001146 // Look for methods that return an owned object.
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001147 if (!isTrackedObjectType(ME->getType())) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001148 if (ScratchArgs.empty() && ReceiverEff == DoNothing)
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001149 return 0;
1150
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001151 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1152 MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001153 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001154
1155 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1156 // by instance methods.
1157
1158 RetEffect E =
Ted Kremenekaca0b452009-04-24 18:19:07 +00001159 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek174a0772009-04-23 23:08:22 +00001160 ? (isGCEnabled() ? RetEffect::MakeNotOwned(RetEffect::ObjC)
1161 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1162 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1163
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001164 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001165}
1166
1167RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001168RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1169 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001170
1171 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001172
Ted Kremenek272aa852008-06-25 21:21:56 +00001173 // Look up a summary in our summary cache.
1174 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001175
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001176 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001177 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001178
Ted Kremenek174a0772009-04-23 23:08:22 +00001179 assert(ScratchArgs.empty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001180
1181 // Annotations take precedence over all other ways to derive
1182 // summaries.
1183 RetainSummary *Summ = getMethodSummaryFromAnnotations(ME->getMethodDecl());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001184
Ted Kremenek923fc392009-04-24 23:32:32 +00001185 if (!Summ) {
1186 // "initXXX": pass-through for receiver.
1187 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1188 == InitRule)
1189 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +00001190
Ted Kremenek923fc392009-04-24 23:32:32 +00001191 Summ = getCommonMethodSummary(ME, S);
1192 }
1193
Ted Kremeneke4158502009-04-23 19:11:35 +00001194 ObjCMethodSummaries[ME] = Summ;
1195 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001196}
1197
Ted Kremeneka7722b72008-05-06 21:26:51 +00001198RetainSummary*
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001199RetainSummaryManager::getClassMethodSummary(ObjCMessageExpr *ME) {
1200
Ted Kremenekb17fa952009-04-23 21:25:57 +00001201 Selector S = ME->getSelector();
Ted Kremenek923fc392009-04-24 23:32:32 +00001202 ObjCMethodSummariesTy::iterator I;
Ted Kremenek272aa852008-06-25 21:21:56 +00001203
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001204 if (ObjCInterfaceDecl *ID = ME->getClassInfo().first) {
1205 // Lookup the method using the decl for the class @interface.
1206 I = ObjCClassMethodSummaries.find(ID, S);
1207 }
1208 else {
1209 // Fallback to using the class name.
1210 IdentifierInfo *ClsName = ME->getClassName();
1211
1212 // Look up a summary in our cache of Selectors -> Summaries.
1213 I = ObjCClassMethodSummaries.find(ClsName, S);
1214 }
Ted Kremeneka7722b72008-05-06 21:26:51 +00001215
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001216 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001217 return I->second;
1218
Ted Kremenek923fc392009-04-24 23:32:32 +00001219 // Annotations take precedence over all other ways to derive
1220 // summaries.
1221 RetainSummary *Summ = getMethodSummaryFromAnnotations(ME->getMethodDecl());
1222
1223 if (!Summ)
1224 Summ = getCommonMethodSummary(ME, S);
1225
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001226 ObjCClassMethodSummaries[ObjCSummaryKey(ME->getClassName(), S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001227 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001228}
1229
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001230void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001231
1232 assert (ScratchArgs.empty());
1233
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001234 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001235 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001236
Ted Kremenek0e344d42008-05-06 00:30:21 +00001237 RetainSummary* Summ = getPersistentSummary(E);
1238
Ted Kremenek272aa852008-06-25 21:21:56 +00001239 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1240 // NSObject and its derivatives.
1241 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1242 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1243 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001244
1245 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001246 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001247 GetNullarySelector("currentHandler", Ctx),
1248 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001249
1250 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001251 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1252 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1253 GetUnarySelector("addObject", Ctx),
1254 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001255 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001256
1257 // Create the summaries for [NSObject performSelector...]. We treat
1258 // these as 'stop tracking' for the arguments because they are often
1259 // used for delegates that can release the object. When we have better
1260 // inter-procedural analysis we can potentially do something better. This
1261 // workaround is to remove false positives.
1262 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1263 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1264 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1265 "afterDelay", NULL);
1266 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1267 "afterDelay", "inModes", NULL);
1268 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1269 "withObject", "waitUntilDone", NULL);
1270 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1271 "withObject", "waitUntilDone", "modes", NULL);
1272 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1273 "withObject", "waitUntilDone", NULL);
1274 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1275 "withObject", "waitUntilDone", "modes", NULL);
1276 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1277 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001278}
1279
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001280void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001281
1282 assert (ScratchArgs.empty());
1283
Ted Kremeneka7722b72008-05-06 21:26:51 +00001284 // Create the "init" selector. It just acts as a pass-through for the
1285 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001286 RetainSummary* InitSumm =
1287 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001288 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001289
1290 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001291 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001292 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001293
Ted Kremeneke44927e2008-07-01 17:21:27 +00001294 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001295
1296 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001297 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1298
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001299 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001300 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001301
Ted Kremenek266d8b62008-05-06 02:26:56 +00001302 // Create the "retain" selector.
1303 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001304 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001305 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001306
1307 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001308 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001309 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001310
1311 // Create the "drain" selector.
1312 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001313 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001314
1315 // Create the -dealloc summary.
1316 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1317 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001318
1319 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001320 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001321 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001322
Ted Kremenekaac82832009-02-23 17:45:03 +00001323 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001324 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001325 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001326 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001327
Ted Kremenek45642a42008-08-12 18:48:50 +00001328 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001329 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1330 // self-own themselves. However, they only do this once they are displayed.
1331 // Thus, we need to track an NSWindow's display status.
1332 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001333 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001334 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1335
1336 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1337
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001338
1339#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001340 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001341 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001342
1343 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1344 "styleMask", "backing", "defer", NULL);
1345
1346 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1347 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001348#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001349
1350 // For NSPanel (which subclasses NSWindow), allocated objects are not
1351 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001352 // FIXME: For now we don't track NSPanels. object for the same reason
1353 // as for NSWindow objects.
1354 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1355
Ted Kremenek45642a42008-08-12 18:48:50 +00001356 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1357 "styleMask", "backing", "defer", NULL);
1358
1359 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1360 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001361
Ted Kremenekf2717b02008-07-18 17:24:20 +00001362 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001363 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1364 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001365
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001366 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1367 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001368}
1369
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001370//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001371// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001372//===----------------------------------------------------------------------===//
1373
Ted Kremeneka7338b42008-03-11 06:39:11 +00001374namespace {
1375
Ted Kremenek7d421f32008-04-09 23:49:11 +00001376class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001377public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001378 enum Kind {
1379 Owned = 0, // Owning reference.
1380 NotOwned, // Reference is not owned by still valid (not freed).
1381 Released, // Object has been released.
1382 ReturnedOwned, // Returned object passes ownership to caller.
1383 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001384 ERROR_START,
1385 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1386 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001387 ErrorUseAfterRelease, // Object used after released.
1388 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001389 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001390 ErrorLeak, // A memory leak due to excessive reference counts.
1391 ErrorLeakReturned // A memory leak due to the returning method not having
1392 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001393 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001394
1395private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001396 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001397 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001398 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001399 QualType T;
1400
Ted Kremenek68621b92009-01-28 05:56:51 +00001401 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1402 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001403
Ted Kremenek68621b92009-01-28 05:56:51 +00001404 RefVal(Kind k, unsigned cnt = 0)
1405 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1406
1407public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001408 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001409
1410 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001411
Ted Kremenek6537a642009-03-17 19:42:23 +00001412 unsigned getCount() const { return Cnt; }
1413 void clearCounts() { Cnt = 0; }
1414
Ted Kremenek272aa852008-06-25 21:21:56 +00001415 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001416
1417 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001418
Ted Kremenek6537a642009-03-17 19:42:23 +00001419 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001420
Ted Kremenek6537a642009-03-17 19:42:23 +00001421 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001422
Ted Kremenekffefc352008-04-11 22:25:11 +00001423 bool isOwned() const {
1424 return getKind() == Owned;
1425 }
1426
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001427 bool isNotOwned() const {
1428 return getKind() == NotOwned;
1429 }
1430
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001431 bool isReturnedOwned() const {
1432 return getKind() == ReturnedOwned;
1433 }
1434
1435 bool isReturnedNotOwned() const {
1436 return getKind() == ReturnedNotOwned;
1437 }
1438
1439 bool isNonLeakError() const {
1440 Kind k = getKind();
1441 return isError(k) && !isLeak(k);
1442 }
1443
Ted Kremenek68621b92009-01-28 05:56:51 +00001444 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1445 unsigned Count = 1) {
1446 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001447 }
1448
Ted Kremenek68621b92009-01-28 05:56:51 +00001449 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1450 unsigned Count = 0) {
1451 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001452 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001453
1454 static RefVal makeReturnedOwned(unsigned Count) {
1455 return RefVal(ReturnedOwned, Count);
1456 }
1457
1458 static RefVal makeReturnedNotOwned() {
1459 return RefVal(ReturnedNotOwned);
1460 }
1461
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001462 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001463
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001464 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001465 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001466 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001467
Ted Kremenek272aa852008-06-25 21:21:56 +00001468 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001469 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001470 }
1471
1472 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001473 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001474 }
1475
1476 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001477 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001478 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001479
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001480 void Profile(llvm::FoldingSetNodeID& ID) const {
1481 ID.AddInteger((unsigned) kind);
1482 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001483 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001484 }
1485
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001486 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001487};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001488
1489void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001490 if (!T.isNull())
1491 Out << "Tracked Type:" << T.getAsString() << '\n';
1492
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001493 switch (getKind()) {
1494 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001495 case Owned: {
1496 Out << "Owned";
1497 unsigned cnt = getCount();
1498 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001499 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001500 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001501
Ted Kremenekc4f81022008-04-10 23:09:18 +00001502 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001503 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001504 unsigned cnt = getCount();
1505 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001506 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001507 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001508
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001509 case ReturnedOwned: {
1510 Out << "ReturnedOwned";
1511 unsigned cnt = getCount();
1512 if (cnt) Out << " (+ " << cnt << ")";
1513 break;
1514 }
1515
1516 case ReturnedNotOwned: {
1517 Out << "ReturnedNotOwned";
1518 unsigned cnt = getCount();
1519 if (cnt) Out << " (+ " << cnt << ")";
1520 break;
1521 }
1522
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001523 case Released:
1524 Out << "Released";
1525 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001526
1527 case ErrorDeallocGC:
1528 Out << "-dealloc (GC)";
1529 break;
1530
1531 case ErrorDeallocNotOwned:
1532 Out << "-dealloc (not-owned)";
1533 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001534
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001535 case ErrorLeak:
1536 Out << "Leaked";
1537 break;
1538
Ted Kremenek311f3d42008-10-22 23:56:21 +00001539 case ErrorLeakReturned:
1540 Out << "Leaked (Bad naming)";
1541 break;
1542
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001543 case ErrorUseAfterRelease:
1544 Out << "Use-After-Release [ERROR]";
1545 break;
1546
1547 case ErrorReleaseNotOwned:
1548 Out << "Release of Not-Owned [ERROR]";
1549 break;
1550 }
1551}
Ted Kremenek0d721572008-03-11 17:48:22 +00001552
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001553} // end anonymous namespace
1554
1555//===----------------------------------------------------------------------===//
1556// RefBindings - State used to track object reference counts.
1557//===----------------------------------------------------------------------===//
1558
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001559typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001560static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001561static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001562
1563namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001564 template<>
1565 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1566 static inline void* GDMIndex() { return &RefBIndex; }
1567 };
1568}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001569
1570//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001571// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001572//===----------------------------------------------------------------------===//
1573
Ted Kremenekb6578942009-02-24 19:15:11 +00001574typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1575typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1576typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001577
Ted Kremenekb6578942009-02-24 19:15:11 +00001578static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001579static int AutoRBIndex = 0;
1580
Ted Kremenekb6578942009-02-24 19:15:11 +00001581namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001582namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001583
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001584namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001585template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001586 : public GRStatePartialTrait<ARStack> {
1587 static inline void* GDMIndex() { return &AutoRBIndex; }
1588};
1589
1590template<> struct GRStateTrait<AutoreleasePoolContents>
1591 : public GRStatePartialTrait<ARPoolContents> {
1592 static inline void* GDMIndex() { return &AutoRCIndex; }
1593};
1594} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001595
Ted Kremenek681fb352009-03-20 17:34:15 +00001596static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1597 ARStack stack = state->get<AutoreleaseStack>();
1598 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1599}
1600
1601static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1602 SymbolRef sym) {
1603
1604 SymbolRef pool = GetCurrentAutoreleasePool(state);
1605 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1606 ARCounts newCnts(0);
1607
1608 if (cnts) {
1609 const unsigned *cnt = (*cnts).lookup(sym);
1610 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1611 }
1612 else
1613 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1614
1615 return state.set<AutoreleasePoolContents>(pool, newCnts);
1616}
1617
Ted Kremenek7aef4842008-04-16 20:40:59 +00001618//===----------------------------------------------------------------------===//
1619// Transfer functions.
1620//===----------------------------------------------------------------------===//
1621
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001622namespace {
1623
Ted Kremenek7d421f32008-04-09 23:49:11 +00001624class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001625public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001626 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001627 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001628 virtual void Print(std::ostream& Out, const GRState* state,
1629 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001630 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001631
1632private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001633 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1634 SummaryLogTy;
1635
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001636 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001637 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001638 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001639 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001640
Ted Kremenek708af042009-02-05 06:50:21 +00001641 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001642 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001643 BugType *leakWithinFunction, *leakAtReturn;
1644 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001645
Ted Kremenekb6578942009-02-24 19:15:11 +00001646 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1647 RefVal::Kind& hasErr);
1648
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001649 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1650 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001651 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001652 ExplodedNode<GRState>* Pred,
1653 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001654 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001655
Ted Kremenek0106e202008-10-24 20:32:50 +00001656 std::pair<GRStateRef, bool>
1657 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001658 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001659
Ted Kremenekb6578942009-02-24 19:15:11 +00001660public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001661 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001662 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001663 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1664 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001665 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001666
Ted Kremenek708af042009-02-05 06:50:21 +00001667 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001668
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001669 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001670
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001671 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1672 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001673 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001674
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001675 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001676 const LangOptions& getLangOptions() const { return LOpts; }
1677
Ted Kremenekc26c4692009-02-18 03:48:14 +00001678 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1679 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1680 return I == SummaryLog.end() ? 0 : I->second;
1681 }
1682
Ted Kremeneka7338b42008-03-11 06:39:11 +00001683 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001684
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001685 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001686 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001687 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001688 Expr* Ex,
1689 Expr* Receiver,
1690 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001691 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001692 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001693
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001694 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001695 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001696 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001697 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001698 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001699
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001700
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001701 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001702 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001703 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001704 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001705 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001706
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001707 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001708 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001709 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001710 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001711 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001712
Ted Kremeneka42be302009-02-14 01:43:44 +00001713 // Stores.
1714 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1715
Ted Kremenekffefc352008-04-11 22:25:11 +00001716 // End-of-path.
1717
1718 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001719 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001720
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001721 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001722 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001723 GRStmtNodeBuilder<GRState>& Builder,
1724 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001725 Stmt* S, const GRState* state,
1726 SymbolReaper& SymReaper);
1727
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001728 // Return statements.
1729
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001730 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001731 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001732 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001733 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001734 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001735
1736 // Assumptions.
1737
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001738 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001739 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001740 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001741};
1742
1743} // end anonymous namespace
1744
Ted Kremenek681fb352009-03-20 17:34:15 +00001745static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1746 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001747 if (Sym)
1748 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001749 else
1750 Out << "<pool>";
1751 Out << ":{";
1752
1753 // Get the contents of the pool.
1754 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1755 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1756 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1757
1758 Out << '}';
1759}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001760
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001761void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1762 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001763
1764
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001765
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001766 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001767
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001768 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001769 Out << sep << nl;
1770
1771 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1772 Out << (*I).first << " : ";
1773 (*I).second.print(Out);
1774 Out << nl;
1775 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001776
1777 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001778 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001779 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001780
Ted Kremenek681fb352009-03-20 17:34:15 +00001781 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1782 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1783 PrintPool(Out, *I, state);
1784
1785 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001786}
1787
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001788static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001789 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001790}
1791
Ted Kremenek266d8b62008-05-06 02:26:56 +00001792static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1793 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001794}
1795
Ted Kremenek227c5372008-05-06 02:41:27 +00001796static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1797 return Summ ? Summ->getReceiverEffect() : DoNothing;
1798}
1799
Ted Kremenekf2717b02008-07-18 17:24:20 +00001800static inline bool IsEndPath(RetainSummary* Summ) {
1801 return Summ ? Summ->isEndPath() : false;
1802}
1803
Ted Kremenek1feab292008-04-16 04:28:53 +00001804
Ted Kremenek272aa852008-06-25 21:21:56 +00001805/// GetReturnType - Used to get the return type of a message expression or
1806/// function call with the intention of affixing that type to a tracked symbol.
1807/// While the the return type can be queried directly from RetEx, when
1808/// invoking class methods we augment to the return type to be that of
1809/// a pointer to the class (as opposed it just being id).
1810static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1811
1812 QualType RetTy = RetE->getType();
1813
1814 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001815 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001816 if (!PT)
1817 return RetTy;
1818
1819 // If RetEx is not a message expression just return its type.
1820 // If RetEx is a message expression, return its types if it is something
1821 /// more specific than id.
1822
1823 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1824
Steve Naroff17c03822009-02-12 17:52:19 +00001825 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001826 return RetTy;
1827
1828 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1829
1830 // At this point we know the return type of the message expression is id.
1831 // If we have an ObjCInterceDecl, we know this is a call to a class method
1832 // whose type we can resolve. In such cases, promote the return type to
1833 // Class*.
1834 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1835}
1836
1837
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001838void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001839 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001840 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001841 Expr* Ex,
1842 Expr* Receiver,
1843 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00001844 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001845 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001846
Ted Kremeneka7338b42008-03-11 06:39:11 +00001847 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001848 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001849 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001850
1851 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001852 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001853 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001854 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001855 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001856
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001857 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001858 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001859 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001860
Ted Kremenek74556a12009-03-26 03:35:11 +00001861 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00001862 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1863 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1864 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001865 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001866 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001867 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001868 }
1869 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00001870 }
Ted Kremenekede40b72008-07-09 18:11:16 +00001871
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001872 if (isa<Loc>(V)) {
1873 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001874 if (GetArgE(Summ, idx) == DoNothingByRef)
1875 continue;
1876
1877 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001878
1879 // FIXME: Either this logic should also be replicated in GRSimpleVals
1880 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001881
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001882 // FIXME: We can have collisions on the conjured symbol if the
1883 // expression *I also creates conjured symbols. We probably want
1884 // to identify conjured symbols by an expression pair: the enclosing
1885 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001886 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001887
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001888 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001889
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001890 // Blast through TypedViewRegions to get the original region type.
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001891 while (R) {
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001892 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001893 if (!ATR) break;
1894 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1895 }
1896
Ted Kremenek53b24182009-03-04 22:56:43 +00001897 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001898 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001899 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001900
Ted Kremenek53b24182009-03-04 22:56:43 +00001901 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00001902 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001903
Ted Kremenek53b24182009-03-04 22:56:43 +00001904 if (R->isBoundable(Ctx)) {
1905 // Set the value of the variable to be a conjured symbol.
1906 unsigned Count = Builder.getCurrentBlockCount();
1907 QualType T = R->getRValueType(Ctx);
1908
Zhongxing Xu079dc352009-04-09 06:03:54 +00001909 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001910 ValueManager &ValMgr = Eng.getValueManager();
1911 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00001912 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00001913 }
1914 else if (const RecordType *RT = T->getAsStructureType()) {
1915 // Handle structs in a not so awesome way. Here we just
1916 // eagerly bind new symbols to the fields. In reality we
1917 // should have the store manager handle this. The idea is just
1918 // to prototype some basic functionality here. All of this logic
1919 // should one day soon just go away.
1920 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1921
1922 // No record definition. There is nothing we can do.
1923 if (!RD)
1924 continue;
1925
1926 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1927
1928 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001929 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
1930 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00001931
1932 // For now just handle scalar fields.
1933 FieldDecl *FD = *FI;
1934 QualType FT = FD->getType();
1935
1936 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001937 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00001938 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001939 ValueManager &ValMgr = Eng.getValueManager();
1940 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00001941 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00001942 }
1943 }
1944 }
1945 else {
1946 // Just blast away other values.
1947 state = state.BindLoc(*MR, UnknownVal());
1948 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00001949 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001950 }
1951 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001952 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001953 }
1954 else {
1955 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001956 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001957 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001958 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001959 else if (isa<nonloc::LocAsInteger>(V))
1960 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001961 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001962
Ted Kremenek272aa852008-06-25 21:21:56 +00001963 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001964 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001965 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00001966 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00001967 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1968 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1969 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00001970 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001971 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001972 }
Ted Kremenekb6578942009-02-24 19:15:11 +00001973 }
Ted Kremenek227c5372008-05-06 02:41:27 +00001974 }
1975 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001976
Ted Kremenek272aa852008-06-25 21:21:56 +00001977 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001978 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001979 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001980 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001981 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001982 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001983
Ted Kremenekf2717b02008-07-18 17:24:20 +00001984 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001985 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001986
1987 switch (RE.getKind()) {
1988 default:
1989 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001990
Ted Kremenek8f90e712008-10-17 22:23:12 +00001991 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001992
Ted Kremenek455dd862008-04-11 20:23:24 +00001993 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001994 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1995 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001996
Ted Kremenek8f90e712008-10-17 22:23:12 +00001997 // FIXME: We eventually should handle structs and other compound types
1998 // that are returned by value.
1999
2000 QualType T = Ex->getType();
2001
Ted Kremenek79413a52008-11-13 06:10:40 +00002002 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002003 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002004 ValueManager &ValMgr = Eng.getValueManager();
2005 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002006 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002007 }
2008
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002009 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002010 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002011
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002012 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002013 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002014 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002015 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002016 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002017 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002018 break;
2019 }
2020
Ted Kremenek227c5372008-05-06 02:41:27 +00002021 case RetEffect::ReceiverAlias: {
2022 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002023 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002024 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002025 break;
2026 }
2027
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002028 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002029 case RetEffect::OwnedSymbol: {
2030 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002031 ValueManager &ValMgr = Eng.getValueManager();
2032 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2033 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2034 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2035 RetT));
2036 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002037
2038 // FIXME: Add a flag to the checker where allocations are assumed to
2039 // *not fail.
2040#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002041 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2042 bool isFeasible;
2043 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2044 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2045 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002046#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002047
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002048 break;
2049 }
2050
2051 case RetEffect::NotOwnedSymbol: {
2052 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002053 ValueManager &ValMgr = Eng.getValueManager();
2054 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2055 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2056 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2057 RetT));
2058 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002059 break;
2060 }
2061 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002062
Ted Kremenek0dd65012009-02-18 02:00:25 +00002063 // Generate a sink node if we are at the end of a path.
2064 GRExprEngine::NodeTy *NewNode =
2065 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2066 : Builder.MakeNode(Dst, Ex, Pred, state);
2067
2068 // Annotate the edge with summary we used.
2069 // FIXME: This assumes that we always use the same summary when generating
2070 // this node.
2071 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002072}
2073
2074
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002075void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002076 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002077 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002078 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002079 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002080 const FunctionDecl* FD = L.getAsFunctionDecl();
2081 RetainSummary* Summ = !FD ? 0
2082 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002083
2084 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2085 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002086}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002087
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002088void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002089 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002090 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002091 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002092 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002093 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002094
Ted Kremenek272aa852008-06-25 21:21:56 +00002095 if (Expr* Receiver = ME->getReceiver()) {
2096 // We need the type-information of the tracked receiver object
2097 // Retrieve it from the state.
2098 ObjCInterfaceDecl* ID = 0;
2099
2100 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2101 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002102 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002103 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002104
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002105 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002106 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002107 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002108 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002109
2110 if (const PointerType* PT = Ty->getAsPointerType()) {
2111 QualType PointeeTy = PT->getPointeeType();
2112
2113 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2114 ID = IT->getDecl();
2115 }
2116 }
2117 }
2118
2119 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002120
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002121 // Special-case: are we sending a mesage to "self"?
2122 // This is a hack. When we have full-IP this should be removed.
2123 if (!Summ) {
2124 ObjCMethodDecl* MD =
2125 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2126
2127 if (MD) {
2128 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002129 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002130 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002131 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2132 // Create a summmary where all of the arguments "StopTracking".
2133 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2134 DoNothing,
2135 StopTracking);
2136 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002137 }
2138 }
2139 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002140 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002141 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002142 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002143
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002144
Ted Kremenek926abf22008-05-06 04:20:12 +00002145 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2146 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002147}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002148
2149namespace {
2150class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2151 GRStateRef state;
2152public:
2153 StopTrackingCallback(GRStateRef st) : state(st) {}
2154 GRStateRef getState() { return state; }
2155
2156 bool VisitSymbol(SymbolRef sym) {
2157 state = state.remove<RefBindings>(sym);
2158 return true;
2159 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002160
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002161 const GRState* getState() const { return state.getState(); }
2162};
2163} // end anonymous namespace
2164
2165
Ted Kremeneka42be302009-02-14 01:43:44 +00002166void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002167 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002168 bool escapes = false;
2169
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002170 // A value escapes in three possible cases (this may change):
2171 //
2172 // (1) we are binding to something that is not a memory region.
2173 // (2) we are binding to a memregion that does not have stack storage
2174 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002175 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002176 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002177
Ted Kremeneka42be302009-02-14 01:43:44 +00002178 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002179 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002180 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002181 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2182 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002183
2184 if (!escapes) {
2185 // To test (3), generate a new state with the binding removed. If it is
2186 // the same state, then it escapes (since the store cannot represent
2187 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002188 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002189 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002190 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002191
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002192 // If our store can represent the binding and we aren't storing to something
2193 // that doesn't have local storage then just return and have the simulation
2194 // state continue as is.
2195 if (!escapes)
2196 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002197
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002198 // Otherwise, find all symbols referenced by 'val' that we are tracking
2199 // and stop tracking them.
2200 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002201}
2202
Ted Kremenek0106e202008-10-24 20:32:50 +00002203std::pair<GRStateRef,bool>
2204CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2205 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002206 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002207 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002208
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002209 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00002210 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00002211 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002212
Ted Kremenek311f3d42008-10-22 23:56:21 +00002213 if (V.isReturnedOwned() && V.getCount() == 0)
2214 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00002215 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00002216 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00002217 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00002218 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2219 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00002220 }
2221 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002222
Ted Kremenek311f3d42008-10-22 23:56:21 +00002223 // All other cases.
2224
2225 hasLeak = V.isOwned() ||
2226 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002227
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002228 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002229 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002230
Ted Kremenek0106e202008-10-24 20:32:50 +00002231 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2232 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002233}
2234
Ted Kremenek541db372008-04-24 23:57:27 +00002235
Ted Kremenekffefc352008-04-11 22:25:11 +00002236
Ted Kremenek541db372008-04-24 23:57:27 +00002237// Dead symbols.
2238
Ted Kremenek708af042009-02-05 06:50:21 +00002239
Ted Kremenek541db372008-04-24 23:57:27 +00002240
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002241 // Return statements.
2242
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002243void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002244 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002245 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002246 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002247 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002248
2249 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002250 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002251 return;
2252
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002253 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002254 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002255
Ted Kremenek74556a12009-03-26 03:35:11 +00002256 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002257 return;
2258
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002259 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002260 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002261
2262 if (!T)
2263 return;
2264
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002265 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002266 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002267
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002268 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002269 case RefVal::Owned: {
2270 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002271 assert (cnt > 0);
2272 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002273 break;
2274 }
2275
2276 case RefVal::NotOwned: {
2277 unsigned cnt = X.getCount();
2278 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2279 : RefVal::makeReturnedNotOwned();
2280 break;
2281 }
2282
2283 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002284 return;
2285 }
2286
2287 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002288 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002289 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002290}
2291
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002292// Assumptions.
2293
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002294const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2295 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002296 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002297 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002298
2299 // FIXME: We may add to the interface of EvalAssume the list of symbols
2300 // whose assumptions have changed. For now we just iterate through the
2301 // bindings and check if any of the tracked symbols are NULL. This isn't
2302 // too bad since the number of symbols we will track in practice are
2303 // probably small and EvalAssume is only called at branches and a few
2304 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002305 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002306
2307 if (B.isEmpty())
2308 return St;
2309
2310 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002311
2312 GRStateRef state(St, VMgr);
2313 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002314
2315 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002316 // Check if the symbol is null (or equal to any constant).
2317 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002318 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002319 changed = true;
2320 B = RefBFactory.Remove(B, I.getKey());
2321 }
2322 }
2323
Ted Kremenek91781202008-08-17 03:20:02 +00002324 if (changed)
2325 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002326
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002327 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002328}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002329
Ted Kremenekb6578942009-02-24 19:15:11 +00002330GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2331 RefVal V, ArgEffect E,
2332 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002333
2334 // In GC mode [... release] and [... retain] do nothing.
2335 switch (E) {
2336 default: break;
2337 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2338 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002339 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00002340 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2341 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002342 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002343
Ted Kremenek6537a642009-03-17 19:42:23 +00002344 // Handle all use-after-releases.
2345 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
2346 V = V ^ RefVal::ErrorUseAfterRelease;
2347 hasErr = V.getKind();
2348 return state.set<RefBindings>(sym, V);
2349 }
2350
Ted Kremenek0d721572008-03-11 17:48:22 +00002351 switch (E) {
2352 default:
2353 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00002354
2355 case Dealloc:
2356 // Any use of -dealloc in GC is *bad*.
2357 if (isGCEnabled()) {
2358 V = V ^ RefVal::ErrorDeallocGC;
2359 hasErr = V.getKind();
2360 break;
2361 }
2362
2363 switch (V.getKind()) {
2364 default:
2365 assert(false && "Invalid case.");
2366 case RefVal::Owned:
2367 // The object immediately transitions to the released state.
2368 V = V ^ RefVal::Released;
2369 V.clearCounts();
2370 return state.set<RefBindings>(sym, V);
2371 case RefVal::NotOwned:
2372 V = V ^ RefVal::ErrorDeallocNotOwned;
2373 hasErr = V.getKind();
2374 break;
2375 }
2376 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002377
Ted Kremenekb7826ab2009-02-25 23:11:49 +00002378 case NewAutoreleasePool:
2379 assert(!isGCEnabled());
2380 return state.add<AutoreleaseStack>(sym);
2381
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002382 case MayEscape:
2383 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002384 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002385 break;
2386 }
Ted Kremenek6537a642009-03-17 19:42:23 +00002387
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002388 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00002389
Ted Kremenekede40b72008-07-09 18:11:16 +00002390 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002391 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00002392 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002393
Ted Kremenek9b112d22009-01-28 21:44:40 +00002394 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00002395 if (isGCEnabled())
2396 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00002397
2398 // Update the autorelease counts.
2399 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00002400
2401 // Fall-through.
2402
Ted Kremenek227c5372008-05-06 02:41:27 +00002403 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00002404 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002405
Ted Kremenek0d721572008-03-11 17:48:22 +00002406 case IncRef:
2407 switch (V.getKind()) {
2408 default:
2409 assert(false);
2410
2411 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002412 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002413 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002414 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002415 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002416 // Non-GC cases are handled above.
2417 assert(isGCEnabled());
2418 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002419 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002420 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002421 break;
2422
Ted Kremenek272aa852008-06-25 21:21:56 +00002423 case SelfOwn:
2424 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002425 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002426 case DecRef:
2427 switch (V.getKind()) {
2428 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00002429 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00002430 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002431
Ted Kremenek272aa852008-06-25 21:21:56 +00002432 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002433 assert(V.getCount() > 0);
2434 if (V.getCount() == 1) V = V ^ RefVal::Released;
2435 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002436 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002437
Ted Kremenek272aa852008-06-25 21:21:56 +00002438 case RefVal::NotOwned:
2439 if (V.getCount() > 0)
2440 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002441 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002442 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002443 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002444 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002445 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00002446
Ted Kremenek0d721572008-03-11 17:48:22 +00002447 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002448 // Non-GC cases are handled above.
2449 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00002450 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002451 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00002452 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002453 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002454 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002455 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002456 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002457}
2458
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002459//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002460// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002461//===----------------------------------------------------------------------===//
2462
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002463namespace {
2464
2465 //===-------------===//
2466 // Bug Descriptions. //
2467 //===-------------===//
2468
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002469 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002470 protected:
2471 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002472
2473 CFRefBug(CFRefCount* tf, const char* name)
2474 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002475 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002476
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002477 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002478 const CFRefCount& getTF() const { return TF; }
2479
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002480 // FIXME: Eventually remove.
2481 virtual const char* getDescription() const = 0;
2482
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002483 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002484 };
2485
2486 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2487 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002488 UseAfterRelease(CFRefCount* tf)
Ted Kremenek5b1ab102009-04-03 21:10:31 +00002489 : CFRefBug(tf, "Use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002490
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002491 const char* getDescription() const {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002492 return "Reference-counted object is used after it is released";
Ted Kremenek708af042009-02-05 06:50:21 +00002493 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002494 };
2495
2496 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2497 public:
Ted Kremenekcce60492009-04-24 17:51:19 +00002498 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002499
2500 const char* getDescription() const {
Ted Kremeneke4158502009-04-23 19:11:35 +00002501 return "Incorrect decrement of the reference count of an "
2502 "object is not owned at this point by the caller";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002503 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002504 };
2505
Ted Kremenek6537a642009-03-17 19:42:23 +00002506 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2507 public:
2508 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
2509 "-dealloc called while using GC") {}
2510
2511 const char *getDescription() const {
2512 return "-dealloc called while using GC";
2513 }
2514 };
2515
2516 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2517 public:
2518 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
2519 "-dealloc sent to non-exclusively owned object") {}
2520
2521 const char *getDescription() const {
2522 return "-dealloc sent to object that may be referenced elsewhere";
2523 }
2524 };
2525
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002526 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002527 const bool isReturn;
2528 protected:
2529 Leak(CFRefCount* tf, const char* name, bool isRet)
2530 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002531 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002532
Ted Kremenek44274e62009-02-07 22:38:00 +00002533 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002534
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002535 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002536 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002537
2538 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2539 public:
2540 LeakAtReturn(CFRefCount* tf, const char* name)
2541 : Leak(tf, name, true) {}
2542 };
2543
2544 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2545 public:
2546 LeakWithinFunction(CFRefCount* tf, const char* name)
2547 : Leak(tf, name, false) {}
2548 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002549
2550 //===---------===//
2551 // Bug Reports. //
2552 //===---------===//
2553
2554 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002555 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002556 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002557 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002558 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002559 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2560 ExplodedNode<GRState> *n, SymbolRef sym)
2561 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002562
2563 virtual ~CFRefReport() {}
2564
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002565 CFRefBug& getBugType() {
2566 return (CFRefBug&) RangedBugReport::getBugType();
2567 }
2568 const CFRefBug& getBugType() const {
2569 return (const CFRefBug&) RangedBugReport::getBugType();
2570 }
2571
2572 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2573 const SourceRange*& end) {
2574
Ted Kremenek198cae02008-05-02 20:53:50 +00002575 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002576 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002577 else
2578 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002579 }
2580
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002581 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002582
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002583 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2584 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002585
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002586 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002587
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002588 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2589 const ExplodedNode<GRState>* PrevN,
2590 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002591 BugReporter& BR,
2592 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002593 };
2594
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002595 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002596 SourceLocation AllocSite;
2597 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002598 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002599 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2600 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002601 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002602
2603 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2604 const ExplodedNode<GRState>* N);
2605
Ted Kremenek86617f42009-02-07 22:19:59 +00002606 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002607 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002608} // end anonymous namespace
2609
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002610void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002611 useAfterRelease = new UseAfterRelease(this);
2612 BR.Register(useAfterRelease);
2613
2614 releaseNotOwned = new BadRelease(this);
2615 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002616
Ted Kremenek6537a642009-03-17 19:42:23 +00002617 deallocGC = new DeallocGC(this);
2618 BR.Register(deallocGC);
2619
2620 deallocNotOwned = new DeallocNotOwned(this);
2621 BR.Register(deallocNotOwned);
2622
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002623 // First register "return" leaks.
2624 const char* name = 0;
2625
2626 if (isGCEnabled())
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002627 name = "Leak of returned object when using garbage collection";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002628 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002629 name = "Leak of returned object when not using garbage collection (GC) in "
2630 "dual GC/non-GC code";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002631 else {
2632 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002633 name = "Leak of returned object";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002634 }
2635
Ted Kremenek708af042009-02-05 06:50:21 +00002636 leakAtReturn = new LeakAtReturn(this, name);
2637 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002638
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002639 // Second, register leaks within a function/method.
2640 if (isGCEnabled())
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002641 name = "Leak of object when using garbage collection";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002642 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002643 name = "Leak of object when not using garbage collection (GC) in "
2644 "dual GC/non-GC code";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002645 else {
2646 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002647 name = "Leak";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002648 }
2649
Ted Kremenek708af042009-02-05 06:50:21 +00002650 leakWithinFunction = new LeakWithinFunction(this, name);
2651 BR.Register(leakWithinFunction);
2652
2653 // Save the reference to the BugReporter.
2654 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002655}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002656
2657static const char* Msgs[] = {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002658 // GC only
2659 "Code is compiled to only use garbage collection",
2660 // No GC.
Ted Kremeneka9203882009-03-05 00:12:45 +00002661 "Code is compiled to use reference counts",
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002662 // Hybrid, with GC.
2663 "Code is compiled to use either garbage collection (GC) or reference counts"
2664 " (non-GC). The bug occurs with GC enabled",
2665 // Hybrid, without GC
2666 "Code is compiled to use either garbage collection (GC) or reference counts"
2667 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002668};
2669
2670std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2671 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2672
2673 switch (TF.getLangOptions().getGCMode()) {
2674 default:
2675 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002676
2677 case LangOptions::GCOnly:
2678 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002679 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2680
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002681 case LangOptions::NonGC:
2682 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002683 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2684
2685 case LangOptions::HybridGC:
2686 if (TF.isGCEnabled())
2687 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2688 else
2689 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2690 }
2691}
2692
Ted Kremenek2126bef2009-02-18 21:57:45 +00002693static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2694 ArgEffect X) {
2695 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2696 I!=E; ++I)
2697 if (*I == X) return true;
2698
2699 return false;
2700}
2701
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002702PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2703 const ExplodedNode<GRState>* PrevN,
2704 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002705 BugReporter& BR,
2706 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002707
Ted Kremenek71745d92009-01-28 05:29:13 +00002708 // Check if the type state has changed.
2709 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2710 GRStateRef PrevSt(PrevN->getState(), StMgr);
2711 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002712
Ted Kremenek71745d92009-01-28 05:29:13 +00002713 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2714 if (!CurrT) return NULL;
2715
2716 const RefVal& CurrV = *CurrT;
2717 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002718
Ted Kremenek2126bef2009-02-18 21:57:45 +00002719 // Create a string buffer to constain all the useful things we want
2720 // to tell the user.
2721 std::string sbuf;
2722 llvm::raw_string_ostream os(sbuf);
2723
Ted Kremenekc26c4692009-02-18 03:48:14 +00002724 // This is the allocation site since the previous node had no bindings
2725 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002726 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002727 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2728
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002729 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2730 // Get the name of the callee (if it is available).
Zhongxing Xucac107a2009-04-20 05:24:46 +00002731 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2732 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2733 os << "Call to function '" << FD->getNameAsString() <<'\'';
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002734 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002735 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002736 }
2737 else {
2738 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002739 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002740 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002741
Ted Kremenek18878b12009-01-28 06:06:36 +00002742 if (CurrV.getObjKind() == RetEffect::CF) {
2743 os << " returns a Core Foundation object with a ";
2744 }
2745 else {
2746 assert (CurrV.getObjKind() == RetEffect::ObjC);
2747 os << " returns an Objective-C object with a ";
2748 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002749
Ted Kremenekabe30922009-01-28 06:25:48 +00002750 if (CurrV.isOwned()) {
2751 os << "+1 retain count (owning reference).";
2752
2753 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2754 assert(CurrV.getObjKind() == RetEffect::CF);
2755 os << " "
2756 "Core Foundation objects are not automatically garbage collected.";
2757 }
2758 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002759 else {
2760 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002761 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002762 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002763
Ted Kremenek2fba6152009-04-01 06:13:56 +00002764 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2765 return new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002766 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002767
Ted Kremenek2126bef2009-02-18 21:57:45 +00002768 // Gather up the effects that were performed on the object at this
2769 // program point
2770 llvm::SmallVector<ArgEffect, 2> AEffects;
2771
Ted Kremenekc26c4692009-02-18 03:48:14 +00002772 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2773 // We only have summaries attached to nodes after evaluating CallExpr and
2774 // ObjCMessageExprs.
2775 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2776
Ted Kremenekc26c4692009-02-18 03:48:14 +00002777 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2778 // Iterate through the parameter expressions and see if the symbol
2779 // was ever passed as an argument.
2780 unsigned i = 0;
2781
2782 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2783 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002784
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002785 // Retrieve the value of the argument. Is it the symbol
2786 // we are interested in?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002787 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002788 continue;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002789
Ted Kremenekc26c4692009-02-18 03:48:14 +00002790 // We have an argument. Get the effect!
2791 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002792 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002793 }
2794 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002795 if (Expr *receiver = ME->getReceiver())
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002796 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002797 // The symbol we are tracking is the receiver.
2798 AEffects.push_back(Summ->getReceiverEffect());
2799 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002800 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002801 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002802
Ted Kremenek2126bef2009-02-18 21:57:45 +00002803 do {
2804 // Get the previous type state.
2805 RefVal PrevV = *PrevT;
Ted Kremenek6537a642009-03-17 19:42:23 +00002806
2807 // Specially handle -dealloc.
2808 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2809 // Determine if the object's reference count was pushed to zero.
2810 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2811 // We may not have transitioned to 'release' if we hit an error.
2812 // This case is handled elsewhere.
2813 if (CurrV.getKind() == RefVal::Released) {
2814 assert(CurrV.getCount() == 0);
2815 os << "Object released by directly sending the '-dealloc' message";
2816 break;
2817 }
2818 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002819
2820 // Specially handle CFMakeCollectable and friends.
2821 if (contains(AEffects, MakeCollectable)) {
2822 // Get the name of the function.
2823 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Zhongxing Xucac107a2009-04-20 05:24:46 +00002824 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2825 const FunctionDecl* FD = X.getAsFunctionDecl();
2826 const std::string& FName = FD->getNameAsString();
Ted Kremenek2126bef2009-02-18 21:57:45 +00002827
2828 if (TF.isGCEnabled()) {
2829 // Determine if the object's reference count was pushed to zero.
2830 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2831
2832 os << "In GC mode a call to '" << FName
2833 << "' decrements an object's retain count and registers the "
2834 "object with the garbage collector. ";
2835
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002836 if (CurrV.getKind() == RefVal::Released) {
2837 assert(CurrV.getCount() == 0);
2838 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002839 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002840 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002841 else
2842 os << "An object must have a 0 retain count to be garbage collected. "
2843 "After this call its retain count is +" << CurrV.getCount()
2844 << '.';
2845 }
2846 else
2847 os << "When GC is not enabled a call to '" << FName
2848 << "' has no effect on its argument.";
2849
2850 // Nothing more to say.
2851 break;
2852 }
2853
2854 // Determine if the typestate has changed.
2855 if (!(PrevV == CurrV))
2856 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002857 case RefVal::Owned:
2858 case RefVal::NotOwned:
2859
2860 if (PrevV.getCount() == CurrV.getCount())
2861 return 0;
2862
2863 if (PrevV.getCount() > CurrV.getCount())
2864 os << "Reference count decremented.";
2865 else
2866 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002867
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002868 if (unsigned Count = CurrV.getCount())
2869 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002870
2871 if (PrevV.getKind() == RefVal::Released) {
2872 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2873 os << " The object is not eligible for garbage collection until the "
2874 "retain count reaches 0 again.";
2875 }
2876
Ted Kremenekc26c4692009-02-18 03:48:14 +00002877 break;
2878
2879 case RefVal::Released:
2880 os << "Object released.";
2881 break;
2882
2883 case RefVal::ReturnedOwned:
2884 os << "Object returned to caller as an owning reference (single retain "
2885 "count transferred to caller).";
2886 break;
2887
2888 case RefVal::ReturnedNotOwned:
2889 os << "Object returned to caller with a +0 (non-owning) retain count.";
2890 break;
2891
2892 default:
2893 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002894 }
2895
2896 // Emit any remaining diagnostics for the argument effects (if any).
2897 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2898 E=AEffects.end(); I != E; ++I) {
2899
2900 // A bunch of things have alternate behavior under GC.
2901 if (TF.isGCEnabled())
2902 switch (*I) {
2903 default: break;
2904 case Autorelease:
2905 os << "In GC mode an 'autorelease' has no effect.";
2906 continue;
2907 case IncRefMsg:
2908 os << "In GC mode the 'retain' message has no effect.";
2909 continue;
2910 case DecRefMsg:
2911 os << "In GC mode the 'release' message has no effect.";
2912 continue;
2913 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002914 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002915 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002916
2917 if (os.str().empty())
2918 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002919
2920 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek2fba6152009-04-01 06:13:56 +00002921 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
Ted Kremenek23563642009-03-06 23:58:11 +00002922 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002923
2924 // Add the range by scanning the children of the statement for any bindings
2925 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002926 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002927 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002928 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002929 P->addRange(Exp->getSourceRange());
2930 break;
2931 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002932
2933 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002934}
2935
Ted Kremenekb15eba42008-10-04 05:50:14 +00002936namespace {
2937class VISIBILITY_HIDDEN FindUniqueBinding :
2938 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002939 SymbolRef Sym;
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002940 const MemRegion* Binding;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002941 bool First;
2942
2943 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002944 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002945
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002946 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2947 SVal val) {
Ted Kremenek74556a12009-03-26 03:35:11 +00002948
2949 SymbolRef SymV = val.getAsSymbol();
2950 if (!SymV || SymV != Sym)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002951 return true;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002952
Ted Kremenekb15eba42008-10-04 05:50:14 +00002953 if (Binding) {
2954 First = false;
2955 return false;
2956 }
2957 else
2958 Binding = R;
2959
2960 return true;
2961 }
2962
2963 operator bool() { return First && Binding; }
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002964 const MemRegion* getRegion() { return Binding; }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002965};
2966}
2967
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002968static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00002969GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002970 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00002971
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002972 // Find both first node that referred to the tracked symbol and the
2973 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002974 const ExplodedNode<GRState>* Last = N;
2975 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002976
2977 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002978 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002979 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002980
Ted Kremenek6064a362008-07-07 16:21:19 +00002981 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002982 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002983
Ted Kremenek86617f42009-02-07 22:19:59 +00002984 FindUniqueBinding FB(Sym);
2985 StateMgr.iterBindings(St, FB);
2986 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002987
Ted Kremenekd7e26782008-05-16 18:33:44 +00002988 Last = N;
2989 N = N->pred_empty() ? NULL : *(N->pred_begin());
2990 }
2991
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002992 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002993}
Ted Kremenek4c479322008-05-06 23:07:13 +00002994
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002995PathDiagnosticPiece*
2996CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002997 // Tell the BugReporter to report cases when the tracked symbol is
2998 // assigned to different variables, etc.
Ted Kremenek6537a642009-03-17 19:42:23 +00002999 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00003000 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00003001 return RangedBugReport::getEndPath(BR, EndN);
3002}
3003
3004PathDiagnosticPiece*
3005CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
3006
3007 GRBugReporter& BR = cast<GRBugReporter>(br);
3008 // Tell the BugReporter to report cases when the tracked symbol is
3009 // assigned to different variables, etc.
3010 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
3011
3012 // We are reporting a leak. Walk up the graph to get to the first node where
3013 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00003014 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00003015 const ExplodedNode<GRState>* AllocNode = 0;
3016 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00003017
3018 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00003019 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003020
Ted Kremenekd7e26782008-05-16 18:33:44 +00003021 // Get the allocate site.
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003022 assert(AllocNode);
Ted Kremenekd7e26782008-05-16 18:33:44 +00003023 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003024
Ted Kremenekea794e92008-05-05 18:50:19 +00003025 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00003026 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003027
Ted Kremenek505dc672009-04-07 04:54:20 +00003028 // Compute an actual location for the leak. Sometimes a leak doesn't
3029 // occur at an actual statement (e.g., transition between blocks; end
3030 // of function) so we need to walk the graph and compute a real location.
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003031 const ExplodedNode<GRState>* LeakN = EndN;
3032 PathDiagnosticLocation L;
3033
3034 while (LeakN) {
3035 ProgramPoint P = LeakN->getLocation();
3036
3037 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
3038 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
3039 break;
3040 }
3041 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
3042 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
3043 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
3044 break;
3045 }
3046 }
3047
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003048 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
3049 }
Sebastian Redlbc9ef252009-04-26 20:35:05 +00003050
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003051 if (!L.isValid()) {
Sebastian Redlbc9ef252009-04-26 20:35:05 +00003052 L = PathDiagnosticLocation(
3053 BR.getStateManager().getCodeDecl().getBodyRBrace(BR.getContext()),
3054 SMgr);
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003055 }
3056
Ted Kremenek59f9fe12009-02-07 21:59:45 +00003057 std::string sbuf;
3058 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00003059
Ted Kremenekea794e92008-05-05 18:50:19 +00003060 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00003061
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00003062 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00003063 os << " and stored into '" << FirstBinding->getString() << '\'';
3064
Ted Kremenek311f3d42008-10-22 23:56:21 +00003065 // Get the retain count.
3066 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
3067
3068 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00003069 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
3070 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
3071 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00003072 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
3073 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00003074 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00003075 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00003076 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00003077 " in the Memory Management Guide for Cocoa (object leaked).";
3078 }
3079 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00003080 os << " is no longer referenced after this point and has a retain count of"
3081 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00003082 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003083
Ted Kremenek23563642009-03-06 23:58:11 +00003084 return new PathDiagnosticEventPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003085}
3086
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00003087
Ted Kremenekc26c4692009-02-18 03:48:14 +00003088CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
3089 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00003090 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00003091 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00003092{
3093
Ted Kremenekd7e26782008-05-16 18:33:44 +00003094 // Most bug reports are cached at the location where they occured.
3095 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00003096 // allocated, and only report a single path. To do this, we need to find
3097 // the allocation site of a piece of tracked memory, which we do via a
3098 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
3099 // Note that this is *not* the trimmed graph; we are guaranteed, however,
3100 // that all ancestor nodes that represent the allocation site have the
3101 // same SourceLocation.
3102 const ExplodedNode<GRState>* AllocNode = 0;
3103
3104 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00003105 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00003106
Ted Kremenek86617f42009-02-07 22:19:59 +00003107 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00003108 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00003109 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00003110
3111 // Fill in the description of the bug.
3112 Description.clear();
3113 llvm::raw_string_ostream os(Description);
3114 SourceManager& SMgr = Eng.getContext().getSourceManager();
3115 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00003116 os << "Potential leak of object allocated on line " << AllocLine;
3117
3118 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
3119 if (AllocBinding)
Ted Kremenek5ee01662009-04-02 03:42:38 +00003120 os << " and stored into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00003121}
3122
Ted Kremeneka7338b42008-03-11 06:39:11 +00003123//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003124// Handle dead symbols and end-of-path.
3125//===----------------------------------------------------------------------===//
3126
3127void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3128 GREndPathNodeBuilder<GRState>& Builder) {
3129
3130 const GRState* St = Builder.getState();
3131 RefBindings B = St->get<RefBindings>();
3132
3133 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3134 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3135
3136 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3137 bool hasLeak = false;
3138
3139 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003140 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3141 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003142
3143 St = X.first;
3144 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3145 }
3146
3147 if (Leaked.empty())
3148 return;
3149
3150 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3151
3152 if (!N)
3153 return;
3154
3155 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3156 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3157
3158 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3159 : leakWithinFunction);
3160 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003161 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003162 BR->EmitReport(report);
3163 }
3164}
3165
3166void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3167 GRExprEngine& Eng,
3168 GRStmtNodeBuilder<GRState>& Builder,
3169 ExplodedNode<GRState>* Pred,
3170 Stmt* S,
3171 const GRState* St,
3172 SymbolReaper& SymReaper) {
3173
Ted Kremenek876d8df2009-02-19 23:47:02 +00003174 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003175 RefBindings B = St->get<RefBindings>();
3176 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3177
3178 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3179 E = SymReaper.dead_end(); I != E; ++I) {
3180
3181 const RefVal* T = B.lookup(*I);
3182 if (!T) continue;
3183
3184 bool hasLeak = false;
3185
3186 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003187 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003188
3189 St = X.first;
3190
3191 if (hasLeak)
3192 Leaked.push_back(std::make_pair(*I,X.second));
3193 }
3194
Ted Kremenek876d8df2009-02-19 23:47:02 +00003195 if (!Leaked.empty()) {
3196 // Create a new intermediate node representing the leak point. We
3197 // use a special program point that represents this checker-specific
3198 // transition. We use the address of RefBIndex as a unique tag for this
3199 // checker. We will create another node (if we don't cache out) that
3200 // removes the retain-count bindings from the state.
3201 // NOTE: We use 'generateNode' so that it does interplay with the
3202 // auto-transition logic.
3203 ExplodedNode<GRState>* N =
3204 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003205
Ted Kremenek876d8df2009-02-19 23:47:02 +00003206 if (!N)
3207 return;
3208
3209 // Generate the bug reports.
3210 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3211 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3212
3213 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3214 : leakWithinFunction);
3215 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003216 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3217 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003218 BR->EmitReport(report);
3219 }
Ted Kremenek708af042009-02-05 06:50:21 +00003220
Ted Kremenek876d8df2009-02-19 23:47:02 +00003221 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003222 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003223
3224 // Now generate a new node that nukes the old bindings.
3225 GRStateRef state(St, Eng.getStateManager());
3226 RefBindings::Factory& F = state.get_context<RefBindings>();
3227
3228 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3229 E = SymReaper.dead_end(); I!=E; ++I)
3230 B = F.Remove(B, *I);
3231
3232 state = state.set<RefBindings>(B);
3233 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003234}
3235
3236void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3237 GRStmtNodeBuilder<GRState>& Builder,
3238 Expr* NodeExpr, Expr* ErrorExpr,
3239 ExplodedNode<GRState>* Pred,
3240 const GRState* St,
3241 RefVal::Kind hasErr, SymbolRef Sym) {
3242 Builder.BuildSinks = true;
3243 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3244
3245 if (!N) return;
3246
3247 CFRefBug *BT = 0;
3248
Ted Kremenek6537a642009-03-17 19:42:23 +00003249 switch (hasErr) {
3250 default:
3251 assert(false && "Unhandled error.");
3252 return;
3253 case RefVal::ErrorUseAfterRelease:
3254 BT = static_cast<CFRefBug*>(useAfterRelease);
3255 break;
3256 case RefVal::ErrorReleaseNotOwned:
3257 BT = static_cast<CFRefBug*>(releaseNotOwned);
3258 break;
3259 case RefVal::ErrorDeallocGC:
3260 BT = static_cast<CFRefBug*>(deallocGC);
3261 break;
3262 case RefVal::ErrorDeallocNotOwned:
3263 BT = static_cast<CFRefBug*>(deallocNotOwned);
3264 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003265 }
3266
Ted Kremenekc26c4692009-02-18 03:48:14 +00003267 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003268 report->addRange(ErrorExpr->getSourceRange());
3269 BR->EmitReport(report);
3270}
3271
3272//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003273// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003274//===----------------------------------------------------------------------===//
3275
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003276GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3277 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003278 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003279}