blob: eb7d04a3425392fbaca5260624d0cc28e7ea9c98 [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
Ted Kremenek314b1952009-04-29 23:03:22 +0000152static const ObjCMethodDecl*
153ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
154 ObjCInterfaceDecl *ID =
155 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
156
157 return MD->isInstanceMethod()
158 ? ID->lookupInstanceMethod(Context, MD->getSelector())
159 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000160}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000161
Ted Kremenek7d421f32008-04-09 23:49:11 +0000162//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000163// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000164//===----------------------------------------------------------------------===//
165
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000166static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(0, &II);
169}
170
Ted Kremenek0e344d42008-05-06 00:30:21 +0000171static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
172 IdentifierInfo* II = &Ctx.Idents.get(name);
173 return Ctx.Selectors.getSelector(1, &II);
174}
175
Ted Kremenek272aa852008-06-25 21:21:56 +0000176//===----------------------------------------------------------------------===//
177// Type querying functions.
178//===----------------------------------------------------------------------===//
179
Ted Kremenek17144e82009-01-12 21:45:02 +0000180static bool hasPrefix(const char* s, const char* prefix) {
181 if (!prefix)
182 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000183
Ted Kremenek17144e82009-01-12 21:45:02 +0000184 char c = *s;
185 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000186
Ted Kremenek17144e82009-01-12 21:45:02 +0000187 while (c != '\0' && cP != '\0') {
188 if (c != cP) break;
189 c = *(++s);
190 cP = *(++prefix);
191 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000192
Ted Kremenek17144e82009-01-12 21:45:02 +0000193 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000194}
195
Ted Kremenek17144e82009-01-12 21:45:02 +0000196static bool hasSuffix(const char* s, const char* suffix) {
197 const char* loc = strstr(s, suffix);
198 return loc && strcmp(suffix, loc) == 0;
199}
200
201static bool isRefType(QualType RetTy, const char* prefix,
202 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
205 const char* TDName = TD->getDecl()->getIdentifier()->getName();
206 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
207 }
208
209 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Is the type void*?
213 const PointerType* PT = RetTy->getAsPointerType();
214 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000215 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000216
217 // Does the name start with the prefix?
218 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000219}
220
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000221//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000222// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000223//===----------------------------------------------------------------------===//
224
Ted Kremenek272aa852008-06-25 21:21:56 +0000225namespace {
226/// ArgEffect is used to summarize a function/method call's effect on a
227/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000228enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
229 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
230 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000231
232/// ArgEffects summarizes the effects of a function/method call on all of
233/// its arguments.
234typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000235}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000236
Ted Kremeneka7338b42008-03-11 06:39:11 +0000237namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000238template <> struct FoldingSetTrait<ArgEffects> {
239 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
240 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
241 ID.AddInteger(I->first);
242 ID.AddInteger((unsigned) I->second);
243 }
244 }
245};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000246} // end llvm namespace
247
248namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000249
250/// RetEffect is used to summarize a function/method call's behavior with
251/// respect to its return value.
252class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000253public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000254 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000255 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000256
257 enum ObjKind { CF, ObjC, AnyObj };
258
Ted Kremeneka7338b42008-03-11 06:39:11 +0000259private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000260 Kind K;
261 ObjKind O;
262 unsigned index;
263
264 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
265 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000266
Ted Kremeneka7338b42008-03-11 06:39:11 +0000267public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000268 Kind getKind() const { return K; }
269
270 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000271
272 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000273 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000274 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000275 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000276
Ted Kremenek314b1952009-04-29 23:03:22 +0000277 bool isOwned() const {
278 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
279 }
280
Ted Kremenek272aa852008-06-25 21:21:56 +0000281 static RetEffect MakeAlias(unsigned Idx) {
282 return RetEffect(Alias, Idx);
283 }
284 static RetEffect MakeReceiverAlias() {
285 return RetEffect(ReceiverAlias);
286 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000287 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
288 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000289 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000290 static RetEffect MakeNotOwned(ObjKind o) {
291 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000292 }
293 static RetEffect MakeGCNotOwned() {
294 return RetEffect(GCNotOwnedSymbol, ObjC);
295 }
296
Ted Kremenek272aa852008-06-25 21:21:56 +0000297 static RetEffect MakeNoRet() {
298 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000299 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000300
Ted Kremenek272aa852008-06-25 21:21:56 +0000301 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000302 ID.AddInteger((unsigned)K);
303 ID.AddInteger((unsigned)O);
304 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000305 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000306};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000307
Ted Kremenek272aa852008-06-25 21:21:56 +0000308
309class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000310 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
311 /// specifies the argument (starting from 0). This can be sparsely
312 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000313 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000314
315 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
316 /// do not have an entry in Args.
317 ArgEffect DefaultArgEffect;
318
Ted Kremenek272aa852008-06-25 21:21:56 +0000319 /// Receiver - If this summary applies to an Objective-C message expression,
320 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000321 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000322
323 /// Ret - The effect on the return value. Used to indicate if the
324 /// function/method call returns a new tracked symbol, returns an
325 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000326 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000327
Ted Kremenekf2717b02008-07-18 17:24:20 +0000328 /// EndPath - Indicates that execution of this method/function should
329 /// terminate the simulation of a path.
330 bool EndPath;
331
Ted Kremeneka7338b42008-03-11 06:39:11 +0000332public:
333
Ted Kremenekbcaff792008-05-06 15:44:25 +0000334 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000335 ArgEffect ReceiverEff, bool endpath = false)
336 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
337 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000338
Ted Kremenek272aa852008-06-25 21:21:56 +0000339 /// getArg - Return the argument effect on the argument specified by
340 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000341 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000342
Ted Kremenekae855d42008-04-24 17:22:33 +0000343 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000344 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000345
346 // If Args is present, it is likely to contain only 1 element.
347 // Just do a linear search. Do it from the back because functions with
348 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000349 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000350 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
351 I!=E; ++I) {
352
353 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000354 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000355
356 if (idx == I->first)
357 return I->second;
358 }
359
Ted Kremenekbcaff792008-05-06 15:44:25 +0000360 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000361 }
362
Ted Kremenek272aa852008-06-25 21:21:56 +0000363 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000364 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000365 return Ret;
366 }
367
Ted Kremenekf2717b02008-07-18 17:24:20 +0000368 /// isEndPath - Returns true if executing the given method/function should
369 /// terminate the path.
370 bool isEndPath() const { return EndPath; }
371
Ted Kremenek272aa852008-06-25 21:21:56 +0000372 /// getReceiverEffect - Returns the effect on the receiver of the call.
373 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000374 ArgEffect getReceiverEffect() const {
375 return Receiver;
376 }
377
Ted Kremenek2719e982008-06-17 02:43:46 +0000378 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000379
Ted Kremenek2719e982008-06-17 02:43:46 +0000380 ExprIterator begin_args() const { return Args->begin(); }
381 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000382
Ted Kremenek266d8b62008-05-06 02:26:56 +0000383 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000384 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000385 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000386 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000387 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000388 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000389 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000390 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000391 }
392
393 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000394 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000395 }
396};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000397} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000398
Ted Kremenek272aa852008-06-25 21:21:56 +0000399//===----------------------------------------------------------------------===//
400// Data structures for constructing summaries.
401//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000402
Ted Kremenek272aa852008-06-25 21:21:56 +0000403namespace {
404class VISIBILITY_HIDDEN ObjCSummaryKey {
405 IdentifierInfo* II;
406 Selector S;
407public:
408 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
409 : II(ii), S(s) {}
410
Ted Kremenek314b1952009-04-29 23:03:22 +0000411 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000412 : II(d ? d->getIdentifier() : 0), S(s) {}
413
414 ObjCSummaryKey(Selector s)
415 : II(0), S(s) {}
416
417 IdentifierInfo* getIdentifier() const { return II; }
418 Selector getSelector() const { return S; }
419};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000420}
421
422namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000423template <> struct DenseMapInfo<ObjCSummaryKey> {
424 static inline ObjCSummaryKey getEmptyKey() {
425 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
426 DenseMapInfo<Selector>::getEmptyKey());
427 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000428
Ted Kremenek272aa852008-06-25 21:21:56 +0000429 static inline ObjCSummaryKey getTombstoneKey() {
430 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
431 DenseMapInfo<Selector>::getTombstoneKey());
432 }
433
434 static unsigned getHashValue(const ObjCSummaryKey &V) {
435 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
436 & 0x88888888)
437 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
438 & 0x55555555);
439 }
440
441 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
442 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
443 RHS.getIdentifier()) &&
444 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
445 RHS.getSelector());
446 }
447
448 static bool isPod() {
449 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
450 DenseMapInfo<Selector>::isPod();
451 }
452};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000453} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000454
Ted Kremenek84f010c2008-06-23 23:30:29 +0000455namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000456class VISIBILITY_HIDDEN ObjCSummaryCache {
457 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
458 MapTy M;
459public:
460 ObjCSummaryCache() {}
461
462 typedef MapTy::iterator iterator;
463
Ted Kremenek314b1952009-04-29 23:03:22 +0000464 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
465 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000466 // Lookup the method using the decl for the class @interface. If we
467 // have no decl, lookup using the class name.
468 return D ? find(D, S) : find(ClsName, S);
469 }
470
Ted Kremenek314b1952009-04-29 23:03:22 +0000471 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000472 // Do a lookup with the (D,S) pair. If we find a match return
473 // the iterator.
474 ObjCSummaryKey K(D, S);
475 MapTy::iterator I = M.find(K);
476
477 if (I != M.end() || !D)
478 return I;
479
480 // Walk the super chain. If we find a hit with a parent, we'll end
481 // up returning that summary. We actually allow that key (null,S), as
482 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
483 // generate initial summaries without having to worry about NSObject
484 // being declared.
485 // FIXME: We may change this at some point.
486 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
487 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
488 break;
489
490 if (!C)
491 return I;
492 }
493
494 // Cache the summary with original key to make the next lookup faster
495 // and return the iterator.
496 M[K] = I->second;
497 return I;
498 }
499
Ted Kremenek9449ca92008-08-12 20:41:56 +0000500
Ted Kremenek272aa852008-06-25 21:21:56 +0000501 iterator find(Expr* Receiver, Selector S) {
502 return find(getReceiverDecl(Receiver), S);
503 }
504
505 iterator find(IdentifierInfo* II, Selector S) {
506 // FIXME: Class method lookup. Right now we dont' have a good way
507 // of going between IdentifierInfo* and the class hierarchy.
508 iterator I = M.find(ObjCSummaryKey(II, S));
509 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
510 }
511
512 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
513
514 const PointerType* PT = E->getType()->getAsPointerType();
515 if (!PT) return 0;
516
517 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
518 if (!OI) return 0;
519
520 return OI ? OI->getDecl() : 0;
521 }
522
523 iterator end() { return M.end(); }
524
525 RetainSummary*& operator[](ObjCMessageExpr* ME) {
526
527 Selector S = ME->getSelector();
528
529 if (Expr* Receiver = ME->getReceiver()) {
530 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
531 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
532 }
533
534 return M[ObjCSummaryKey(ME->getClassName(), S)];
535 }
536
537 RetainSummary*& operator[](ObjCSummaryKey K) {
538 return M[K];
539 }
540
541 RetainSummary*& operator[](Selector S) {
542 return M[ ObjCSummaryKey(S) ];
543 }
544};
545} // end anonymous namespace
546
547//===----------------------------------------------------------------------===//
548// Data structures for managing collections of summaries.
549//===----------------------------------------------------------------------===//
550
551namespace {
552class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000553
554 //==-----------------------------------------------------------------==//
555 // Typedefs.
556 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000557
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000558 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
559 ArgEffectsSetTy;
560
561 typedef llvm::FoldingSet<RetainSummary>
562 SummarySetTy;
563
564 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
565 FuncSummariesTy;
566
Ted Kremenek84f010c2008-06-23 23:30:29 +0000567 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000568
569 //==-----------------------------------------------------------------==//
570 // Data.
571 //==-----------------------------------------------------------------==//
572
Ted Kremenek272aa852008-06-25 21:21:56 +0000573 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000574 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000575
Ted Kremenekede40b72008-07-09 18:11:16 +0000576 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
577 /// "CFDictionaryCreate".
578 IdentifierInfo* CFDictionaryCreateII;
579
Ted Kremenek272aa852008-06-25 21:21:56 +0000580 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000581 const bool GCEnabled;
582
Ted Kremenek272aa852008-06-25 21:21:56 +0000583 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000584 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000585
Ted Kremenek272aa852008-06-25 21:21:56 +0000586 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000587 FuncSummariesTy FuncSummaries;
588
Ted Kremenek272aa852008-06-25 21:21:56 +0000589 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
590 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000591 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000592
Ted Kremenek272aa852008-06-25 21:21:56 +0000593 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000594 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000595
Ted Kremenek272aa852008-06-25 21:21:56 +0000596 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000597 ArgEffectsSetTy ArgEffectsSet;
598
Ted Kremenek272aa852008-06-25 21:21:56 +0000599 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
600 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000601 llvm::BumpPtrAllocator BPAlloc;
602
Ted Kremenek272aa852008-06-25 21:21:56 +0000603 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000604 ArgEffects ScratchArgs;
605
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000606 RetainSummary* StopSummary;
607
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000608 //==-----------------------------------------------------------------==//
609 // Methods.
610 //==-----------------------------------------------------------------==//
611
Ted Kremenek272aa852008-06-25 21:21:56 +0000612 /// getArgEffects - Returns a persistent ArgEffects object based on the
613 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000614 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000615
Ted Kremenek562c1302008-05-05 16:51:50 +0000616 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000617
618public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000619 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000620
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000621 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
622 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000623 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000624
Ted Kremenek266d8b62008-05-06 02:26:56 +0000625 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000626 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000627 ArgEffect DefaultEff = MayEscape,
628 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000629
Ted Kremenek266d8b62008-05-06 02:26:56 +0000630 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000631 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000632 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000633 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000634 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000635
Ted Kremeneka821b792009-04-29 05:04:30 +0000636 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000637 if (StopSummary)
638 return StopSummary;
639
640 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
641 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000642
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000643 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000644 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000645
Ted Kremeneka821b792009-04-29 05:04:30 +0000646 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000647
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000648 void InitializeClassMethodSummaries();
649 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000650
Ted Kremenek35920ed2009-01-07 00:39:56 +0000651 bool isTrackedObjectType(QualType T);
652
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000653private:
654
Ted Kremenekf2717b02008-07-18 17:24:20 +0000655 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
656 RetainSummary* Summ) {
657 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
658 }
659
Ted Kremenek272aa852008-06-25 21:21:56 +0000660 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
661 ObjCClassMethodSummaries[S] = Summ;
662 }
663
664 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
665 ObjCMethodSummaries[S] = Summ;
666 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000667
668 void addClassMethSummary(const char* Cls, const char* nullaryName,
669 RetainSummary *Summ) {
670 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
671 Selector S = GetNullarySelector(nullaryName, Ctx);
672 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
673 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000674
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000675 void addInstMethSummary(const char* Cls, const char* nullaryName,
676 RetainSummary *Summ) {
677 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
678 Selector S = GetNullarySelector(nullaryName, Ctx);
679 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
680 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000681
682 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000683 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000684
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000685 while (const char* s = va_arg(argp, const char*))
686 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000687
688 return Ctx.Selectors.getSelector(II.size(), &II[0]);
689 }
690
691 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
692 RetainSummary* Summ, va_list argp) {
693 Selector S = generateSelector(argp);
694 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000695 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000696
697 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
698 va_list argp;
699 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000700 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000701 va_end(argp);
702 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000703
704 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
705 va_list argp;
706 va_start(argp, Summ);
707 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
708 va_end(argp);
709 }
710
711 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
712 va_list argp;
713 va_start(argp, Summ);
714 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
715 va_end(argp);
716 }
717
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000718 void addPanicSummary(const char* Cls, ...) {
719 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
720 DoNothing, DoNothing, true);
721 va_list argp;
722 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000723 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000724 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000725 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000726
Ted Kremeneka7338b42008-03-11 06:39:11 +0000727public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000728
729 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000730 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000731 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000732 GCEnabled(gcenabled), StopSummary(0) {
733
734 InitializeClassMethodSummaries();
735 InitializeMethodSummaries();
736 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000737
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000738 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000739
Ted Kremenekd13c1872008-06-24 03:56:45 +0000740 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000741
Ted Kremenek314b1952009-04-29 23:03:22 +0000742 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
743 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000744 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000745 ID, ME->getMethodDecl(), ME->getType());
746 }
747
Ted Kremenek04e00302009-04-29 17:09:14 +0000748 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000749 const ObjCInterfaceDecl* ID,
750 const ObjCMethodDecl *MD,
751 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000752
753 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000754 const ObjCInterfaceDecl *ID,
755 const ObjCMethodDecl *MD,
756 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000757
758 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
759 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
760 ME->getClassInfo().first,
761 ME->getMethodDecl(), ME->getType());
762 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000763
764 /// getMethodSummary - This version of getMethodSummary is used to query
765 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000766 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
767 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000768 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000769 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000770 IdentifierInfo *ClsName = ID->getIdentifier();
771 QualType ResultTy = MD->getResultType();
772
Ted Kremenek81eb4642009-04-30 05:47:23 +0000773 // Resolve the method decl last.
774 if (const ObjCMethodDecl *InterfaceMD =
775 ResolveToInterfaceMethodDecl(MD, Ctx))
776 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000777
Ted Kremenek91b89a42009-04-29 17:17:48 +0000778 if (MD->isInstanceMethod())
779 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
780 else
781 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
782 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000783
Ted Kremenek314b1952009-04-29 23:03:22 +0000784 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
785 Selector S, QualType RetTy);
786
787 RetainSummary* getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000788
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000789 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000790};
791
792} // end anonymous namespace
793
794//===----------------------------------------------------------------------===//
795// Implementation of checker data structures.
796//===----------------------------------------------------------------------===//
797
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000798RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000799
800 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
801 // mitigating the need to do explicit cleanup of the
802 // Argument-Effect summaries.
803
Ted Kremenek42ea0322008-05-05 23:55:01 +0000804 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
805 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000806 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000807}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000808
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000809ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000810
Ted Kremenekae855d42008-04-24 17:22:33 +0000811 if (ScratchArgs.empty())
812 return NULL;
813
814 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000815 llvm::FoldingSetNodeID profile;
816 profile.Add(ScratchArgs);
817 void* InsertPos;
818
Ted Kremenekae855d42008-04-24 17:22:33 +0000819 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000820 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000821 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000822
Ted Kremenekae855d42008-04-24 17:22:33 +0000823 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000824 ScratchArgs.clear();
825 return &E->getValue();
826 }
827
828 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000829 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000830
831 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000832 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000833
834 ScratchArgs.clear();
835 return &E->getValue();
836}
837
Ted Kremenek266d8b62008-05-06 02:26:56 +0000838RetainSummary*
839RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000840 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000841 ArgEffect DefaultEff,
842 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000843
Ted Kremenekae855d42008-04-24 17:22:33 +0000844 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000845 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000846 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
847 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000848
Ted Kremenekae855d42008-04-24 17:22:33 +0000849 // Look up the uniqued summary, or create one if it doesn't exist.
850 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000851 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000852
853 if (Summ)
854 return Summ;
855
Ted Kremenekae855d42008-04-24 17:22:33 +0000856 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000857 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000858 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000859 SummarySet.InsertNode(Summ, InsertPos);
860
861 return Summ;
862}
863
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000864//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000865// Predicates.
866//===----------------------------------------------------------------------===//
867
Ted Kremenek0d813552009-04-23 22:11:07 +0000868bool RetainSummaryManager::isTrackedObjectType(QualType Ty) {
869 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000870 return false;
871
Ted Kremenek0d813552009-04-23 22:11:07 +0000872 // We assume that id<..>, id, and "Class" all represent tracked objects.
873 const PointerType *PT = Ty->getAsPointerType();
874 if (PT == 0)
875 return true;
876
877 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000878
879 // We assume that id<..>, id, and "Class" all represent tracked objects.
880 if (!OT)
881 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000882
883 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000884 // FIXME: We can memoize here if this gets too expensive.
885 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
886 ObjCInterfaceDecl* ID = OT->getDecl();
887
888 for ( ; ID ; ID = ID->getSuperClass())
889 if (ID->getIdentifier() == NSObjectII)
890 return true;
891
892 return false;
893}
894
895//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000896// Summary creation for functions (largely uses of Core Foundation).
897//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000898
Ted Kremenek17144e82009-01-12 21:45:02 +0000899static bool isRetain(FunctionDecl* FD, const char* FName) {
900 const char* loc = strstr(FName, "Retain");
901 return loc && loc[sizeof("Retain")-1] == '\0';
902}
903
904static bool isRelease(FunctionDecl* FD, const char* FName) {
905 const char* loc = strstr(FName, "Release");
906 return loc && loc[sizeof("Release")-1] == '\0';
907}
908
Ted Kremenekd13c1872008-06-24 03:56:45 +0000909RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000910
911 SourceLocation Loc = FD->getLocation();
912
913 if (!Loc.isFileID())
914 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000915
Ted Kremenekae855d42008-04-24 17:22:33 +0000916 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000917 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000918
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000919 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000920 return I->second;
921
922 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000923 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000924
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000925 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000926 // We generate "stop" summaries for implicitly defined functions.
927 if (FD->isImplicit()) {
928 S = getPersistentStopSummary();
929 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000930 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000931
Ted Kremenek064ef322009-02-23 16:51:39 +0000932 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000933 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000934 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000935 const char* FName = FD->getIdentifier()->getName();
936
Ted Kremenek38c6f022009-03-05 22:11:14 +0000937 // Strip away preceding '_'. Doing this here will effect all the checks
938 // down below.
939 while (*FName == '_') ++FName;
940
Ted Kremenek17144e82009-01-12 21:45:02 +0000941 // Inspect the result type.
942 QualType RetTy = FT->getResultType();
943
944 // FIXME: This should all be refactored into a chain of "summary lookup"
945 // filters.
946 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
947 // FIXES: <rdar://problem/6326900>
948 // This should be addressed using a API table. This strcmp is also
949 // a little gross, but there is no need to super optimize here.
950 assert (ScratchArgs.empty());
951 ScratchArgs.push_back(std::make_pair(1, DecRef));
952 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
953 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000954 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000955
956 // Enable this code once the semantics of NSDeallocateObject are resolved
957 // for GC. <rdar://problem/6619988>
958#if 0
959 // Handle: NSDeallocateObject(id anObject);
960 // This method does allow 'nil' (although we don't check it now).
961 if (strcmp(FName, "NSDeallocateObject") == 0) {
962 return RetTy == Ctx.VoidTy
963 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
964 : getPersistentStopSummary();
965 }
966#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000967
968 // Handle: id NSMakeCollectable(CFTypeRef)
969 if (strcmp(FName, "NSMakeCollectable") == 0) {
970 S = (RetTy == Ctx.getObjCIdType())
971 ? getUnarySummary(FT, cfmakecollectable)
972 : getPersistentStopSummary();
973
974 break;
975 }
976
977 if (RetTy->isPointerType()) {
978 // For CoreFoundation ('CF') types.
979 if (isRefType(RetTy, "CF", &Ctx, FName)) {
980 if (isRetain(FD, FName))
981 S = getUnarySummary(FT, cfretain);
982 else if (strstr(FName, "MakeCollectable"))
983 S = getUnarySummary(FT, cfmakecollectable);
984 else
985 S = getCFCreateGetRuleSummary(FD, FName);
986
987 break;
988 }
989
990 // For CoreGraphics ('CG') types.
991 if (isRefType(RetTy, "CG", &Ctx, FName)) {
992 if (isRetain(FD, FName))
993 S = getUnarySummary(FT, cfretain);
994 else
995 S = getCFCreateGetRuleSummary(FD, FName);
996
997 break;
998 }
999
1000 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1001 if (isRefType(RetTy, "DADisk") ||
1002 isRefType(RetTy, "DADissenter") ||
1003 isRefType(RetTy, "DASessionRef")) {
1004 S = getCFCreateGetRuleSummary(FD, FName);
1005 break;
1006 }
1007
1008 break;
1009 }
1010
1011 // Check for release functions, the only kind of functions that we care
1012 // about that don't return a pointer type.
1013 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001014 // Test for 'CGCF'.
1015 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1016 FName += 4;
1017 else
1018 FName += 2;
1019
1020 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001021 S = getUnarySummary(FT, cfrelease);
1022 else {
Ted Kremenek7b293682009-01-29 22:45:13 +00001023 assert (ScratchArgs.empty());
1024 // Remaining CoreFoundation and CoreGraphics functions.
1025 // We use to assume that they all strictly followed the ownership idiom
1026 // and that ownership cannot be transferred. While this is technically
1027 // correct, many methods allow a tracked object to escape. For example:
1028 //
1029 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1030 // CFDictionaryAddValue(y, key, x);
1031 // CFRelease(x);
1032 // ... it is okay to use 'x' since 'y' has a reference to it
1033 //
1034 // We handle this and similar cases with the follow heuristic. If the
1035 // function name contains "InsertValue", "SetValue" or "AddValue" then
1036 // we assume that arguments may "escape."
1037 //
1038 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1039 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001040 CStrInCStrNoCase(FName, "SetValue") ||
1041 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001042 ? MayEscape : DoNothing;
1043
1044 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001045 }
1046 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001047 }
1048 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +00001049
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001050 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001051 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001052}
1053
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001054RetainSummary*
1055RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1056 const char* FName) {
1057
Ted Kremenek562c1302008-05-05 16:51:50 +00001058 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1059 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001060
Ted Kremenek562c1302008-05-05 16:51:50 +00001061 if (strstr(FName, "Get"))
1062 return getCFSummaryGetRule(FD);
1063
1064 return 0;
1065}
1066
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001067RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001068RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1069 UnaryFuncKind func) {
1070
Ted Kremenek17144e82009-01-12 21:45:02 +00001071 // Sanity check that this is *really* a unary function. This can
1072 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001073 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001074 if (!FTP || FTP->getNumArgs() != 1)
1075 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001076
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001077 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001078
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001079 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +00001080 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001081 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001082 return getPersistentSummary(RetEffect::MakeAlias(0),
1083 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001084 }
1085
1086 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001087 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001088 return getPersistentSummary(RetEffect::MakeNoRet(),
1089 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001090 }
1091
1092 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +00001093 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1094 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001095 }
1096
1097 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001098 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001099 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001100 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001101}
1102
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001103RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001104 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001105
1106 if (FD->getIdentifier() == CFDictionaryCreateII) {
1107 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1108 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1109 }
1110
Ted Kremenek68621b92009-01-28 05:56:51 +00001111 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001112}
1113
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001114RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001115 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001116 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1117 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001118}
1119
Ted Kremeneka7338b42008-03-11 06:39:11 +00001120//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001121// Summary creation for Selectors.
1122//===----------------------------------------------------------------------===//
1123
Ted Kremenekbcaff792008-05-06 15:44:25 +00001124RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001125RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001126 assert(ScratchArgs.empty());
1127
Ted Kremenek802cfc72009-02-20 00:05:35 +00001128 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001129 return getPersistentSummary(Loc::IsLocType(RetTy)
1130 ? RetEffect::MakeReceiverAlias()
1131 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001132}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001133
Ted Kremenek923fc392009-04-24 23:32:32 +00001134RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001135RetainSummaryManager::getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD){
Ted Kremenek923fc392009-04-24 23:32:32 +00001136 if (!MD)
1137 return 0;
1138
1139 assert(ScratchArgs.empty());
1140
1141 // Determine if there is a special return effect for this method.
1142 bool hasRetEffect = false;
1143 RetEffect RE = RetEffect::MakeNoRet();
1144
1145 if (isTrackedObjectType(MD->getResultType())) {
1146 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001147 RE = isGCEnabled() ? RetEffect::MakeGCNotOwned()
1148 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek923fc392009-04-24 23:32:32 +00001149 hasRetEffect = true;
1150 }
1151 else {
1152 // Default to 'not owned'.
1153 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1154 }
1155 }
1156
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001157 // Determine if there are any arguments with a specific ArgEffect.
1158 bool hasArgEffect = false;
1159 unsigned i = 0;
1160 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1161 E = MD->param_end(); I != E; ++I, ++i) {
1162 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
1163 ScratchArgs.push_back(std::make_pair(i, IncRefMsg));
1164 hasArgEffect = true;
1165 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001166 else if ((*I)->getAttr<ObjCOwnershipCFRetainAttr>()) {
1167 ScratchArgs.push_back(std::make_pair(i, IncRef));
1168 hasArgEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001169 }
1170 else if ((*I)->getAttr<ObjCOwnershipReleaseAttr>()) {
1171 ScratchArgs.push_back(std::make_pair(i, DecRefMsg));
1172 hasArgEffect = true;
1173 }
1174 else if ((*I)->getAttr<ObjCOwnershipCFReleaseAttr>()) {
1175 ScratchArgs.push_back(std::make_pair(i, DecRef));
1176 hasArgEffect = true;
1177 }
Ted Kremenekff8648d2009-04-28 22:32:26 +00001178 else if ((*I)->getAttr<ObjCOwnershipMakeCollectableAttr>()) {
1179 ScratchArgs.push_back(std::make_pair(i, MakeCollectable));
1180 hasArgEffect = true;
1181 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001182 }
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001183
1184 if (!hasRetEffect && !hasArgEffect)
Ted Kremenek923fc392009-04-24 23:32:32 +00001185 return 0;
1186
1187 return getPersistentSummary(RE);
1188}
Ted Kremenek272aa852008-06-25 21:21:56 +00001189
Ted Kremenekbcaff792008-05-06 15:44:25 +00001190RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001191RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1192 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001193
Ted Kremenek578498a2009-04-29 00:42:39 +00001194 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001195 // Scan the method decl for 'void*' arguments. These should be treated
1196 // as 'StopTracking' because they are often used with delegates.
1197 // Delegates are a frequent form of false positives with the retain
1198 // count checker.
1199 unsigned i = 0;
1200 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1201 E = MD->param_end(); I != E; ++I, ++i)
1202 if (ParmVarDecl *PD = *I) {
1203 QualType Ty = Ctx.getCanonicalType(PD->getType());
1204 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
1205 ScratchArgs.push_back(std::make_pair(i, StopTracking));
1206 }
1207 }
1208
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001209 // Any special effect for the receiver?
1210 ArgEffect ReceiverEff = DoNothing;
1211
1212 // If one of the arguments in the selector has the keyword 'delegate' we
1213 // should stop tracking the reference count for the receiver. This is
1214 // because the reference count is quite possibly handled by a delegate
1215 // method.
1216 if (S.isKeywordSelector()) {
1217 const std::string &str = S.getAsString();
1218 assert(!str.empty());
1219 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1220 }
1221
Ted Kremenek174a0772009-04-23 23:08:22 +00001222 // Look for methods that return an owned object.
Ted Kremenek578498a2009-04-29 00:42:39 +00001223 if (!isTrackedObjectType(RetTy)) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001224 if (ScratchArgs.empty() && ReceiverEff == DoNothing)
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001225 return 0;
1226
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001227 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1228 MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001229 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001230
1231 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1232 // by instance methods.
1233
1234 RetEffect E =
Ted Kremenekaca0b452009-04-24 18:19:07 +00001235 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001236 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek174a0772009-04-23 23:08:22 +00001237 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1238 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1239
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001240 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001241}
1242
1243RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001244RetainSummaryManager::getInstanceMethodSummary(Selector S,
1245 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001246 const ObjCInterfaceDecl* ID,
1247 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001248 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001249
Ted Kremeneka821b792009-04-29 05:04:30 +00001250 // Look up a summary in our summary cache.
1251 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001252
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001253 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001254 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001255
Ted Kremenek174a0772009-04-23 23:08:22 +00001256 assert(ScratchArgs.empty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001257
1258 // Annotations take precedence over all other ways to derive
1259 // summaries.
Ted Kremeneka821b792009-04-29 05:04:30 +00001260 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001261
Ted Kremenek923fc392009-04-24 23:32:32 +00001262 if (!Summ) {
1263 // "initXXX": pass-through for receiver.
1264 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1265 == InitRule)
Ted Kremeneka821b792009-04-29 05:04:30 +00001266 Summ = getInitMethodSummary(RetTy);
1267 else
1268 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001269 }
1270
Ted Kremeneka821b792009-04-29 05:04:30 +00001271 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001272 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001273}
1274
Ted Kremeneka7722b72008-05-06 21:26:51 +00001275RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001276RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001277 const ObjCInterfaceDecl *ID,
1278 const ObjCMethodDecl *MD,
1279 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001280
Ted Kremenek578498a2009-04-29 00:42:39 +00001281 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001282 ObjCMethodSummariesTy::iterator I =
1283 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001284
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001285 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001286 return I->second;
1287
Ted Kremenek923fc392009-04-24 23:32:32 +00001288 // Annotations take precedence over all other ways to derive
1289 // summaries.
Ted Kremenek578498a2009-04-29 00:42:39 +00001290 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001291
1292 if (!Summ)
Ted Kremenek578498a2009-04-29 00:42:39 +00001293 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001294
Ted Kremenek578498a2009-04-29 00:42:39 +00001295 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001296 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001297}
1298
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001299void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001300
1301 assert (ScratchArgs.empty());
1302
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001303 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001304 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001305
Ted Kremenek0e344d42008-05-06 00:30:21 +00001306 RetainSummary* Summ = getPersistentSummary(E);
1307
Ted Kremenek272aa852008-06-25 21:21:56 +00001308 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1309 // NSObject and its derivatives.
1310 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1311 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1312 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001313
1314 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001315 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001316 GetNullarySelector("currentHandler", Ctx),
1317 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001318
1319 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001320 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1321 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1322 GetUnarySelector("addObject", Ctx),
1323 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001324 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001325
1326 // Create the summaries for [NSObject performSelector...]. We treat
1327 // these as 'stop tracking' for the arguments because they are often
1328 // used for delegates that can release the object. When we have better
1329 // inter-procedural analysis we can potentially do something better. This
1330 // workaround is to remove false positives.
1331 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1332 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1333 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1334 "afterDelay", NULL);
1335 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1336 "afterDelay", "inModes", NULL);
1337 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1338 "withObject", "waitUntilDone", NULL);
1339 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1340 "withObject", "waitUntilDone", "modes", NULL);
1341 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1342 "withObject", "waitUntilDone", NULL);
1343 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1344 "withObject", "waitUntilDone", "modes", NULL);
1345 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1346 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001347}
1348
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001349void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001350
1351 assert (ScratchArgs.empty());
1352
Ted Kremeneka7722b72008-05-06 21:26:51 +00001353 // Create the "init" selector. It just acts as a pass-through for the
1354 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001355 RetainSummary* InitSumm =
1356 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001357 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001358
1359 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001360 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001361 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001362
Ted Kremeneke44927e2008-07-01 17:21:27 +00001363 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001364
1365 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001366 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1367
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001368 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001369 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001370
Ted Kremenek266d8b62008-05-06 02:26:56 +00001371 // Create the "retain" selector.
1372 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001373 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001374 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001375
1376 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001377 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001378 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001379
1380 // Create the "drain" selector.
1381 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001382 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001383
1384 // Create the -dealloc summary.
1385 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1386 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001387
1388 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001389 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001390 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001391
Ted Kremenekaac82832009-02-23 17:45:03 +00001392 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001393 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001394 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001395 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001396
Ted Kremenek45642a42008-08-12 18:48:50 +00001397 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001398 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1399 // self-own themselves. However, they only do this once they are displayed.
1400 // Thus, we need to track an NSWindow's display status.
1401 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001402 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001403 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1404
1405 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1406
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001407
1408#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001409 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001410 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001411
1412 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1413 "styleMask", "backing", "defer", NULL);
1414
1415 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1416 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001417#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001418
1419 // For NSPanel (which subclasses NSWindow), allocated objects are not
1420 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001421 // FIXME: For now we don't track NSPanels. object for the same reason
1422 // as for NSWindow objects.
1423 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1424
Ted Kremenek45642a42008-08-12 18:48:50 +00001425 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1426 "styleMask", "backing", "defer", NULL);
1427
1428 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1429 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001430
Ted Kremenekf2717b02008-07-18 17:24:20 +00001431 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001432 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1433 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001434
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001435 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1436 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001437}
1438
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001439//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001440// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001441//===----------------------------------------------------------------------===//
1442
Ted Kremeneka7338b42008-03-11 06:39:11 +00001443namespace {
1444
Ted Kremenek7d421f32008-04-09 23:49:11 +00001445class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001446public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001447 enum Kind {
1448 Owned = 0, // Owning reference.
1449 NotOwned, // Reference is not owned by still valid (not freed).
1450 Released, // Object has been released.
1451 ReturnedOwned, // Returned object passes ownership to caller.
1452 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001453 ERROR_START,
1454 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1455 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001456 ErrorUseAfterRelease, // Object used after released.
1457 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001458 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001459 ErrorLeak, // A memory leak due to excessive reference counts.
1460 ErrorLeakReturned // A memory leak due to the returning method not having
1461 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001462 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001463
1464private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001465 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001466 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001467 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001468 QualType T;
1469
Ted Kremenek68621b92009-01-28 05:56:51 +00001470 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1471 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001472
Ted Kremenek68621b92009-01-28 05:56:51 +00001473 RefVal(Kind k, unsigned cnt = 0)
1474 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1475
1476public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001477 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001478
1479 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001480
Ted Kremenek6537a642009-03-17 19:42:23 +00001481 unsigned getCount() const { return Cnt; }
1482 void clearCounts() { Cnt = 0; }
1483
Ted Kremenek272aa852008-06-25 21:21:56 +00001484 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001485
1486 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001487
Ted Kremenek6537a642009-03-17 19:42:23 +00001488 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001489
Ted Kremenek6537a642009-03-17 19:42:23 +00001490 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001491
Ted Kremenekffefc352008-04-11 22:25:11 +00001492 bool isOwned() const {
1493 return getKind() == Owned;
1494 }
1495
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001496 bool isNotOwned() const {
1497 return getKind() == NotOwned;
1498 }
1499
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001500 bool isReturnedOwned() const {
1501 return getKind() == ReturnedOwned;
1502 }
1503
1504 bool isReturnedNotOwned() const {
1505 return getKind() == ReturnedNotOwned;
1506 }
1507
1508 bool isNonLeakError() const {
1509 Kind k = getKind();
1510 return isError(k) && !isLeak(k);
1511 }
1512
Ted Kremenek68621b92009-01-28 05:56:51 +00001513 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1514 unsigned Count = 1) {
1515 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001516 }
1517
Ted Kremenek68621b92009-01-28 05:56:51 +00001518 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1519 unsigned Count = 0) {
1520 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001521 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001522
1523 static RefVal makeReturnedOwned(unsigned Count) {
1524 return RefVal(ReturnedOwned, Count);
1525 }
1526
1527 static RefVal makeReturnedNotOwned() {
1528 return RefVal(ReturnedNotOwned);
1529 }
1530
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001531 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001532
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001533 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001534 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001535 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001536
Ted Kremenek272aa852008-06-25 21:21:56 +00001537 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001538 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001539 }
1540
1541 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001542 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001543 }
1544
1545 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001546 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001547 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001548
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001549 void Profile(llvm::FoldingSetNodeID& ID) const {
1550 ID.AddInteger((unsigned) kind);
1551 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001552 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001553 }
1554
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001555 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001556};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001557
1558void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001559 if (!T.isNull())
1560 Out << "Tracked Type:" << T.getAsString() << '\n';
1561
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001562 switch (getKind()) {
1563 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001564 case Owned: {
1565 Out << "Owned";
1566 unsigned cnt = getCount();
1567 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001568 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001569 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001570
Ted Kremenekc4f81022008-04-10 23:09:18 +00001571 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001572 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001573 unsigned cnt = getCount();
1574 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001575 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001576 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001577
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001578 case ReturnedOwned: {
1579 Out << "ReturnedOwned";
1580 unsigned cnt = getCount();
1581 if (cnt) Out << " (+ " << cnt << ")";
1582 break;
1583 }
1584
1585 case ReturnedNotOwned: {
1586 Out << "ReturnedNotOwned";
1587 unsigned cnt = getCount();
1588 if (cnt) Out << " (+ " << cnt << ")";
1589 break;
1590 }
1591
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001592 case Released:
1593 Out << "Released";
1594 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001595
1596 case ErrorDeallocGC:
1597 Out << "-dealloc (GC)";
1598 break;
1599
1600 case ErrorDeallocNotOwned:
1601 Out << "-dealloc (not-owned)";
1602 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001603
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001604 case ErrorLeak:
1605 Out << "Leaked";
1606 break;
1607
Ted Kremenek311f3d42008-10-22 23:56:21 +00001608 case ErrorLeakReturned:
1609 Out << "Leaked (Bad naming)";
1610 break;
1611
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001612 case ErrorUseAfterRelease:
1613 Out << "Use-After-Release [ERROR]";
1614 break;
1615
1616 case ErrorReleaseNotOwned:
1617 Out << "Release of Not-Owned [ERROR]";
1618 break;
1619 }
1620}
Ted Kremenek0d721572008-03-11 17:48:22 +00001621
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001622} // end anonymous namespace
1623
1624//===----------------------------------------------------------------------===//
1625// RefBindings - State used to track object reference counts.
1626//===----------------------------------------------------------------------===//
1627
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001628typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001629static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001630static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001631
1632namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001633 template<>
1634 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1635 static inline void* GDMIndex() { return &RefBIndex; }
1636 };
1637}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001638
1639//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001640// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001641//===----------------------------------------------------------------------===//
1642
Ted Kremenekb6578942009-02-24 19:15:11 +00001643typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1644typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1645typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001646
Ted Kremenekb6578942009-02-24 19:15:11 +00001647static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001648static int AutoRBIndex = 0;
1649
Ted Kremenekb6578942009-02-24 19:15:11 +00001650namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001651namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001652
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001653namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001654template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001655 : public GRStatePartialTrait<ARStack> {
1656 static inline void* GDMIndex() { return &AutoRBIndex; }
1657};
1658
1659template<> struct GRStateTrait<AutoreleasePoolContents>
1660 : public GRStatePartialTrait<ARPoolContents> {
1661 static inline void* GDMIndex() { return &AutoRCIndex; }
1662};
1663} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001664
Ted Kremenek681fb352009-03-20 17:34:15 +00001665static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1666 ARStack stack = state->get<AutoreleaseStack>();
1667 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1668}
1669
1670static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1671 SymbolRef sym) {
1672
1673 SymbolRef pool = GetCurrentAutoreleasePool(state);
1674 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1675 ARCounts newCnts(0);
1676
1677 if (cnts) {
1678 const unsigned *cnt = (*cnts).lookup(sym);
1679 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1680 }
1681 else
1682 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1683
1684 return state.set<AutoreleasePoolContents>(pool, newCnts);
1685}
1686
Ted Kremenek7aef4842008-04-16 20:40:59 +00001687//===----------------------------------------------------------------------===//
1688// Transfer functions.
1689//===----------------------------------------------------------------------===//
1690
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001691namespace {
1692
Ted Kremenek7d421f32008-04-09 23:49:11 +00001693class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001694public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001695 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001696 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001697 virtual void Print(std::ostream& Out, const GRState* state,
1698 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001699 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001700
1701private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001702 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1703 SummaryLogTy;
1704
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001705 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001706 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001707 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001708 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001709
Ted Kremenek708af042009-02-05 06:50:21 +00001710 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001711 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001712 BugType *leakWithinFunction, *leakAtReturn;
1713 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001714
Ted Kremenekb6578942009-02-24 19:15:11 +00001715 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1716 RefVal::Kind& hasErr);
1717
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001718 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1719 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001720 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001721 ExplodedNode<GRState>* Pred,
1722 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001723 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001724
Ted Kremenek0106e202008-10-24 20:32:50 +00001725 std::pair<GRStateRef, bool>
1726 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001727 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001728
Ted Kremenekb6578942009-02-24 19:15:11 +00001729public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001730 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001731 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001732 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1733 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001734 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001735
Ted Kremenek708af042009-02-05 06:50:21 +00001736 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001737
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001738 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001739
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001740 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1741 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001742 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001743
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001744 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001745 const LangOptions& getLangOptions() const { return LOpts; }
1746
Ted Kremenekc26c4692009-02-18 03:48:14 +00001747 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1748 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1749 return I == SummaryLog.end() ? 0 : I->second;
1750 }
1751
Ted Kremeneka7338b42008-03-11 06:39:11 +00001752 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001753
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001754 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001755 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001756 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001757 Expr* Ex,
1758 Expr* Receiver,
1759 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001760 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001761 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001762
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001763 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001764 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001765 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001766 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001767 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001768
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001769
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001770 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001771 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001772 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001773 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001774 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001775
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001776 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001777 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001778 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001779 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001780 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001781
Ted Kremeneka42be302009-02-14 01:43:44 +00001782 // Stores.
1783 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1784
Ted Kremenekffefc352008-04-11 22:25:11 +00001785 // End-of-path.
1786
1787 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001788 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001789
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001790 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001791 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001792 GRStmtNodeBuilder<GRState>& Builder,
1793 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001794 Stmt* S, const GRState* state,
1795 SymbolReaper& SymReaper);
1796
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001797 // Return statements.
1798
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001799 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001800 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001801 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001802 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001803 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001804
1805 // Assumptions.
1806
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001807 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001808 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001809 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001810};
1811
1812} // end anonymous namespace
1813
Ted Kremenek681fb352009-03-20 17:34:15 +00001814static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1815 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001816 if (Sym)
1817 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001818 else
1819 Out << "<pool>";
1820 Out << ":{";
1821
1822 // Get the contents of the pool.
1823 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1824 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1825 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1826
1827 Out << '}';
1828}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001829
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001830void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1831 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001832
1833
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001834
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001835 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001836
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001837 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001838 Out << sep << nl;
1839
1840 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1841 Out << (*I).first << " : ";
1842 (*I).second.print(Out);
1843 Out << nl;
1844 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001845
1846 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001847 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001848 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001849
Ted Kremenek681fb352009-03-20 17:34:15 +00001850 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1851 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1852 PrintPool(Out, *I, state);
1853
1854 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001855}
1856
Ted Kremenek47a72422009-04-29 18:50:19 +00001857//===----------------------------------------------------------------------===//
1858// Error reporting.
1859//===----------------------------------------------------------------------===//
1860
1861namespace {
1862
1863 //===-------------===//
1864 // Bug Descriptions. //
1865 //===-------------===//
1866
1867 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1868 protected:
1869 CFRefCount& TF;
1870
1871 CFRefBug(CFRefCount* tf, const char* name)
1872 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1873 public:
1874
1875 CFRefCount& getTF() { return TF; }
1876 const CFRefCount& getTF() const { return TF; }
1877
1878 // FIXME: Eventually remove.
1879 virtual const char* getDescription() const = 0;
1880
1881 virtual bool isLeak() const { return false; }
1882 };
1883
1884 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1885 public:
1886 UseAfterRelease(CFRefCount* tf)
1887 : CFRefBug(tf, "Use-after-release") {}
1888
1889 const char* getDescription() const {
1890 return "Reference-counted object is used after it is released";
1891 }
1892 };
1893
1894 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1895 public:
1896 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1897
1898 const char* getDescription() const {
1899 return "Incorrect decrement of the reference count of an "
1900 "object is not owned at this point by the caller";
1901 }
1902 };
1903
1904 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1905 public:
1906 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1907 "-dealloc called while using GC") {}
1908
1909 const char *getDescription() const {
1910 return "-dealloc called while using GC";
1911 }
1912 };
1913
1914 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1915 public:
1916 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1917 "-dealloc sent to non-exclusively owned object") {}
1918
1919 const char *getDescription() const {
1920 return "-dealloc sent to object that may be referenced elsewhere";
1921 }
1922 };
1923
1924 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1925 const bool isReturn;
1926 protected:
1927 Leak(CFRefCount* tf, const char* name, bool isRet)
1928 : CFRefBug(tf, name), isReturn(isRet) {}
1929 public:
1930
1931 const char* getDescription() const { return ""; }
1932
1933 bool isLeak() const { return true; }
1934 };
1935
1936 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1937 public:
1938 LeakAtReturn(CFRefCount* tf, const char* name)
1939 : Leak(tf, name, true) {}
1940 };
1941
1942 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1943 public:
1944 LeakWithinFunction(CFRefCount* tf, const char* name)
1945 : Leak(tf, name, false) {}
1946 };
1947
1948 //===---------===//
1949 // Bug Reports. //
1950 //===---------===//
1951
1952 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1953 protected:
1954 SymbolRef Sym;
1955 const CFRefCount &TF;
1956 public:
1957 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1958 ExplodedNode<GRState> *n, SymbolRef sym)
1959 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1960
1961 virtual ~CFRefReport() {}
1962
1963 CFRefBug& getBugType() {
1964 return (CFRefBug&) RangedBugReport::getBugType();
1965 }
1966 const CFRefBug& getBugType() const {
1967 return (const CFRefBug&) RangedBugReport::getBugType();
1968 }
1969
1970 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1971 const SourceRange*& end) {
1972
1973 if (!getBugType().isLeak())
1974 RangedBugReport::getRanges(BR, beg, end);
1975 else
1976 beg = end = 0;
1977 }
1978
1979 SymbolRef getSymbol() const { return Sym; }
1980
1981 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1982 const ExplodedNode<GRState>* N);
1983
1984 std::pair<const char**,const char**> getExtraDescriptiveText();
1985
1986 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1987 const ExplodedNode<GRState>* PrevN,
1988 const ExplodedGraph<GRState>& G,
1989 BugReporter& BR,
1990 NodeResolver& NR);
1991 };
1992
1993 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1994 SourceLocation AllocSite;
1995 const MemRegion* AllocBinding;
1996 public:
1997 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1998 ExplodedNode<GRState> *n, SymbolRef sym,
1999 GRExprEngine& Eng);
2000
2001 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2002 const ExplodedNode<GRState>* N);
2003
2004 SourceLocation getLocation() const { return AllocSite; }
2005 };
2006} // end anonymous namespace
2007
2008void CFRefCount::RegisterChecks(BugReporter& BR) {
2009 useAfterRelease = new UseAfterRelease(this);
2010 BR.Register(useAfterRelease);
2011
2012 releaseNotOwned = new BadRelease(this);
2013 BR.Register(releaseNotOwned);
2014
2015 deallocGC = new DeallocGC(this);
2016 BR.Register(deallocGC);
2017
2018 deallocNotOwned = new DeallocNotOwned(this);
2019 BR.Register(deallocNotOwned);
2020
2021 // First register "return" leaks.
2022 const char* name = 0;
2023
2024 if (isGCEnabled())
2025 name = "Leak of returned object when using garbage collection";
2026 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2027 name = "Leak of returned object when not using garbage collection (GC) in "
2028 "dual GC/non-GC code";
2029 else {
2030 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2031 name = "Leak of returned object";
2032 }
2033
2034 leakAtReturn = new LeakAtReturn(this, name);
2035 BR.Register(leakAtReturn);
2036
2037 // Second, register leaks within a function/method.
2038 if (isGCEnabled())
2039 name = "Leak of object when using garbage collection";
2040 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2041 name = "Leak of object when not using garbage collection (GC) in "
2042 "dual GC/non-GC code";
2043 else {
2044 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2045 name = "Leak";
2046 }
2047
2048 leakWithinFunction = new LeakWithinFunction(this, name);
2049 BR.Register(leakWithinFunction);
2050
2051 // Save the reference to the BugReporter.
2052 this->BR = &BR;
2053}
2054
2055static const char* Msgs[] = {
2056 // GC only
2057 "Code is compiled to only use garbage collection",
2058 // No GC.
2059 "Code is compiled to use reference counts",
2060 // Hybrid, with GC.
2061 "Code is compiled to use either garbage collection (GC) or reference counts"
2062 " (non-GC). The bug occurs with GC enabled",
2063 // Hybrid, without GC
2064 "Code is compiled to use either garbage collection (GC) or reference counts"
2065 " (non-GC). The bug occurs in non-GC mode"
2066};
2067
2068std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2069 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2070
2071 switch (TF.getLangOptions().getGCMode()) {
2072 default:
2073 assert(false);
2074
2075 case LangOptions::GCOnly:
2076 assert (TF.isGCEnabled());
2077 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2078
2079 case LangOptions::NonGC:
2080 assert (!TF.isGCEnabled());
2081 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2082
2083 case LangOptions::HybridGC:
2084 if (TF.isGCEnabled())
2085 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2086 else
2087 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2088 }
2089}
2090
2091static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2092 ArgEffect X) {
2093 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2094 I!=E; ++I)
2095 if (*I == X) return true;
2096
2097 return false;
2098}
2099
2100PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2101 const ExplodedNode<GRState>* PrevN,
2102 const ExplodedGraph<GRState>& G,
2103 BugReporter& BR,
2104 NodeResolver& NR) {
2105
2106 // Check if the type state has changed.
2107 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2108 GRStateRef PrevSt(PrevN->getState(), StMgr);
2109 GRStateRef CurrSt(N->getState(), StMgr);
2110
2111 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2112 if (!CurrT) return NULL;
2113
2114 const RefVal& CurrV = *CurrT;
2115 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2116
2117 // Create a string buffer to constain all the useful things we want
2118 // to tell the user.
2119 std::string sbuf;
2120 llvm::raw_string_ostream os(sbuf);
2121
2122 // This is the allocation site since the previous node had no bindings
2123 // for this symbol.
2124 if (!PrevT) {
2125 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2126
2127 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2128 // Get the name of the callee (if it is available).
2129 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2130 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2131 os << "Call to function '" << FD->getNameAsString() <<'\'';
2132 else
2133 os << "function call";
2134 }
2135 else {
2136 assert (isa<ObjCMessageExpr>(S));
2137 os << "Method";
2138 }
2139
2140 if (CurrV.getObjKind() == RetEffect::CF) {
2141 os << " returns a Core Foundation object with a ";
2142 }
2143 else {
2144 assert (CurrV.getObjKind() == RetEffect::ObjC);
2145 os << " returns an Objective-C object with a ";
2146 }
2147
2148 if (CurrV.isOwned()) {
2149 os << "+1 retain count (owning reference).";
2150
2151 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2152 assert(CurrV.getObjKind() == RetEffect::CF);
2153 os << " "
2154 "Core Foundation objects are not automatically garbage collected.";
2155 }
2156 }
2157 else {
2158 assert (CurrV.isNotOwned());
2159 os << "+0 retain count (non-owning reference).";
2160 }
2161
2162 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2163 return new PathDiagnosticEventPiece(Pos, os.str());
2164 }
2165
2166 // Gather up the effects that were performed on the object at this
2167 // program point
2168 llvm::SmallVector<ArgEffect, 2> AEffects;
2169
2170 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2171 // We only have summaries attached to nodes after evaluating CallExpr and
2172 // ObjCMessageExprs.
2173 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2174
2175 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2176 // Iterate through the parameter expressions and see if the symbol
2177 // was ever passed as an argument.
2178 unsigned i = 0;
2179
2180 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2181 AI!=AE; ++AI, ++i) {
2182
2183 // Retrieve the value of the argument. Is it the symbol
2184 // we are interested in?
2185 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2186 continue;
2187
2188 // We have an argument. Get the effect!
2189 AEffects.push_back(Summ->getArg(i));
2190 }
2191 }
2192 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2193 if (Expr *receiver = ME->getReceiver())
2194 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2195 // The symbol we are tracking is the receiver.
2196 AEffects.push_back(Summ->getReceiverEffect());
2197 }
2198 }
2199 }
2200
2201 do {
2202 // Get the previous type state.
2203 RefVal PrevV = *PrevT;
2204
2205 // Specially handle -dealloc.
2206 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2207 // Determine if the object's reference count was pushed to zero.
2208 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2209 // We may not have transitioned to 'release' if we hit an error.
2210 // This case is handled elsewhere.
2211 if (CurrV.getKind() == RefVal::Released) {
2212 assert(CurrV.getCount() == 0);
2213 os << "Object released by directly sending the '-dealloc' message";
2214 break;
2215 }
2216 }
2217
2218 // Specially handle CFMakeCollectable and friends.
2219 if (contains(AEffects, MakeCollectable)) {
2220 // Get the name of the function.
2221 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2222 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2223 const FunctionDecl* FD = X.getAsFunctionDecl();
2224 const std::string& FName = FD->getNameAsString();
2225
2226 if (TF.isGCEnabled()) {
2227 // Determine if the object's reference count was pushed to zero.
2228 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2229
2230 os << "In GC mode a call to '" << FName
2231 << "' decrements an object's retain count and registers the "
2232 "object with the garbage collector. ";
2233
2234 if (CurrV.getKind() == RefVal::Released) {
2235 assert(CurrV.getCount() == 0);
2236 os << "Since it now has a 0 retain count the object can be "
2237 "automatically collected by the garbage collector.";
2238 }
2239 else
2240 os << "An object must have a 0 retain count to be garbage collected. "
2241 "After this call its retain count is +" << CurrV.getCount()
2242 << '.';
2243 }
2244 else
2245 os << "When GC is not enabled a call to '" << FName
2246 << "' has no effect on its argument.";
2247
2248 // Nothing more to say.
2249 break;
2250 }
2251
2252 // Determine if the typestate has changed.
2253 if (!(PrevV == CurrV))
2254 switch (CurrV.getKind()) {
2255 case RefVal::Owned:
2256 case RefVal::NotOwned:
2257
2258 if (PrevV.getCount() == CurrV.getCount())
2259 return 0;
2260
2261 if (PrevV.getCount() > CurrV.getCount())
2262 os << "Reference count decremented.";
2263 else
2264 os << "Reference count incremented.";
2265
2266 if (unsigned Count = CurrV.getCount())
2267 os << " The object now has a +" << Count << " retain count.";
2268
2269 if (PrevV.getKind() == RefVal::Released) {
2270 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2271 os << " The object is not eligible for garbage collection until the "
2272 "retain count reaches 0 again.";
2273 }
2274
2275 break;
2276
2277 case RefVal::Released:
2278 os << "Object released.";
2279 break;
2280
2281 case RefVal::ReturnedOwned:
2282 os << "Object returned to caller as an owning reference (single retain "
2283 "count transferred to caller).";
2284 break;
2285
2286 case RefVal::ReturnedNotOwned:
2287 os << "Object returned to caller with a +0 (non-owning) retain count.";
2288 break;
2289
2290 default:
2291 return NULL;
2292 }
2293
2294 // Emit any remaining diagnostics for the argument effects (if any).
2295 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2296 E=AEffects.end(); I != E; ++I) {
2297
2298 // A bunch of things have alternate behavior under GC.
2299 if (TF.isGCEnabled())
2300 switch (*I) {
2301 default: break;
2302 case Autorelease:
2303 os << "In GC mode an 'autorelease' has no effect.";
2304 continue;
2305 case IncRefMsg:
2306 os << "In GC mode the 'retain' message has no effect.";
2307 continue;
2308 case DecRefMsg:
2309 os << "In GC mode the 'release' message has no effect.";
2310 continue;
2311 }
2312 }
2313 } while(0);
2314
2315 if (os.str().empty())
2316 return 0; // We have nothing to say!
2317
2318 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2319 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2320 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2321
2322 // Add the range by scanning the children of the statement for any bindings
2323 // to Sym.
2324 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2325 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2326 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2327 P->addRange(Exp->getSourceRange());
2328 break;
2329 }
2330
2331 return P;
2332}
2333
2334namespace {
2335 class VISIBILITY_HIDDEN FindUniqueBinding :
2336 public StoreManager::BindingsHandler {
2337 SymbolRef Sym;
2338 const MemRegion* Binding;
2339 bool First;
2340
2341 public:
2342 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2343
2344 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2345 SVal val) {
2346
2347 SymbolRef SymV = val.getAsSymbol();
2348 if (!SymV || SymV != Sym)
2349 return true;
2350
2351 if (Binding) {
2352 First = false;
2353 return false;
2354 }
2355 else
2356 Binding = R;
2357
2358 return true;
2359 }
2360
2361 operator bool() { return First && Binding; }
2362 const MemRegion* getRegion() { return Binding; }
2363 };
2364}
2365
2366static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2367GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2368 SymbolRef Sym) {
2369
2370 // Find both first node that referred to the tracked symbol and the
2371 // memory location that value was store to.
2372 const ExplodedNode<GRState>* Last = N;
2373 const MemRegion* FirstBinding = 0;
2374
2375 while (N) {
2376 const GRState* St = N->getState();
2377 RefBindings B = St->get<RefBindings>();
2378
2379 if (!B.lookup(Sym))
2380 break;
2381
2382 FindUniqueBinding FB(Sym);
2383 StateMgr.iterBindings(St, FB);
2384 if (FB) FirstBinding = FB.getRegion();
2385
2386 Last = N;
2387 N = N->pred_empty() ? NULL : *(N->pred_begin());
2388 }
2389
2390 return std::make_pair(Last, FirstBinding);
2391}
2392
2393PathDiagnosticPiece*
2394CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
2395 // Tell the BugReporter to report cases when the tracked symbol is
2396 // assigned to different variables, etc.
2397 GRBugReporter& BR = cast<GRBugReporter>(br);
2398 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2399 return RangedBugReport::getEndPath(BR, EndN);
2400}
2401
2402PathDiagnosticPiece*
2403CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2404
2405 GRBugReporter& BR = cast<GRBugReporter>(br);
2406 // Tell the BugReporter to report cases when the tracked symbol is
2407 // assigned to different variables, etc.
2408 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2409
2410 // We are reporting a leak. Walk up the graph to get to the first node where
2411 // the symbol appeared, and also get the first VarDecl that tracked object
2412 // is stored to.
2413 const ExplodedNode<GRState>* AllocNode = 0;
2414 const MemRegion* FirstBinding = 0;
2415
2416 llvm::tie(AllocNode, FirstBinding) =
2417 GetAllocationSite(BR.getStateManager(), EndN, Sym);
2418
2419 // Get the allocate site.
2420 assert(AllocNode);
2421 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2422
2423 SourceManager& SMgr = BR.getContext().getSourceManager();
2424 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2425
2426 // Compute an actual location for the leak. Sometimes a leak doesn't
2427 // occur at an actual statement (e.g., transition between blocks; end
2428 // of function) so we need to walk the graph and compute a real location.
2429 const ExplodedNode<GRState>* LeakN = EndN;
2430 PathDiagnosticLocation L;
2431
2432 while (LeakN) {
2433 ProgramPoint P = LeakN->getLocation();
2434
2435 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2436 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2437 break;
2438 }
2439 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2440 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2441 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2442 break;
2443 }
2444 }
2445
2446 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2447 }
2448
2449 if (!L.isValid()) {
Ted Kremenek0a6913d2009-04-29 21:31:59 +00002450 const Decl &D = BR.getStateManager().getCodeDecl();
2451 L = PathDiagnosticLocation(D.getBodyRBrace(BR.getContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002452 }
2453
2454 std::string sbuf;
2455 llvm::raw_string_ostream os(sbuf);
2456
2457 os << "Object allocated on line " << AllocLine;
2458
2459 if (FirstBinding)
2460 os << " and stored into '" << FirstBinding->getString() << '\'';
2461
2462 // Get the retain count.
2463 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2464
2465 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2466 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2467 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2468 // to the caller for NS objects.
2469 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2470 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002471 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002472 << "') does not contain 'copy' or otherwise starts with"
2473 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002474 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002475 }
2476 else
2477 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002478 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002479
2480 return new PathDiagnosticEventPiece(L, os.str());
2481}
2482
2483
2484CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2485 ExplodedNode<GRState> *n,
2486 SymbolRef sym, GRExprEngine& Eng)
2487: CFRefReport(D, tf, n, sym)
2488{
2489
2490 // Most bug reports are cached at the location where they occured.
2491 // With leaks, we want to unique them by the location where they were
2492 // allocated, and only report a single path. To do this, we need to find
2493 // the allocation site of a piece of tracked memory, which we do via a
2494 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2495 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2496 // that all ancestor nodes that represent the allocation site have the
2497 // same SourceLocation.
2498 const ExplodedNode<GRState>* AllocNode = 0;
2499
2500 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2501 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2502
2503 // Get the SourceLocation for the allocation site.
2504 ProgramPoint P = AllocNode->getLocation();
2505 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2506
2507 // Fill in the description of the bug.
2508 Description.clear();
2509 llvm::raw_string_ostream os(Description);
2510 SourceManager& SMgr = Eng.getContext().getSourceManager();
2511 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
2512 os << "Potential leak of object allocated on line " << AllocLine;
2513
2514 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2515 if (AllocBinding)
2516 os << " and stored into '" << AllocBinding->getString() << '\'';
2517}
2518
2519//===----------------------------------------------------------------------===//
2520// Main checker logic.
2521//===----------------------------------------------------------------------===//
2522
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002523static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002524 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00002525}
2526
Ted Kremenek266d8b62008-05-06 02:26:56 +00002527static inline RetEffect GetRetEffect(RetainSummary* Summ) {
2528 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00002529}
2530
Ted Kremenek227c5372008-05-06 02:41:27 +00002531static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
2532 return Summ ? Summ->getReceiverEffect() : DoNothing;
2533}
2534
Ted Kremenekf2717b02008-07-18 17:24:20 +00002535static inline bool IsEndPath(RetainSummary* Summ) {
2536 return Summ ? Summ->isEndPath() : false;
2537}
2538
Ted Kremenek1feab292008-04-16 04:28:53 +00002539
Ted Kremenek272aa852008-06-25 21:21:56 +00002540/// GetReturnType - Used to get the return type of a message expression or
2541/// function call with the intention of affixing that type to a tracked symbol.
2542/// While the the return type can be queried directly from RetEx, when
2543/// invoking class methods we augment to the return type to be that of
2544/// a pointer to the class (as opposed it just being id).
2545static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2546
2547 QualType RetTy = RetE->getType();
2548
2549 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002550 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002551 if (!PT)
2552 return RetTy;
2553
2554 // If RetEx is not a message expression just return its type.
2555 // If RetEx is a message expression, return its types if it is something
2556 /// more specific than id.
2557
2558 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2559
Steve Naroff17c03822009-02-12 17:52:19 +00002560 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002561 return RetTy;
2562
2563 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2564
2565 // At this point we know the return type of the message expression is id.
2566 // If we have an ObjCInterceDecl, we know this is a call to a class method
2567 // whose type we can resolve. In such cases, promote the return type to
2568 // Class*.
2569 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2570}
2571
2572
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002573void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002574 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002575 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002576 Expr* Ex,
2577 Expr* Receiver,
2578 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002579 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002580 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002581
Ted Kremeneka7338b42008-03-11 06:39:11 +00002582 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002583 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002584 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002585
2586 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002587 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002588 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002589 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002590 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002591
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002592 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002593 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002594 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002595
Ted Kremenek74556a12009-03-26 03:35:11 +00002596 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002597 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
2598 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
2599 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002600 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002601 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002602 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002603 }
2604 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002605 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002606
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002607 if (isa<Loc>(V)) {
2608 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00002609 if (GetArgE(Summ, idx) == DoNothingByRef)
2610 continue;
2611
2612 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002613
2614 // FIXME: Either this logic should also be replicated in GRSimpleVals
2615 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002616
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002617 // FIXME: We can have collisions on the conjured symbol if the
2618 // expression *I also creates conjured symbols. We probably want
2619 // to identify conjured symbols by an expression pair: the enclosing
2620 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002621 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002622
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002623 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002624
Ted Kremenek53b24182009-03-04 22:56:43 +00002625 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002626 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002627 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002628
Ted Kremenek53b24182009-03-04 22:56:43 +00002629 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002630 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002631
Ted Kremenek53b24182009-03-04 22:56:43 +00002632 if (R->isBoundable(Ctx)) {
2633 // Set the value of the variable to be a conjured symbol.
2634 unsigned Count = Builder.getCurrentBlockCount();
2635 QualType T = R->getRValueType(Ctx);
2636
Zhongxing Xu079dc352009-04-09 06:03:54 +00002637 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002638 ValueManager &ValMgr = Eng.getValueManager();
2639 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002640 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002641 }
2642 else if (const RecordType *RT = T->getAsStructureType()) {
2643 // Handle structs in a not so awesome way. Here we just
2644 // eagerly bind new symbols to the fields. In reality we
2645 // should have the store manager handle this. The idea is just
2646 // to prototype some basic functionality here. All of this logic
2647 // should one day soon just go away.
2648 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2649
2650 // No record definition. There is nothing we can do.
2651 if (!RD)
2652 continue;
2653
2654 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2655
2656 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002657 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2658 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002659
2660 // For now just handle scalar fields.
2661 FieldDecl *FD = *FI;
2662 QualType FT = FD->getType();
2663
2664 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002665 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002666 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002667 ValueManager &ValMgr = Eng.getValueManager();
2668 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002669 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002670 }
2671 }
2672 }
2673 else {
2674 // Just blast away other values.
2675 state = state.BindLoc(*MR, UnknownVal());
2676 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002677 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002678 }
2679 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002680 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002681 }
2682 else {
2683 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002684 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002685 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002686 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002687 else if (isa<nonloc::LocAsInteger>(V))
2688 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002689 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002690
Ted Kremenek272aa852008-06-25 21:21:56 +00002691 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002692 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002693 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002694 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002695 if (const RefVal* T = state.get<RefBindings>(Sym)) {
2696 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
2697 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002698 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002699 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002700 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002701 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002702 }
2703 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002704
Ted Kremenek272aa852008-06-25 21:21:56 +00002705 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002706 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002707 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002708 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002709 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002710 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002711
Ted Kremenekf2717b02008-07-18 17:24:20 +00002712 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00002713 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002714
2715 switch (RE.getKind()) {
2716 default:
2717 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002718
Ted Kremenek8f90e712008-10-17 22:23:12 +00002719 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002720
Ted Kremenek455dd862008-04-11 20:23:24 +00002721 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002722 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2723 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002724
Ted Kremenek8f90e712008-10-17 22:23:12 +00002725 // FIXME: We eventually should handle structs and other compound types
2726 // that are returned by value.
2727
2728 QualType T = Ex->getType();
2729
Ted Kremenek79413a52008-11-13 06:10:40 +00002730 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002731 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002732 ValueManager &ValMgr = Eng.getValueManager();
2733 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002734 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002735 }
2736
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002737 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002738 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002739
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002740 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002741 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002742 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002743 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002744 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002745 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002746 break;
2747 }
2748
Ted Kremenek227c5372008-05-06 02:41:27 +00002749 case RetEffect::ReceiverAlias: {
2750 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002751 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002752 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002753 break;
2754 }
2755
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002756 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002757 case RetEffect::OwnedSymbol: {
2758 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002759 ValueManager &ValMgr = Eng.getValueManager();
2760 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2761 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2762 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2763 RetT));
2764 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002765
2766 // FIXME: Add a flag to the checker where allocations are assumed to
2767 // *not fail.
2768#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002769 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2770 bool isFeasible;
2771 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2772 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2773 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002774#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002775
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002776 break;
2777 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002778
2779 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002780 case RetEffect::NotOwnedSymbol: {
2781 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002782 ValueManager &ValMgr = Eng.getValueManager();
2783 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2784 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2785 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2786 RetT));
2787 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002788 break;
2789 }
2790 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002791
Ted Kremenek0dd65012009-02-18 02:00:25 +00002792 // Generate a sink node if we are at the end of a path.
2793 GRExprEngine::NodeTy *NewNode =
2794 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2795 : Builder.MakeNode(Dst, Ex, Pred, state);
2796
2797 // Annotate the edge with summary we used.
2798 // FIXME: This assumes that we always use the same summary when generating
2799 // this node.
2800 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002801}
2802
2803
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002804void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002805 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002806 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002807 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002808 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002809 const FunctionDecl* FD = L.getAsFunctionDecl();
2810 RetainSummary* Summ = !FD ? 0
2811 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002812
2813 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2814 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002815}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002816
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002817void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002818 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002819 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002820 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002821 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002822 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002823
Ted Kremenek272aa852008-06-25 21:21:56 +00002824 if (Expr* Receiver = ME->getReceiver()) {
2825 // We need the type-information of the tracked receiver object
2826 // Retrieve it from the state.
2827 ObjCInterfaceDecl* ID = 0;
2828
2829 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2830 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002831 // FIXME: Is this really working as expected? There are cases where
2832 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002833 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002834 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002835
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002836 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002837 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002838 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002839 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002840
2841 if (const PointerType* PT = Ty->getAsPointerType()) {
2842 QualType PointeeTy = PT->getPointeeType();
2843
2844 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2845 ID = IT->getDecl();
2846 }
2847 }
2848 }
2849
Ted Kremenek04e00302009-04-29 17:09:14 +00002850 // FIXME: The receiver could be a reference to a class, meaning that
2851 // we should use the class method.
2852 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002853
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002854 // Special-case: are we sending a mesage to "self"?
2855 // This is a hack. When we have full-IP this should be removed.
2856 if (!Summ) {
2857 ObjCMethodDecl* MD =
2858 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2859
2860 if (MD) {
2861 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002862 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002863 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002864 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2865 // Create a summmary where all of the arguments "StopTracking".
2866 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2867 DoNothing,
2868 StopTracking);
2869 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002870 }
2871 }
2872 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002873 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002874 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002875 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002876
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002877
Ted Kremenek926abf22008-05-06 04:20:12 +00002878 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2879 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002880}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002881
2882namespace {
2883class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2884 GRStateRef state;
2885public:
2886 StopTrackingCallback(GRStateRef st) : state(st) {}
2887 GRStateRef getState() { return state; }
2888
2889 bool VisitSymbol(SymbolRef sym) {
2890 state = state.remove<RefBindings>(sym);
2891 return true;
2892 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002893
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002894 const GRState* getState() const { return state.getState(); }
2895};
2896} // end anonymous namespace
2897
2898
Ted Kremeneka42be302009-02-14 01:43:44 +00002899void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002900 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002901 bool escapes = false;
2902
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002903 // A value escapes in three possible cases (this may change):
2904 //
2905 // (1) we are binding to something that is not a memory region.
2906 // (2) we are binding to a memregion that does not have stack storage
2907 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002908 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002909 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002910
Ted Kremeneka42be302009-02-14 01:43:44 +00002911 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002912 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002913 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002914 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2915 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002916
2917 if (!escapes) {
2918 // To test (3), generate a new state with the binding removed. If it is
2919 // the same state, then it escapes (since the store cannot represent
2920 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002921 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002922 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002923 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002924
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002925 // If our store can represent the binding and we aren't storing to something
2926 // that doesn't have local storage then just return and have the simulation
2927 // state continue as is.
2928 if (!escapes)
2929 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002930
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002931 // Otherwise, find all symbols referenced by 'val' that we are tracking
2932 // and stop tracking them.
2933 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002934}
2935
Ted Kremenek0106e202008-10-24 20:32:50 +00002936std::pair<GRStateRef,bool>
2937CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2938 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002939 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002940 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002941
Ted Kremenek47a72422009-04-29 18:50:19 +00002942 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002943 hasLeak = V.isOwned() ||
2944 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002945
Ted Kremenek47a72422009-04-29 18:50:19 +00002946 GRStateRef state(St, VMgr);
2947
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002948 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002949 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002950
Ted Kremenek0106e202008-10-24 20:32:50 +00002951 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2952 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002953}
2954
Ted Kremenek541db372008-04-24 23:57:27 +00002955
Ted Kremenekffefc352008-04-11 22:25:11 +00002956
Ted Kremenek541db372008-04-24 23:57:27 +00002957// Dead symbols.
2958
Ted Kremenek708af042009-02-05 06:50:21 +00002959
Ted Kremenek541db372008-04-24 23:57:27 +00002960
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002961 // Return statements.
2962
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002963void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002964 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002965 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002966 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002967 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002968
2969 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002970 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002971 return;
2972
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002973 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002974 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002975
Ted Kremenek74556a12009-03-26 03:35:11 +00002976 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002977 return;
2978
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002979 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002980 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002981
2982 if (!T)
2983 return;
2984
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002985 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002986 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002987
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002988 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002989 case RefVal::Owned: {
2990 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002991 assert (cnt > 0);
2992 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002993 break;
2994 }
2995
2996 case RefVal::NotOwned: {
2997 unsigned cnt = X.getCount();
2998 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2999 : RefVal::makeReturnedNotOwned();
3000 break;
3001 }
3002
3003 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003004 return;
3005 }
3006
3007 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003008 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003009 Pred = Builder.MakeNode(Dst, S, Pred, state);
3010
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003011 // Did we cache out?
3012 if (!Pred)
3013 return;
3014
Ted Kremenek47a72422009-04-29 18:50:19 +00003015 // Any leaks or other errors?
3016 if (X.isReturnedOwned() && X.getCount() == 0) {
3017 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3018
Ted Kremenek314b1952009-04-29 23:03:22 +00003019 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3020 RetainSummary *Summ = Summaries.getMethodSummary(MD);
3021 if (!GetRetEffect(Summ).isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003022 static int ReturnOwnLeakTag = 0;
3023 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00003024 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003025 if (ExplodedNode<GRState> *N =
3026 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
3027 CFRefLeakReport *report =
3028 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3029 N, Sym, Eng);
3030 BR->EmitReport(report);
3031 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003032 }
3033 }
3034 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003035}
3036
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003037// Assumptions.
3038
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003039const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3040 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003041 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003042 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003043
3044 // FIXME: We may add to the interface of EvalAssume the list of symbols
3045 // whose assumptions have changed. For now we just iterate through the
3046 // bindings and check if any of the tracked symbols are NULL. This isn't
3047 // too bad since the number of symbols we will track in practice are
3048 // probably small and EvalAssume is only called at branches and a few
3049 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003050 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003051
3052 if (B.isEmpty())
3053 return St;
3054
3055 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003056
3057 GRStateRef state(St, VMgr);
3058 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003059
3060 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003061 // Check if the symbol is null (or equal to any constant).
3062 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003063 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003064 changed = true;
3065 B = RefBFactory.Remove(B, I.getKey());
3066 }
3067 }
3068
Ted Kremenek91781202008-08-17 03:20:02 +00003069 if (changed)
3070 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003071
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003072 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003073}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003074
Ted Kremenekb6578942009-02-24 19:15:11 +00003075GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3076 RefVal V, ArgEffect E,
3077 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003078
3079 // In GC mode [... release] and [... retain] do nothing.
3080 switch (E) {
3081 default: break;
3082 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3083 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003084 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003085 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3086 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003087 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003088
Ted Kremenek6537a642009-03-17 19:42:23 +00003089 // Handle all use-after-releases.
3090 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3091 V = V ^ RefVal::ErrorUseAfterRelease;
3092 hasErr = V.getKind();
3093 return state.set<RefBindings>(sym, V);
3094 }
3095
Ted Kremenek0d721572008-03-11 17:48:22 +00003096 switch (E) {
3097 default:
3098 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003099
3100 case Dealloc:
3101 // Any use of -dealloc in GC is *bad*.
3102 if (isGCEnabled()) {
3103 V = V ^ RefVal::ErrorDeallocGC;
3104 hasErr = V.getKind();
3105 break;
3106 }
3107
3108 switch (V.getKind()) {
3109 default:
3110 assert(false && "Invalid case.");
3111 case RefVal::Owned:
3112 // The object immediately transitions to the released state.
3113 V = V ^ RefVal::Released;
3114 V.clearCounts();
3115 return state.set<RefBindings>(sym, V);
3116 case RefVal::NotOwned:
3117 V = V ^ RefVal::ErrorDeallocNotOwned;
3118 hasErr = V.getKind();
3119 break;
3120 }
3121 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003122
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003123 case NewAutoreleasePool:
3124 assert(!isGCEnabled());
3125 return state.add<AutoreleaseStack>(sym);
3126
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003127 case MayEscape:
3128 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003129 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003130 break;
3131 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003132
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003133 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003134
Ted Kremenekede40b72008-07-09 18:11:16 +00003135 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003136 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003137 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003138
Ted Kremenek9b112d22009-01-28 21:44:40 +00003139 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003140 if (isGCEnabled())
3141 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003142
3143 // Update the autorelease counts.
3144 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003145
3146 // Fall-through.
3147
Ted Kremenek227c5372008-05-06 02:41:27 +00003148 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003149 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003150
Ted Kremenek0d721572008-03-11 17:48:22 +00003151 case IncRef:
3152 switch (V.getKind()) {
3153 default:
3154 assert(false);
3155
3156 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003157 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003158 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003159 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003160 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003161 // Non-GC cases are handled above.
3162 assert(isGCEnabled());
3163 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003164 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003165 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003166 break;
3167
Ted Kremenek272aa852008-06-25 21:21:56 +00003168 case SelfOwn:
3169 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003170 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003171 case DecRef:
3172 switch (V.getKind()) {
3173 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003174 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003175 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003176
Ted Kremenek272aa852008-06-25 21:21:56 +00003177 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003178 assert(V.getCount() > 0);
3179 if (V.getCount() == 1) V = V ^ RefVal::Released;
3180 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003181 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003182
Ted Kremenek272aa852008-06-25 21:21:56 +00003183 case RefVal::NotOwned:
3184 if (V.getCount() > 0)
3185 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003186 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003187 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003188 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003189 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003190 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003191
Ted Kremenek0d721572008-03-11 17:48:22 +00003192 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003193 // Non-GC cases are handled above.
3194 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003195 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003196 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003197 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003198 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003199 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003200 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003201 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003202}
3203
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003204//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003205// Handle dead symbols and end-of-path.
3206//===----------------------------------------------------------------------===//
3207
3208void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3209 GREndPathNodeBuilder<GRState>& Builder) {
3210
3211 const GRState* St = Builder.getState();
3212 RefBindings B = St->get<RefBindings>();
3213
3214 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3215 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3216
3217 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3218 bool hasLeak = false;
3219
3220 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003221 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3222 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003223
3224 St = X.first;
3225 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3226 }
3227
3228 if (Leaked.empty())
3229 return;
3230
3231 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3232
3233 if (!N)
3234 return;
3235
3236 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3237 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3238
3239 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3240 : leakWithinFunction);
3241 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003242 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003243 BR->EmitReport(report);
3244 }
3245}
3246
3247void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3248 GRExprEngine& Eng,
3249 GRStmtNodeBuilder<GRState>& Builder,
3250 ExplodedNode<GRState>* Pred,
3251 Stmt* S,
3252 const GRState* St,
3253 SymbolReaper& SymReaper) {
3254
Ted Kremenek876d8df2009-02-19 23:47:02 +00003255 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003256 RefBindings B = St->get<RefBindings>();
3257 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3258
3259 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3260 E = SymReaper.dead_end(); I != E; ++I) {
3261
3262 const RefVal* T = B.lookup(*I);
3263 if (!T) continue;
3264
3265 bool hasLeak = false;
3266
3267 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003268 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003269
3270 St = X.first;
3271
3272 if (hasLeak)
3273 Leaked.push_back(std::make_pair(*I,X.second));
3274 }
3275
Ted Kremenek876d8df2009-02-19 23:47:02 +00003276 if (!Leaked.empty()) {
3277 // Create a new intermediate node representing the leak point. We
3278 // use a special program point that represents this checker-specific
3279 // transition. We use the address of RefBIndex as a unique tag for this
3280 // checker. We will create another node (if we don't cache out) that
3281 // removes the retain-count bindings from the state.
3282 // NOTE: We use 'generateNode' so that it does interplay with the
3283 // auto-transition logic.
3284 ExplodedNode<GRState>* N =
3285 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003286
Ted Kremenek876d8df2009-02-19 23:47:02 +00003287 if (!N)
3288 return;
3289
3290 // Generate the bug reports.
3291 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3292 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3293
3294 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3295 : leakWithinFunction);
3296 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003297 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3298 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003299 BR->EmitReport(report);
3300 }
Ted Kremenek708af042009-02-05 06:50:21 +00003301
Ted Kremenek876d8df2009-02-19 23:47:02 +00003302 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003303 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003304
3305 // Now generate a new node that nukes the old bindings.
3306 GRStateRef state(St, Eng.getStateManager());
3307 RefBindings::Factory& F = state.get_context<RefBindings>();
3308
3309 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3310 E = SymReaper.dead_end(); I!=E; ++I)
3311 B = F.Remove(B, *I);
3312
3313 state = state.set<RefBindings>(B);
3314 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003315}
3316
3317void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3318 GRStmtNodeBuilder<GRState>& Builder,
3319 Expr* NodeExpr, Expr* ErrorExpr,
3320 ExplodedNode<GRState>* Pred,
3321 const GRState* St,
3322 RefVal::Kind hasErr, SymbolRef Sym) {
3323 Builder.BuildSinks = true;
3324 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3325
3326 if (!N) return;
3327
3328 CFRefBug *BT = 0;
3329
Ted Kremenek6537a642009-03-17 19:42:23 +00003330 switch (hasErr) {
3331 default:
3332 assert(false && "Unhandled error.");
3333 return;
3334 case RefVal::ErrorUseAfterRelease:
3335 BT = static_cast<CFRefBug*>(useAfterRelease);
3336 break;
3337 case RefVal::ErrorReleaseNotOwned:
3338 BT = static_cast<CFRefBug*>(releaseNotOwned);
3339 break;
3340 case RefVal::ErrorDeallocGC:
3341 BT = static_cast<CFRefBug*>(deallocGC);
3342 break;
3343 case RefVal::ErrorDeallocNotOwned:
3344 BT = static_cast<CFRefBug*>(deallocNotOwned);
3345 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003346 }
3347
Ted Kremenekc26c4692009-02-18 03:48:14 +00003348 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003349 report->addRange(ErrorExpr->getSourceRange());
3350 BR->EmitReport(report);
3351}
3352
3353//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003354// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003355//===----------------------------------------------------------------------===//
3356
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003357GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3358 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003359 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003360}