blob: f5d29fd73e3b5c2fdd53d19c1b3e3debc8e88fde [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.
768 MD = ResolveToInterfaceMethodDecl(MD, Ctx);
769
Ted Kremenek91b89a42009-04-29 17:17:48 +0000770 Selector S = MD->getSelector();
Ted Kremenek314b1952009-04-29 23:03:22 +0000771 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000772 IdentifierInfo *ClsName = ID->getIdentifier();
773 QualType ResultTy = MD->getResultType();
774
775 if (MD->isInstanceMethod())
776 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
777 else
778 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
779 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000780
Ted Kremenek314b1952009-04-29 23:03:22 +0000781 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
782 Selector S, QualType RetTy);
783
784 RetainSummary* getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000785
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000786 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000787};
788
789} // end anonymous namespace
790
791//===----------------------------------------------------------------------===//
792// Implementation of checker data structures.
793//===----------------------------------------------------------------------===//
794
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000795RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000796
797 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
798 // mitigating the need to do explicit cleanup of the
799 // Argument-Effect summaries.
800
Ted Kremenek42ea0322008-05-05 23:55:01 +0000801 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
802 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000803 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000804}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000805
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000806ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000807
Ted Kremenekae855d42008-04-24 17:22:33 +0000808 if (ScratchArgs.empty())
809 return NULL;
810
811 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000812 llvm::FoldingSetNodeID profile;
813 profile.Add(ScratchArgs);
814 void* InsertPos;
815
Ted Kremenekae855d42008-04-24 17:22:33 +0000816 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000817 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000818 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000819
Ted Kremenekae855d42008-04-24 17:22:33 +0000820 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000821 ScratchArgs.clear();
822 return &E->getValue();
823 }
824
825 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000826 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000827
828 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000829 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000830
831 ScratchArgs.clear();
832 return &E->getValue();
833}
834
Ted Kremenek266d8b62008-05-06 02:26:56 +0000835RetainSummary*
836RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000837 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000838 ArgEffect DefaultEff,
839 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000840
Ted Kremenekae855d42008-04-24 17:22:33 +0000841 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000842 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000843 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
844 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000845
Ted Kremenekae855d42008-04-24 17:22:33 +0000846 // Look up the uniqued summary, or create one if it doesn't exist.
847 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000848 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000849
850 if (Summ)
851 return Summ;
852
Ted Kremenekae855d42008-04-24 17:22:33 +0000853 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000854 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000855 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000856 SummarySet.InsertNode(Summ, InsertPos);
857
858 return Summ;
859}
860
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000861//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000862// Predicates.
863//===----------------------------------------------------------------------===//
864
Ted Kremenek0d813552009-04-23 22:11:07 +0000865bool RetainSummaryManager::isTrackedObjectType(QualType Ty) {
866 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000867 return false;
868
Ted Kremenek0d813552009-04-23 22:11:07 +0000869 // We assume that id<..>, id, and "Class" all represent tracked objects.
870 const PointerType *PT = Ty->getAsPointerType();
871 if (PT == 0)
872 return true;
873
874 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000875
876 // We assume that id<..>, id, and "Class" all represent tracked objects.
877 if (!OT)
878 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000879
880 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000881 // FIXME: We can memoize here if this gets too expensive.
882 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
883 ObjCInterfaceDecl* ID = OT->getDecl();
884
885 for ( ; ID ; ID = ID->getSuperClass())
886 if (ID->getIdentifier() == NSObjectII)
887 return true;
888
889 return false;
890}
891
892//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000893// Summary creation for functions (largely uses of Core Foundation).
894//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000895
Ted Kremenek17144e82009-01-12 21:45:02 +0000896static bool isRetain(FunctionDecl* FD, const char* FName) {
897 const char* loc = strstr(FName, "Retain");
898 return loc && loc[sizeof("Retain")-1] == '\0';
899}
900
901static bool isRelease(FunctionDecl* FD, const char* FName) {
902 const char* loc = strstr(FName, "Release");
903 return loc && loc[sizeof("Release")-1] == '\0';
904}
905
Ted Kremenekd13c1872008-06-24 03:56:45 +0000906RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000907
908 SourceLocation Loc = FD->getLocation();
909
910 if (!Loc.isFileID())
911 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000912
Ted Kremenekae855d42008-04-24 17:22:33 +0000913 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000914 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000915
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000916 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000917 return I->second;
918
919 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000920 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000921
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000922 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000923 // We generate "stop" summaries for implicitly defined functions.
924 if (FD->isImplicit()) {
925 S = getPersistentStopSummary();
926 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000927 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000928
Ted Kremenek064ef322009-02-23 16:51:39 +0000929 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000930 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000931 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000932 const char* FName = FD->getIdentifier()->getName();
933
Ted Kremenek38c6f022009-03-05 22:11:14 +0000934 // Strip away preceding '_'. Doing this here will effect all the checks
935 // down below.
936 while (*FName == '_') ++FName;
937
Ted Kremenek17144e82009-01-12 21:45:02 +0000938 // Inspect the result type.
939 QualType RetTy = FT->getResultType();
940
941 // FIXME: This should all be refactored into a chain of "summary lookup"
942 // filters.
943 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
944 // FIXES: <rdar://problem/6326900>
945 // This should be addressed using a API table. This strcmp is also
946 // a little gross, but there is no need to super optimize here.
947 assert (ScratchArgs.empty());
948 ScratchArgs.push_back(std::make_pair(1, DecRef));
949 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
950 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000951 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000952
953 // Enable this code once the semantics of NSDeallocateObject are resolved
954 // for GC. <rdar://problem/6619988>
955#if 0
956 // Handle: NSDeallocateObject(id anObject);
957 // This method does allow 'nil' (although we don't check it now).
958 if (strcmp(FName, "NSDeallocateObject") == 0) {
959 return RetTy == Ctx.VoidTy
960 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
961 : getPersistentStopSummary();
962 }
963#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000964
965 // Handle: id NSMakeCollectable(CFTypeRef)
966 if (strcmp(FName, "NSMakeCollectable") == 0) {
967 S = (RetTy == Ctx.getObjCIdType())
968 ? getUnarySummary(FT, cfmakecollectable)
969 : getPersistentStopSummary();
970
971 break;
972 }
973
974 if (RetTy->isPointerType()) {
975 // For CoreFoundation ('CF') types.
976 if (isRefType(RetTy, "CF", &Ctx, FName)) {
977 if (isRetain(FD, FName))
978 S = getUnarySummary(FT, cfretain);
979 else if (strstr(FName, "MakeCollectable"))
980 S = getUnarySummary(FT, cfmakecollectable);
981 else
982 S = getCFCreateGetRuleSummary(FD, FName);
983
984 break;
985 }
986
987 // For CoreGraphics ('CG') types.
988 if (isRefType(RetTy, "CG", &Ctx, FName)) {
989 if (isRetain(FD, FName))
990 S = getUnarySummary(FT, cfretain);
991 else
992 S = getCFCreateGetRuleSummary(FD, FName);
993
994 break;
995 }
996
997 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
998 if (isRefType(RetTy, "DADisk") ||
999 isRefType(RetTy, "DADissenter") ||
1000 isRefType(RetTy, "DASessionRef")) {
1001 S = getCFCreateGetRuleSummary(FD, FName);
1002 break;
1003 }
1004
1005 break;
1006 }
1007
1008 // Check for release functions, the only kind of functions that we care
1009 // about that don't return a pointer type.
1010 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001011 // Test for 'CGCF'.
1012 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1013 FName += 4;
1014 else
1015 FName += 2;
1016
1017 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001018 S = getUnarySummary(FT, cfrelease);
1019 else {
Ted Kremenek7b293682009-01-29 22:45:13 +00001020 assert (ScratchArgs.empty());
1021 // Remaining CoreFoundation and CoreGraphics functions.
1022 // We use to assume that they all strictly followed the ownership idiom
1023 // and that ownership cannot be transferred. While this is technically
1024 // correct, many methods allow a tracked object to escape. For example:
1025 //
1026 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1027 // CFDictionaryAddValue(y, key, x);
1028 // CFRelease(x);
1029 // ... it is okay to use 'x' since 'y' has a reference to it
1030 //
1031 // We handle this and similar cases with the follow heuristic. If the
1032 // function name contains "InsertValue", "SetValue" or "AddValue" then
1033 // we assume that arguments may "escape."
1034 //
1035 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1036 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001037 CStrInCStrNoCase(FName, "SetValue") ||
1038 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001039 ? MayEscape : DoNothing;
1040
1041 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001042 }
1043 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001044 }
1045 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +00001046
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001047 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001048 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001049}
1050
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001051RetainSummary*
1052RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1053 const char* FName) {
1054
Ted Kremenek562c1302008-05-05 16:51:50 +00001055 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1056 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001057
Ted Kremenek562c1302008-05-05 16:51:50 +00001058 if (strstr(FName, "Get"))
1059 return getCFSummaryGetRule(FD);
1060
1061 return 0;
1062}
1063
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001064RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001065RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1066 UnaryFuncKind func) {
1067
Ted Kremenek17144e82009-01-12 21:45:02 +00001068 // Sanity check that this is *really* a unary function. This can
1069 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001070 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001071 if (!FTP || FTP->getNumArgs() != 1)
1072 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001073
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001074 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001075
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001076 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +00001077 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001078 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001079 return getPersistentSummary(RetEffect::MakeAlias(0),
1080 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001081 }
1082
1083 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001084 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001085 return getPersistentSummary(RetEffect::MakeNoRet(),
1086 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001087 }
1088
1089 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +00001090 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1091 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001092 }
1093
1094 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001095 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001096 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001097 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001098}
1099
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001100RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001101 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001102
1103 if (FD->getIdentifier() == CFDictionaryCreateII) {
1104 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1105 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1106 }
1107
Ted Kremenek68621b92009-01-28 05:56:51 +00001108 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001109}
1110
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001111RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001112 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001113 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1114 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001115}
1116
Ted Kremeneka7338b42008-03-11 06:39:11 +00001117//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001118// Summary creation for Selectors.
1119//===----------------------------------------------------------------------===//
1120
Ted Kremenekbcaff792008-05-06 15:44:25 +00001121RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001122RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001123 assert(ScratchArgs.empty());
1124
Ted Kremenek802cfc72009-02-20 00:05:35 +00001125 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001126 return getPersistentSummary(Loc::IsLocType(RetTy)
1127 ? RetEffect::MakeReceiverAlias()
1128 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001129}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001130
Ted Kremenek923fc392009-04-24 23:32:32 +00001131RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001132RetainSummaryManager::getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD){
Ted Kremenek923fc392009-04-24 23:32:32 +00001133 if (!MD)
1134 return 0;
1135
1136 assert(ScratchArgs.empty());
1137
1138 // Determine if there is a special return effect for this method.
1139 bool hasRetEffect = false;
1140 RetEffect RE = RetEffect::MakeNoRet();
1141
1142 if (isTrackedObjectType(MD->getResultType())) {
1143 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001144 RE = isGCEnabled() ? RetEffect::MakeGCNotOwned()
1145 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek923fc392009-04-24 23:32:32 +00001146 hasRetEffect = true;
1147 }
1148 else {
1149 // Default to 'not owned'.
1150 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1151 }
1152 }
1153
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001154 // Determine if there are any arguments with a specific ArgEffect.
1155 bool hasArgEffect = false;
1156 unsigned i = 0;
1157 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1158 E = MD->param_end(); I != E; ++I, ++i) {
1159 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
1160 ScratchArgs.push_back(std::make_pair(i, IncRefMsg));
1161 hasArgEffect = true;
1162 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001163 else if ((*I)->getAttr<ObjCOwnershipCFRetainAttr>()) {
1164 ScratchArgs.push_back(std::make_pair(i, IncRef));
1165 hasArgEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001166 }
1167 else if ((*I)->getAttr<ObjCOwnershipReleaseAttr>()) {
1168 ScratchArgs.push_back(std::make_pair(i, DecRefMsg));
1169 hasArgEffect = true;
1170 }
1171 else if ((*I)->getAttr<ObjCOwnershipCFReleaseAttr>()) {
1172 ScratchArgs.push_back(std::make_pair(i, DecRef));
1173 hasArgEffect = true;
1174 }
Ted Kremenekff8648d2009-04-28 22:32:26 +00001175 else if ((*I)->getAttr<ObjCOwnershipMakeCollectableAttr>()) {
1176 ScratchArgs.push_back(std::make_pair(i, MakeCollectable));
1177 hasArgEffect = true;
1178 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001179 }
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001180
1181 if (!hasRetEffect && !hasArgEffect)
Ted Kremenek923fc392009-04-24 23:32:32 +00001182 return 0;
1183
1184 return getPersistentSummary(RE);
1185}
Ted Kremenek272aa852008-06-25 21:21:56 +00001186
Ted Kremenekbcaff792008-05-06 15:44:25 +00001187RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001188RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1189 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001190
Ted Kremenek578498a2009-04-29 00:42:39 +00001191 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001192 // Scan the method decl for 'void*' arguments. These should be treated
1193 // as 'StopTracking' because they are often used with delegates.
1194 // Delegates are a frequent form of false positives with the retain
1195 // count checker.
1196 unsigned i = 0;
1197 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1198 E = MD->param_end(); I != E; ++I, ++i)
1199 if (ParmVarDecl *PD = *I) {
1200 QualType Ty = Ctx.getCanonicalType(PD->getType());
1201 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
1202 ScratchArgs.push_back(std::make_pair(i, StopTracking));
1203 }
1204 }
1205
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001206 // Any special effect for the receiver?
1207 ArgEffect ReceiverEff = DoNothing;
1208
1209 // If one of the arguments in the selector has the keyword 'delegate' we
1210 // should stop tracking the reference count for the receiver. This is
1211 // because the reference count is quite possibly handled by a delegate
1212 // method.
1213 if (S.isKeywordSelector()) {
1214 const std::string &str = S.getAsString();
1215 assert(!str.empty());
1216 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1217 }
1218
Ted Kremenek174a0772009-04-23 23:08:22 +00001219 // Look for methods that return an owned object.
Ted Kremenek578498a2009-04-29 00:42:39 +00001220 if (!isTrackedObjectType(RetTy)) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001221 if (ScratchArgs.empty() && ReceiverEff == DoNothing)
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001222 return 0;
1223
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001224 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1225 MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001226 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001227
1228 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1229 // by instance methods.
1230
1231 RetEffect E =
Ted Kremenekaca0b452009-04-24 18:19:07 +00001232 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001233 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek174a0772009-04-23 23:08:22 +00001234 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1235 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1236
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001237 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001238}
1239
1240RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001241RetainSummaryManager::getInstanceMethodSummary(Selector S,
1242 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001243 const ObjCInterfaceDecl* ID,
1244 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001245 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001246
Ted Kremeneka821b792009-04-29 05:04:30 +00001247 // Look up a summary in our summary cache.
1248 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001249
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001250 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001251 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001252
Ted Kremenek174a0772009-04-23 23:08:22 +00001253 assert(ScratchArgs.empty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001254
1255 // Annotations take precedence over all other ways to derive
1256 // summaries.
Ted Kremeneka821b792009-04-29 05:04:30 +00001257 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001258
Ted Kremenek923fc392009-04-24 23:32:32 +00001259 if (!Summ) {
1260 // "initXXX": pass-through for receiver.
1261 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1262 == InitRule)
Ted Kremeneka821b792009-04-29 05:04:30 +00001263 Summ = getInitMethodSummary(RetTy);
1264 else
1265 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001266 }
1267
Ted Kremeneka821b792009-04-29 05:04:30 +00001268 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001269 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001270}
1271
Ted Kremeneka7722b72008-05-06 21:26:51 +00001272RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001273RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001274 const ObjCInterfaceDecl *ID,
1275 const ObjCMethodDecl *MD,
1276 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001277
Ted Kremenek578498a2009-04-29 00:42:39 +00001278 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001279 ObjCMethodSummariesTy::iterator I =
1280 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001281
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001282 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001283 return I->second;
1284
Ted Kremenek923fc392009-04-24 23:32:32 +00001285 // Annotations take precedence over all other ways to derive
1286 // summaries.
Ted Kremenek578498a2009-04-29 00:42:39 +00001287 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001288
1289 if (!Summ)
Ted Kremenek578498a2009-04-29 00:42:39 +00001290 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001291
Ted Kremenek578498a2009-04-29 00:42:39 +00001292 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001293 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001294}
1295
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001296void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001297
1298 assert (ScratchArgs.empty());
1299
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001300 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001301 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001302
Ted Kremenek0e344d42008-05-06 00:30:21 +00001303 RetainSummary* Summ = getPersistentSummary(E);
1304
Ted Kremenek272aa852008-06-25 21:21:56 +00001305 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1306 // NSObject and its derivatives.
1307 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1308 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1309 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001310
1311 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001312 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001313 GetNullarySelector("currentHandler", Ctx),
1314 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001315
1316 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001317 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1318 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1319 GetUnarySelector("addObject", Ctx),
1320 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001321 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001322
1323 // Create the summaries for [NSObject performSelector...]. We treat
1324 // these as 'stop tracking' for the arguments because they are often
1325 // used for delegates that can release the object. When we have better
1326 // inter-procedural analysis we can potentially do something better. This
1327 // workaround is to remove false positives.
1328 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1329 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1330 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1331 "afterDelay", NULL);
1332 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1333 "afterDelay", "inModes", NULL);
1334 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1335 "withObject", "waitUntilDone", NULL);
1336 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1337 "withObject", "waitUntilDone", "modes", NULL);
1338 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1339 "withObject", "waitUntilDone", NULL);
1340 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1341 "withObject", "waitUntilDone", "modes", NULL);
1342 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1343 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001344}
1345
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001346void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001347
1348 assert (ScratchArgs.empty());
1349
Ted Kremeneka7722b72008-05-06 21:26:51 +00001350 // Create the "init" selector. It just acts as a pass-through for the
1351 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001352 RetainSummary* InitSumm =
1353 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001354 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001355
1356 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001357 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001358 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001359
Ted Kremeneke44927e2008-07-01 17:21:27 +00001360 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001361
1362 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001363 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1364
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001365 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001366 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001367
Ted Kremenek266d8b62008-05-06 02:26:56 +00001368 // Create the "retain" selector.
1369 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001370 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001371 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001372
1373 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001374 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001375 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001376
1377 // Create the "drain" selector.
1378 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001379 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001380
1381 // Create the -dealloc summary.
1382 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1383 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001384
1385 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001386 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001387 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001388
Ted Kremenekaac82832009-02-23 17:45:03 +00001389 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001390 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001391 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001392 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001393
Ted Kremenek45642a42008-08-12 18:48:50 +00001394 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001395 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1396 // self-own themselves. However, they only do this once they are displayed.
1397 // Thus, we need to track an NSWindow's display status.
1398 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001399 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001400 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1401
1402 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1403
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001404
1405#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001406 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001407 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001408
1409 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1410 "styleMask", "backing", "defer", NULL);
1411
1412 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1413 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001414#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001415
1416 // For NSPanel (which subclasses NSWindow), allocated objects are not
1417 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001418 // FIXME: For now we don't track NSPanels. object for the same reason
1419 // as for NSWindow objects.
1420 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1421
Ted Kremenek45642a42008-08-12 18:48:50 +00001422 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1423 "styleMask", "backing", "defer", NULL);
1424
1425 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1426 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001427
Ted Kremenekf2717b02008-07-18 17:24:20 +00001428 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001429 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1430 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001431
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001432 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1433 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001434}
1435
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001436//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001437// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001438//===----------------------------------------------------------------------===//
1439
Ted Kremeneka7338b42008-03-11 06:39:11 +00001440namespace {
1441
Ted Kremenek7d421f32008-04-09 23:49:11 +00001442class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001443public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001444 enum Kind {
1445 Owned = 0, // Owning reference.
1446 NotOwned, // Reference is not owned by still valid (not freed).
1447 Released, // Object has been released.
1448 ReturnedOwned, // Returned object passes ownership to caller.
1449 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001450 ERROR_START,
1451 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1452 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001453 ErrorUseAfterRelease, // Object used after released.
1454 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001455 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001456 ErrorLeak, // A memory leak due to excessive reference counts.
1457 ErrorLeakReturned // A memory leak due to the returning method not having
1458 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001459 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001460
1461private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001462 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001463 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001464 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001465 QualType T;
1466
Ted Kremenek68621b92009-01-28 05:56:51 +00001467 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1468 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001469
Ted Kremenek68621b92009-01-28 05:56:51 +00001470 RefVal(Kind k, unsigned cnt = 0)
1471 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1472
1473public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001474 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001475
1476 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001477
Ted Kremenek6537a642009-03-17 19:42:23 +00001478 unsigned getCount() const { return Cnt; }
1479 void clearCounts() { Cnt = 0; }
1480
Ted Kremenek272aa852008-06-25 21:21:56 +00001481 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001482
1483 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001484
Ted Kremenek6537a642009-03-17 19:42:23 +00001485 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001486
Ted Kremenek6537a642009-03-17 19:42:23 +00001487 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001488
Ted Kremenekffefc352008-04-11 22:25:11 +00001489 bool isOwned() const {
1490 return getKind() == Owned;
1491 }
1492
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001493 bool isNotOwned() const {
1494 return getKind() == NotOwned;
1495 }
1496
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001497 bool isReturnedOwned() const {
1498 return getKind() == ReturnedOwned;
1499 }
1500
1501 bool isReturnedNotOwned() const {
1502 return getKind() == ReturnedNotOwned;
1503 }
1504
1505 bool isNonLeakError() const {
1506 Kind k = getKind();
1507 return isError(k) && !isLeak(k);
1508 }
1509
Ted Kremenek68621b92009-01-28 05:56:51 +00001510 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1511 unsigned Count = 1) {
1512 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001513 }
1514
Ted Kremenek68621b92009-01-28 05:56:51 +00001515 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1516 unsigned Count = 0) {
1517 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001518 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001519
1520 static RefVal makeReturnedOwned(unsigned Count) {
1521 return RefVal(ReturnedOwned, Count);
1522 }
1523
1524 static RefVal makeReturnedNotOwned() {
1525 return RefVal(ReturnedNotOwned);
1526 }
1527
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001528 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001529
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001530 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001531 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001532 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001533
Ted Kremenek272aa852008-06-25 21:21:56 +00001534 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001535 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001536 }
1537
1538 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001539 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001540 }
1541
1542 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001543 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001544 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001545
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001546 void Profile(llvm::FoldingSetNodeID& ID) const {
1547 ID.AddInteger((unsigned) kind);
1548 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001549 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001550 }
1551
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001552 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001553};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001554
1555void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001556 if (!T.isNull())
1557 Out << "Tracked Type:" << T.getAsString() << '\n';
1558
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001559 switch (getKind()) {
1560 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001561 case Owned: {
1562 Out << "Owned";
1563 unsigned cnt = getCount();
1564 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001565 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001566 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001567
Ted Kremenekc4f81022008-04-10 23:09:18 +00001568 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001569 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001570 unsigned cnt = getCount();
1571 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001572 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001573 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001574
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001575 case ReturnedOwned: {
1576 Out << "ReturnedOwned";
1577 unsigned cnt = getCount();
1578 if (cnt) Out << " (+ " << cnt << ")";
1579 break;
1580 }
1581
1582 case ReturnedNotOwned: {
1583 Out << "ReturnedNotOwned";
1584 unsigned cnt = getCount();
1585 if (cnt) Out << " (+ " << cnt << ")";
1586 break;
1587 }
1588
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001589 case Released:
1590 Out << "Released";
1591 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001592
1593 case ErrorDeallocGC:
1594 Out << "-dealloc (GC)";
1595 break;
1596
1597 case ErrorDeallocNotOwned:
1598 Out << "-dealloc (not-owned)";
1599 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001600
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001601 case ErrorLeak:
1602 Out << "Leaked";
1603 break;
1604
Ted Kremenek311f3d42008-10-22 23:56:21 +00001605 case ErrorLeakReturned:
1606 Out << "Leaked (Bad naming)";
1607 break;
1608
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001609 case ErrorUseAfterRelease:
1610 Out << "Use-After-Release [ERROR]";
1611 break;
1612
1613 case ErrorReleaseNotOwned:
1614 Out << "Release of Not-Owned [ERROR]";
1615 break;
1616 }
1617}
Ted Kremenek0d721572008-03-11 17:48:22 +00001618
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001619} // end anonymous namespace
1620
1621//===----------------------------------------------------------------------===//
1622// RefBindings - State used to track object reference counts.
1623//===----------------------------------------------------------------------===//
1624
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001625typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001626static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001627static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001628
1629namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001630 template<>
1631 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1632 static inline void* GDMIndex() { return &RefBIndex; }
1633 };
1634}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001635
1636//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001637// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001638//===----------------------------------------------------------------------===//
1639
Ted Kremenekb6578942009-02-24 19:15:11 +00001640typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1641typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1642typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001643
Ted Kremenekb6578942009-02-24 19:15:11 +00001644static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001645static int AutoRBIndex = 0;
1646
Ted Kremenekb6578942009-02-24 19:15:11 +00001647namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001648namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001649
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001650namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001651template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001652 : public GRStatePartialTrait<ARStack> {
1653 static inline void* GDMIndex() { return &AutoRBIndex; }
1654};
1655
1656template<> struct GRStateTrait<AutoreleasePoolContents>
1657 : public GRStatePartialTrait<ARPoolContents> {
1658 static inline void* GDMIndex() { return &AutoRCIndex; }
1659};
1660} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001661
Ted Kremenek681fb352009-03-20 17:34:15 +00001662static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1663 ARStack stack = state->get<AutoreleaseStack>();
1664 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1665}
1666
1667static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1668 SymbolRef sym) {
1669
1670 SymbolRef pool = GetCurrentAutoreleasePool(state);
1671 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1672 ARCounts newCnts(0);
1673
1674 if (cnts) {
1675 const unsigned *cnt = (*cnts).lookup(sym);
1676 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1677 }
1678 else
1679 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1680
1681 return state.set<AutoreleasePoolContents>(pool, newCnts);
1682}
1683
Ted Kremenek7aef4842008-04-16 20:40:59 +00001684//===----------------------------------------------------------------------===//
1685// Transfer functions.
1686//===----------------------------------------------------------------------===//
1687
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001688namespace {
1689
Ted Kremenek7d421f32008-04-09 23:49:11 +00001690class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001691public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001692 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001693 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001694 virtual void Print(std::ostream& Out, const GRState* state,
1695 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001696 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001697
1698private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001699 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1700 SummaryLogTy;
1701
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001702 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001703 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001704 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001705 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001706
Ted Kremenek708af042009-02-05 06:50:21 +00001707 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001708 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001709 BugType *leakWithinFunction, *leakAtReturn;
1710 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001711
Ted Kremenekb6578942009-02-24 19:15:11 +00001712 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1713 RefVal::Kind& hasErr);
1714
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001715 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1716 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001717 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001718 ExplodedNode<GRState>* Pred,
1719 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001720 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001721
Ted Kremenek0106e202008-10-24 20:32:50 +00001722 std::pair<GRStateRef, bool>
1723 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001724 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001725
Ted Kremenekb6578942009-02-24 19:15:11 +00001726public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001727 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001728 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001729 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1730 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001731 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001732
Ted Kremenek708af042009-02-05 06:50:21 +00001733 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001734
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001735 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001736
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001737 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1738 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001739 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001740
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001741 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001742 const LangOptions& getLangOptions() const { return LOpts; }
1743
Ted Kremenekc26c4692009-02-18 03:48:14 +00001744 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1745 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1746 return I == SummaryLog.end() ? 0 : I->second;
1747 }
1748
Ted Kremeneka7338b42008-03-11 06:39:11 +00001749 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001750
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001751 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001752 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001753 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001754 Expr* Ex,
1755 Expr* Receiver,
1756 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001757 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001758 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001759
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001760 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001761 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001762 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001763 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001764 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001765
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001766
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001767 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001768 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001769 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001770 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001771 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001772
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001773 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001774 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001775 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001776 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001777 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001778
Ted Kremeneka42be302009-02-14 01:43:44 +00001779 // Stores.
1780 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1781
Ted Kremenekffefc352008-04-11 22:25:11 +00001782 // End-of-path.
1783
1784 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001785 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001786
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001787 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001788 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001789 GRStmtNodeBuilder<GRState>& Builder,
1790 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001791 Stmt* S, const GRState* state,
1792 SymbolReaper& SymReaper);
1793
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001794 // Return statements.
1795
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001796 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001797 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001798 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001799 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001800 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001801
1802 // Assumptions.
1803
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001804 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001805 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001806 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001807};
1808
1809} // end anonymous namespace
1810
Ted Kremenek681fb352009-03-20 17:34:15 +00001811static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1812 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001813 if (Sym)
1814 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001815 else
1816 Out << "<pool>";
1817 Out << ":{";
1818
1819 // Get the contents of the pool.
1820 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1821 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1822 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1823
1824 Out << '}';
1825}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001826
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001827void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1828 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001829
1830
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001831
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001832 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001833
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001834 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001835 Out << sep << nl;
1836
1837 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1838 Out << (*I).first << " : ";
1839 (*I).second.print(Out);
1840 Out << nl;
1841 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001842
1843 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001844 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001845 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001846
Ted Kremenek681fb352009-03-20 17:34:15 +00001847 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1848 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1849 PrintPool(Out, *I, state);
1850
1851 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001852}
1853
Ted Kremenek47a72422009-04-29 18:50:19 +00001854//===----------------------------------------------------------------------===//
1855// Error reporting.
1856//===----------------------------------------------------------------------===//
1857
1858namespace {
1859
1860 //===-------------===//
1861 // Bug Descriptions. //
1862 //===-------------===//
1863
1864 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1865 protected:
1866 CFRefCount& TF;
1867
1868 CFRefBug(CFRefCount* tf, const char* name)
1869 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1870 public:
1871
1872 CFRefCount& getTF() { return TF; }
1873 const CFRefCount& getTF() const { return TF; }
1874
1875 // FIXME: Eventually remove.
1876 virtual const char* getDescription() const = 0;
1877
1878 virtual bool isLeak() const { return false; }
1879 };
1880
1881 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1882 public:
1883 UseAfterRelease(CFRefCount* tf)
1884 : CFRefBug(tf, "Use-after-release") {}
1885
1886 const char* getDescription() const {
1887 return "Reference-counted object is used after it is released";
1888 }
1889 };
1890
1891 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1892 public:
1893 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1894
1895 const char* getDescription() const {
1896 return "Incorrect decrement of the reference count of an "
1897 "object is not owned at this point by the caller";
1898 }
1899 };
1900
1901 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1902 public:
1903 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1904 "-dealloc called while using GC") {}
1905
1906 const char *getDescription() const {
1907 return "-dealloc called while using GC";
1908 }
1909 };
1910
1911 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1912 public:
1913 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1914 "-dealloc sent to non-exclusively owned object") {}
1915
1916 const char *getDescription() const {
1917 return "-dealloc sent to object that may be referenced elsewhere";
1918 }
1919 };
1920
1921 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1922 const bool isReturn;
1923 protected:
1924 Leak(CFRefCount* tf, const char* name, bool isRet)
1925 : CFRefBug(tf, name), isReturn(isRet) {}
1926 public:
1927
1928 const char* getDescription() const { return ""; }
1929
1930 bool isLeak() const { return true; }
1931 };
1932
1933 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1934 public:
1935 LeakAtReturn(CFRefCount* tf, const char* name)
1936 : Leak(tf, name, true) {}
1937 };
1938
1939 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1940 public:
1941 LeakWithinFunction(CFRefCount* tf, const char* name)
1942 : Leak(tf, name, false) {}
1943 };
1944
1945 //===---------===//
1946 // Bug Reports. //
1947 //===---------===//
1948
1949 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1950 protected:
1951 SymbolRef Sym;
1952 const CFRefCount &TF;
1953 public:
1954 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1955 ExplodedNode<GRState> *n, SymbolRef sym)
1956 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1957
1958 virtual ~CFRefReport() {}
1959
1960 CFRefBug& getBugType() {
1961 return (CFRefBug&) RangedBugReport::getBugType();
1962 }
1963 const CFRefBug& getBugType() const {
1964 return (const CFRefBug&) RangedBugReport::getBugType();
1965 }
1966
1967 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1968 const SourceRange*& end) {
1969
1970 if (!getBugType().isLeak())
1971 RangedBugReport::getRanges(BR, beg, end);
1972 else
1973 beg = end = 0;
1974 }
1975
1976 SymbolRef getSymbol() const { return Sym; }
1977
1978 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1979 const ExplodedNode<GRState>* N);
1980
1981 std::pair<const char**,const char**> getExtraDescriptiveText();
1982
1983 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1984 const ExplodedNode<GRState>* PrevN,
1985 const ExplodedGraph<GRState>& G,
1986 BugReporter& BR,
1987 NodeResolver& NR);
1988 };
1989
1990 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1991 SourceLocation AllocSite;
1992 const MemRegion* AllocBinding;
1993 public:
1994 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1995 ExplodedNode<GRState> *n, SymbolRef sym,
1996 GRExprEngine& Eng);
1997
1998 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1999 const ExplodedNode<GRState>* N);
2000
2001 SourceLocation getLocation() const { return AllocSite; }
2002 };
2003} // end anonymous namespace
2004
2005void CFRefCount::RegisterChecks(BugReporter& BR) {
2006 useAfterRelease = new UseAfterRelease(this);
2007 BR.Register(useAfterRelease);
2008
2009 releaseNotOwned = new BadRelease(this);
2010 BR.Register(releaseNotOwned);
2011
2012 deallocGC = new DeallocGC(this);
2013 BR.Register(deallocGC);
2014
2015 deallocNotOwned = new DeallocNotOwned(this);
2016 BR.Register(deallocNotOwned);
2017
2018 // First register "return" leaks.
2019 const char* name = 0;
2020
2021 if (isGCEnabled())
2022 name = "Leak of returned object when using garbage collection";
2023 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2024 name = "Leak of returned object when not using garbage collection (GC) in "
2025 "dual GC/non-GC code";
2026 else {
2027 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2028 name = "Leak of returned object";
2029 }
2030
2031 leakAtReturn = new LeakAtReturn(this, name);
2032 BR.Register(leakAtReturn);
2033
2034 // Second, register leaks within a function/method.
2035 if (isGCEnabled())
2036 name = "Leak of object when using garbage collection";
2037 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2038 name = "Leak of object when not using garbage collection (GC) in "
2039 "dual GC/non-GC code";
2040 else {
2041 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2042 name = "Leak";
2043 }
2044
2045 leakWithinFunction = new LeakWithinFunction(this, name);
2046 BR.Register(leakWithinFunction);
2047
2048 // Save the reference to the BugReporter.
2049 this->BR = &BR;
2050}
2051
2052static const char* Msgs[] = {
2053 // GC only
2054 "Code is compiled to only use garbage collection",
2055 // No GC.
2056 "Code is compiled to use reference counts",
2057 // Hybrid, with GC.
2058 "Code is compiled to use either garbage collection (GC) or reference counts"
2059 " (non-GC). The bug occurs with GC enabled",
2060 // Hybrid, without GC
2061 "Code is compiled to use either garbage collection (GC) or reference counts"
2062 " (non-GC). The bug occurs in non-GC mode"
2063};
2064
2065std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2066 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2067
2068 switch (TF.getLangOptions().getGCMode()) {
2069 default:
2070 assert(false);
2071
2072 case LangOptions::GCOnly:
2073 assert (TF.isGCEnabled());
2074 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2075
2076 case LangOptions::NonGC:
2077 assert (!TF.isGCEnabled());
2078 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2079
2080 case LangOptions::HybridGC:
2081 if (TF.isGCEnabled())
2082 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2083 else
2084 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2085 }
2086}
2087
2088static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2089 ArgEffect X) {
2090 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2091 I!=E; ++I)
2092 if (*I == X) return true;
2093
2094 return false;
2095}
2096
2097PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2098 const ExplodedNode<GRState>* PrevN,
2099 const ExplodedGraph<GRState>& G,
2100 BugReporter& BR,
2101 NodeResolver& NR) {
2102
2103 // Check if the type state has changed.
2104 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2105 GRStateRef PrevSt(PrevN->getState(), StMgr);
2106 GRStateRef CurrSt(N->getState(), StMgr);
2107
2108 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2109 if (!CurrT) return NULL;
2110
2111 const RefVal& CurrV = *CurrT;
2112 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2113
2114 // Create a string buffer to constain all the useful things we want
2115 // to tell the user.
2116 std::string sbuf;
2117 llvm::raw_string_ostream os(sbuf);
2118
2119 // This is the allocation site since the previous node had no bindings
2120 // for this symbol.
2121 if (!PrevT) {
2122 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2123
2124 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2125 // Get the name of the callee (if it is available).
2126 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2127 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2128 os << "Call to function '" << FD->getNameAsString() <<'\'';
2129 else
2130 os << "function call";
2131 }
2132 else {
2133 assert (isa<ObjCMessageExpr>(S));
2134 os << "Method";
2135 }
2136
2137 if (CurrV.getObjKind() == RetEffect::CF) {
2138 os << " returns a Core Foundation object with a ";
2139 }
2140 else {
2141 assert (CurrV.getObjKind() == RetEffect::ObjC);
2142 os << " returns an Objective-C object with a ";
2143 }
2144
2145 if (CurrV.isOwned()) {
2146 os << "+1 retain count (owning reference).";
2147
2148 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2149 assert(CurrV.getObjKind() == RetEffect::CF);
2150 os << " "
2151 "Core Foundation objects are not automatically garbage collected.";
2152 }
2153 }
2154 else {
2155 assert (CurrV.isNotOwned());
2156 os << "+0 retain count (non-owning reference).";
2157 }
2158
2159 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2160 return new PathDiagnosticEventPiece(Pos, os.str());
2161 }
2162
2163 // Gather up the effects that were performed on the object at this
2164 // program point
2165 llvm::SmallVector<ArgEffect, 2> AEffects;
2166
2167 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2168 // We only have summaries attached to nodes after evaluating CallExpr and
2169 // ObjCMessageExprs.
2170 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2171
2172 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2173 // Iterate through the parameter expressions and see if the symbol
2174 // was ever passed as an argument.
2175 unsigned i = 0;
2176
2177 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2178 AI!=AE; ++AI, ++i) {
2179
2180 // Retrieve the value of the argument. Is it the symbol
2181 // we are interested in?
2182 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2183 continue;
2184
2185 // We have an argument. Get the effect!
2186 AEffects.push_back(Summ->getArg(i));
2187 }
2188 }
2189 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2190 if (Expr *receiver = ME->getReceiver())
2191 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2192 // The symbol we are tracking is the receiver.
2193 AEffects.push_back(Summ->getReceiverEffect());
2194 }
2195 }
2196 }
2197
2198 do {
2199 // Get the previous type state.
2200 RefVal PrevV = *PrevT;
2201
2202 // Specially handle -dealloc.
2203 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2204 // Determine if the object's reference count was pushed to zero.
2205 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2206 // We may not have transitioned to 'release' if we hit an error.
2207 // This case is handled elsewhere.
2208 if (CurrV.getKind() == RefVal::Released) {
2209 assert(CurrV.getCount() == 0);
2210 os << "Object released by directly sending the '-dealloc' message";
2211 break;
2212 }
2213 }
2214
2215 // Specially handle CFMakeCollectable and friends.
2216 if (contains(AEffects, MakeCollectable)) {
2217 // Get the name of the function.
2218 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2219 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2220 const FunctionDecl* FD = X.getAsFunctionDecl();
2221 const std::string& FName = FD->getNameAsString();
2222
2223 if (TF.isGCEnabled()) {
2224 // Determine if the object's reference count was pushed to zero.
2225 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2226
2227 os << "In GC mode a call to '" << FName
2228 << "' decrements an object's retain count and registers the "
2229 "object with the garbage collector. ";
2230
2231 if (CurrV.getKind() == RefVal::Released) {
2232 assert(CurrV.getCount() == 0);
2233 os << "Since it now has a 0 retain count the object can be "
2234 "automatically collected by the garbage collector.";
2235 }
2236 else
2237 os << "An object must have a 0 retain count to be garbage collected. "
2238 "After this call its retain count is +" << CurrV.getCount()
2239 << '.';
2240 }
2241 else
2242 os << "When GC is not enabled a call to '" << FName
2243 << "' has no effect on its argument.";
2244
2245 // Nothing more to say.
2246 break;
2247 }
2248
2249 // Determine if the typestate has changed.
2250 if (!(PrevV == CurrV))
2251 switch (CurrV.getKind()) {
2252 case RefVal::Owned:
2253 case RefVal::NotOwned:
2254
2255 if (PrevV.getCount() == CurrV.getCount())
2256 return 0;
2257
2258 if (PrevV.getCount() > CurrV.getCount())
2259 os << "Reference count decremented.";
2260 else
2261 os << "Reference count incremented.";
2262
2263 if (unsigned Count = CurrV.getCount())
2264 os << " The object now has a +" << Count << " retain count.";
2265
2266 if (PrevV.getKind() == RefVal::Released) {
2267 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2268 os << " The object is not eligible for garbage collection until the "
2269 "retain count reaches 0 again.";
2270 }
2271
2272 break;
2273
2274 case RefVal::Released:
2275 os << "Object released.";
2276 break;
2277
2278 case RefVal::ReturnedOwned:
2279 os << "Object returned to caller as an owning reference (single retain "
2280 "count transferred to caller).";
2281 break;
2282
2283 case RefVal::ReturnedNotOwned:
2284 os << "Object returned to caller with a +0 (non-owning) retain count.";
2285 break;
2286
2287 default:
2288 return NULL;
2289 }
2290
2291 // Emit any remaining diagnostics for the argument effects (if any).
2292 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2293 E=AEffects.end(); I != E; ++I) {
2294
2295 // A bunch of things have alternate behavior under GC.
2296 if (TF.isGCEnabled())
2297 switch (*I) {
2298 default: break;
2299 case Autorelease:
2300 os << "In GC mode an 'autorelease' has no effect.";
2301 continue;
2302 case IncRefMsg:
2303 os << "In GC mode the 'retain' message has no effect.";
2304 continue;
2305 case DecRefMsg:
2306 os << "In GC mode the 'release' message has no effect.";
2307 continue;
2308 }
2309 }
2310 } while(0);
2311
2312 if (os.str().empty())
2313 return 0; // We have nothing to say!
2314
2315 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2316 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2317 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2318
2319 // Add the range by scanning the children of the statement for any bindings
2320 // to Sym.
2321 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2322 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2323 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2324 P->addRange(Exp->getSourceRange());
2325 break;
2326 }
2327
2328 return P;
2329}
2330
2331namespace {
2332 class VISIBILITY_HIDDEN FindUniqueBinding :
2333 public StoreManager::BindingsHandler {
2334 SymbolRef Sym;
2335 const MemRegion* Binding;
2336 bool First;
2337
2338 public:
2339 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2340
2341 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2342 SVal val) {
2343
2344 SymbolRef SymV = val.getAsSymbol();
2345 if (!SymV || SymV != Sym)
2346 return true;
2347
2348 if (Binding) {
2349 First = false;
2350 return false;
2351 }
2352 else
2353 Binding = R;
2354
2355 return true;
2356 }
2357
2358 operator bool() { return First && Binding; }
2359 const MemRegion* getRegion() { return Binding; }
2360 };
2361}
2362
2363static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2364GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2365 SymbolRef Sym) {
2366
2367 // Find both first node that referred to the tracked symbol and the
2368 // memory location that value was store to.
2369 const ExplodedNode<GRState>* Last = N;
2370 const MemRegion* FirstBinding = 0;
2371
2372 while (N) {
2373 const GRState* St = N->getState();
2374 RefBindings B = St->get<RefBindings>();
2375
2376 if (!B.lookup(Sym))
2377 break;
2378
2379 FindUniqueBinding FB(Sym);
2380 StateMgr.iterBindings(St, FB);
2381 if (FB) FirstBinding = FB.getRegion();
2382
2383 Last = N;
2384 N = N->pred_empty() ? NULL : *(N->pred_begin());
2385 }
2386
2387 return std::make_pair(Last, FirstBinding);
2388}
2389
2390PathDiagnosticPiece*
2391CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
2392 // Tell the BugReporter to report cases when the tracked symbol is
2393 // assigned to different variables, etc.
2394 GRBugReporter& BR = cast<GRBugReporter>(br);
2395 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2396 return RangedBugReport::getEndPath(BR, EndN);
2397}
2398
2399PathDiagnosticPiece*
2400CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2401
2402 GRBugReporter& BR = cast<GRBugReporter>(br);
2403 // Tell the BugReporter to report cases when the tracked symbol is
2404 // assigned to different variables, etc.
2405 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2406
2407 // We are reporting a leak. Walk up the graph to get to the first node where
2408 // the symbol appeared, and also get the first VarDecl that tracked object
2409 // is stored to.
2410 const ExplodedNode<GRState>* AllocNode = 0;
2411 const MemRegion* FirstBinding = 0;
2412
2413 llvm::tie(AllocNode, FirstBinding) =
2414 GetAllocationSite(BR.getStateManager(), EndN, Sym);
2415
2416 // Get the allocate site.
2417 assert(AllocNode);
2418 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2419
2420 SourceManager& SMgr = BR.getContext().getSourceManager();
2421 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2422
2423 // Compute an actual location for the leak. Sometimes a leak doesn't
2424 // occur at an actual statement (e.g., transition between blocks; end
2425 // of function) so we need to walk the graph and compute a real location.
2426 const ExplodedNode<GRState>* LeakN = EndN;
2427 PathDiagnosticLocation L;
2428
2429 while (LeakN) {
2430 ProgramPoint P = LeakN->getLocation();
2431
2432 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2433 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2434 break;
2435 }
2436 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2437 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2438 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2439 break;
2440 }
2441 }
2442
2443 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2444 }
2445
2446 if (!L.isValid()) {
Ted Kremenek0a6913d2009-04-29 21:31:59 +00002447 const Decl &D = BR.getStateManager().getCodeDecl();
2448 L = PathDiagnosticLocation(D.getBodyRBrace(BR.getContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002449 }
2450
2451 std::string sbuf;
2452 llvm::raw_string_ostream os(sbuf);
2453
2454 os << "Object allocated on line " << AllocLine;
2455
2456 if (FirstBinding)
2457 os << " and stored into '" << FirstBinding->getString() << '\'';
2458
2459 // Get the retain count.
2460 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2461
2462 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2463 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2464 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2465 // to the caller for NS objects.
2466 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2467 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002468 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002469 << "') does not contain 'copy' or otherwise starts with"
2470 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002471 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002472 }
2473 else
2474 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002475 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002476
2477 return new PathDiagnosticEventPiece(L, os.str());
2478}
2479
2480
2481CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2482 ExplodedNode<GRState> *n,
2483 SymbolRef sym, GRExprEngine& Eng)
2484: CFRefReport(D, tf, n, sym)
2485{
2486
2487 // Most bug reports are cached at the location where they occured.
2488 // With leaks, we want to unique them by the location where they were
2489 // allocated, and only report a single path. To do this, we need to find
2490 // the allocation site of a piece of tracked memory, which we do via a
2491 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2492 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2493 // that all ancestor nodes that represent the allocation site have the
2494 // same SourceLocation.
2495 const ExplodedNode<GRState>* AllocNode = 0;
2496
2497 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2498 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2499
2500 // Get the SourceLocation for the allocation site.
2501 ProgramPoint P = AllocNode->getLocation();
2502 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2503
2504 // Fill in the description of the bug.
2505 Description.clear();
2506 llvm::raw_string_ostream os(Description);
2507 SourceManager& SMgr = Eng.getContext().getSourceManager();
2508 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
2509 os << "Potential leak of object allocated on line " << AllocLine;
2510
2511 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2512 if (AllocBinding)
2513 os << " and stored into '" << AllocBinding->getString() << '\'';
2514}
2515
2516//===----------------------------------------------------------------------===//
2517// Main checker logic.
2518//===----------------------------------------------------------------------===//
2519
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002520static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002521 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00002522}
2523
Ted Kremenek266d8b62008-05-06 02:26:56 +00002524static inline RetEffect GetRetEffect(RetainSummary* Summ) {
2525 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00002526}
2527
Ted Kremenek227c5372008-05-06 02:41:27 +00002528static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
2529 return Summ ? Summ->getReceiverEffect() : DoNothing;
2530}
2531
Ted Kremenekf2717b02008-07-18 17:24:20 +00002532static inline bool IsEndPath(RetainSummary* Summ) {
2533 return Summ ? Summ->isEndPath() : false;
2534}
2535
Ted Kremenek1feab292008-04-16 04:28:53 +00002536
Ted Kremenek272aa852008-06-25 21:21:56 +00002537/// GetReturnType - Used to get the return type of a message expression or
2538/// function call with the intention of affixing that type to a tracked symbol.
2539/// While the the return type can be queried directly from RetEx, when
2540/// invoking class methods we augment to the return type to be that of
2541/// a pointer to the class (as opposed it just being id).
2542static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2543
2544 QualType RetTy = RetE->getType();
2545
2546 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002547 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002548 if (!PT)
2549 return RetTy;
2550
2551 // If RetEx is not a message expression just return its type.
2552 // If RetEx is a message expression, return its types if it is something
2553 /// more specific than id.
2554
2555 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2556
Steve Naroff17c03822009-02-12 17:52:19 +00002557 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002558 return RetTy;
2559
2560 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2561
2562 // At this point we know the return type of the message expression is id.
2563 // If we have an ObjCInterceDecl, we know this is a call to a class method
2564 // whose type we can resolve. In such cases, promote the return type to
2565 // Class*.
2566 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2567}
2568
2569
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002570void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002571 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002572 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002573 Expr* Ex,
2574 Expr* Receiver,
2575 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002576 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002577 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002578
Ted Kremeneka7338b42008-03-11 06:39:11 +00002579 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002580 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002581 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002582
2583 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002584 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002585 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002586 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002587 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002588
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002589 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002590 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002591 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002592
Ted Kremenek74556a12009-03-26 03:35:11 +00002593 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002594 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
2595 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
2596 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002597 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002598 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002599 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002600 }
2601 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002602 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002603
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002604 if (isa<Loc>(V)) {
2605 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00002606 if (GetArgE(Summ, idx) == DoNothingByRef)
2607 continue;
2608
2609 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002610
2611 // FIXME: Either this logic should also be replicated in GRSimpleVals
2612 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002613
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002614 // FIXME: We can have collisions on the conjured symbol if the
2615 // expression *I also creates conjured symbols. We probably want
2616 // to identify conjured symbols by an expression pair: the enclosing
2617 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002618 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002619
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002620 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002621
Ted Kremenek53b24182009-03-04 22:56:43 +00002622 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002623 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002624 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002625
Ted Kremenek53b24182009-03-04 22:56:43 +00002626 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002627 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002628
Ted Kremenek53b24182009-03-04 22:56:43 +00002629 if (R->isBoundable(Ctx)) {
2630 // Set the value of the variable to be a conjured symbol.
2631 unsigned Count = Builder.getCurrentBlockCount();
2632 QualType T = R->getRValueType(Ctx);
2633
Zhongxing Xu079dc352009-04-09 06:03:54 +00002634 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002635 ValueManager &ValMgr = Eng.getValueManager();
2636 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002637 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002638 }
2639 else if (const RecordType *RT = T->getAsStructureType()) {
2640 // Handle structs in a not so awesome way. Here we just
2641 // eagerly bind new symbols to the fields. In reality we
2642 // should have the store manager handle this. The idea is just
2643 // to prototype some basic functionality here. All of this logic
2644 // should one day soon just go away.
2645 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2646
2647 // No record definition. There is nothing we can do.
2648 if (!RD)
2649 continue;
2650
2651 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2652
2653 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002654 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2655 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002656
2657 // For now just handle scalar fields.
2658 FieldDecl *FD = *FI;
2659 QualType FT = FD->getType();
2660
2661 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002662 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002663 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002664 ValueManager &ValMgr = Eng.getValueManager();
2665 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002666 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002667 }
2668 }
2669 }
2670 else {
2671 // Just blast away other values.
2672 state = state.BindLoc(*MR, UnknownVal());
2673 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002674 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002675 }
2676 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002677 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002678 }
2679 else {
2680 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002681 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002682 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002683 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002684 else if (isa<nonloc::LocAsInteger>(V))
2685 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002686 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002687
Ted Kremenek272aa852008-06-25 21:21:56 +00002688 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002689 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002690 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002691 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002692 if (const RefVal* T = state.get<RefBindings>(Sym)) {
2693 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
2694 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002695 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002696 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002697 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002698 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002699 }
2700 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002701
Ted Kremenek272aa852008-06-25 21:21:56 +00002702 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002703 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002704 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002705 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002706 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002707 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002708
Ted Kremenekf2717b02008-07-18 17:24:20 +00002709 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00002710 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002711
2712 switch (RE.getKind()) {
2713 default:
2714 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002715
Ted Kremenek8f90e712008-10-17 22:23:12 +00002716 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002717
Ted Kremenek455dd862008-04-11 20:23:24 +00002718 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002719 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2720 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002721
Ted Kremenek8f90e712008-10-17 22:23:12 +00002722 // FIXME: We eventually should handle structs and other compound types
2723 // that are returned by value.
2724
2725 QualType T = Ex->getType();
2726
Ted Kremenek79413a52008-11-13 06:10:40 +00002727 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002728 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002729 ValueManager &ValMgr = Eng.getValueManager();
2730 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002731 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002732 }
2733
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002734 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002735 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002736
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002737 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002738 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002739 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002740 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002741 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002742 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002743 break;
2744 }
2745
Ted Kremenek227c5372008-05-06 02:41:27 +00002746 case RetEffect::ReceiverAlias: {
2747 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002748 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002749 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002750 break;
2751 }
2752
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002753 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002754 case RetEffect::OwnedSymbol: {
2755 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002756 ValueManager &ValMgr = Eng.getValueManager();
2757 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2758 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2759 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2760 RetT));
2761 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002762
2763 // FIXME: Add a flag to the checker where allocations are assumed to
2764 // *not fail.
2765#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002766 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2767 bool isFeasible;
2768 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2769 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2770 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002771#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002772
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002773 break;
2774 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002775
2776 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002777 case RetEffect::NotOwnedSymbol: {
2778 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002779 ValueManager &ValMgr = Eng.getValueManager();
2780 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2781 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2782 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2783 RetT));
2784 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002785 break;
2786 }
2787 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002788
Ted Kremenek0dd65012009-02-18 02:00:25 +00002789 // Generate a sink node if we are at the end of a path.
2790 GRExprEngine::NodeTy *NewNode =
2791 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2792 : Builder.MakeNode(Dst, Ex, Pred, state);
2793
2794 // Annotate the edge with summary we used.
2795 // FIXME: This assumes that we always use the same summary when generating
2796 // this node.
2797 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002798}
2799
2800
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002801void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002802 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002803 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002804 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002805 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002806 const FunctionDecl* FD = L.getAsFunctionDecl();
2807 RetainSummary* Summ = !FD ? 0
2808 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002809
2810 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2811 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002812}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002813
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002814void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002815 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002816 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002817 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002818 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002819 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002820
Ted Kremenek272aa852008-06-25 21:21:56 +00002821 if (Expr* Receiver = ME->getReceiver()) {
2822 // We need the type-information of the tracked receiver object
2823 // Retrieve it from the state.
2824 ObjCInterfaceDecl* ID = 0;
2825
2826 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2827 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002828 // FIXME: Is this really working as expected? There are cases where
2829 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002830 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002831 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002832
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002833 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002834 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002835 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002836 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002837
2838 if (const PointerType* PT = Ty->getAsPointerType()) {
2839 QualType PointeeTy = PT->getPointeeType();
2840
2841 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2842 ID = IT->getDecl();
2843 }
2844 }
2845 }
2846
Ted Kremenek04e00302009-04-29 17:09:14 +00002847 // FIXME: The receiver could be a reference to a class, meaning that
2848 // we should use the class method.
2849 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002850
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002851 // Special-case: are we sending a mesage to "self"?
2852 // This is a hack. When we have full-IP this should be removed.
2853 if (!Summ) {
2854 ObjCMethodDecl* MD =
2855 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2856
2857 if (MD) {
2858 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002859 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002860 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002861 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2862 // Create a summmary where all of the arguments "StopTracking".
2863 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2864 DoNothing,
2865 StopTracking);
2866 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002867 }
2868 }
2869 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002870 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002871 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002872 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002873
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002874
Ted Kremenek926abf22008-05-06 04:20:12 +00002875 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2876 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002877}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002878
2879namespace {
2880class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2881 GRStateRef state;
2882public:
2883 StopTrackingCallback(GRStateRef st) : state(st) {}
2884 GRStateRef getState() { return state; }
2885
2886 bool VisitSymbol(SymbolRef sym) {
2887 state = state.remove<RefBindings>(sym);
2888 return true;
2889 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002890
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002891 const GRState* getState() const { return state.getState(); }
2892};
2893} // end anonymous namespace
2894
2895
Ted Kremeneka42be302009-02-14 01:43:44 +00002896void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002897 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002898 bool escapes = false;
2899
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002900 // A value escapes in three possible cases (this may change):
2901 //
2902 // (1) we are binding to something that is not a memory region.
2903 // (2) we are binding to a memregion that does not have stack storage
2904 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002905 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002906 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002907
Ted Kremeneka42be302009-02-14 01:43:44 +00002908 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002909 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002910 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002911 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2912 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002913
2914 if (!escapes) {
2915 // To test (3), generate a new state with the binding removed. If it is
2916 // the same state, then it escapes (since the store cannot represent
2917 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002918 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002919 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002920 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002921
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002922 // If our store can represent the binding and we aren't storing to something
2923 // that doesn't have local storage then just return and have the simulation
2924 // state continue as is.
2925 if (!escapes)
2926 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002927
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002928 // Otherwise, find all symbols referenced by 'val' that we are tracking
2929 // and stop tracking them.
2930 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002931}
2932
Ted Kremenek0106e202008-10-24 20:32:50 +00002933std::pair<GRStateRef,bool>
2934CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2935 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002936 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002937 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002938
Ted Kremenek47a72422009-04-29 18:50:19 +00002939 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002940 hasLeak = V.isOwned() ||
2941 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002942
Ted Kremenek47a72422009-04-29 18:50:19 +00002943 GRStateRef state(St, VMgr);
2944
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002945 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002946 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002947
Ted Kremenek0106e202008-10-24 20:32:50 +00002948 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2949 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002950}
2951
Ted Kremenek541db372008-04-24 23:57:27 +00002952
Ted Kremenekffefc352008-04-11 22:25:11 +00002953
Ted Kremenek541db372008-04-24 23:57:27 +00002954// Dead symbols.
2955
Ted Kremenek708af042009-02-05 06:50:21 +00002956
Ted Kremenek541db372008-04-24 23:57:27 +00002957
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002958 // Return statements.
2959
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002960void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002961 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002962 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002963 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002964 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002965
2966 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002967 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002968 return;
2969
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002970 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002971 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002972
Ted Kremenek74556a12009-03-26 03:35:11 +00002973 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002974 return;
2975
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002976 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002977 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002978
2979 if (!T)
2980 return;
2981
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002982 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002983 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002984
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002985 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002986 case RefVal::Owned: {
2987 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002988 assert (cnt > 0);
2989 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002990 break;
2991 }
2992
2993 case RefVal::NotOwned: {
2994 unsigned cnt = X.getCount();
2995 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2996 : RefVal::makeReturnedNotOwned();
2997 break;
2998 }
2999
3000 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003001 return;
3002 }
3003
3004 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003005 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003006 Pred = Builder.MakeNode(Dst, S, Pred, state);
3007
3008 // Any leaks or other errors?
3009 if (X.isReturnedOwned() && X.getCount() == 0) {
3010 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3011
Ted Kremenek314b1952009-04-29 23:03:22 +00003012 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3013 RetainSummary *Summ = Summaries.getMethodSummary(MD);
3014 if (!GetRetEffect(Summ).isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003015 static int ReturnOwnLeakTag = 0;
3016 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00003017 // Generate an error node.
3018 ExplodedNode<GRState> *N =
3019 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3020
3021 CFRefLeakReport *report =
3022 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3023 N, Sym, Eng);
3024 BR->EmitReport(report);
3025 }
3026 }
3027 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003028}
3029
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003030// Assumptions.
3031
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003032const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3033 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003034 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003035 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003036
3037 // FIXME: We may add to the interface of EvalAssume the list of symbols
3038 // whose assumptions have changed. For now we just iterate through the
3039 // bindings and check if any of the tracked symbols are NULL. This isn't
3040 // too bad since the number of symbols we will track in practice are
3041 // probably small and EvalAssume is only called at branches and a few
3042 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003043 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003044
3045 if (B.isEmpty())
3046 return St;
3047
3048 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003049
3050 GRStateRef state(St, VMgr);
3051 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003052
3053 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003054 // Check if the symbol is null (or equal to any constant).
3055 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003056 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003057 changed = true;
3058 B = RefBFactory.Remove(B, I.getKey());
3059 }
3060 }
3061
Ted Kremenek91781202008-08-17 03:20:02 +00003062 if (changed)
3063 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003064
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003065 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003066}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003067
Ted Kremenekb6578942009-02-24 19:15:11 +00003068GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3069 RefVal V, ArgEffect E,
3070 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003071
3072 // In GC mode [... release] and [... retain] do nothing.
3073 switch (E) {
3074 default: break;
3075 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3076 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003077 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003078 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3079 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003080 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003081
Ted Kremenek6537a642009-03-17 19:42:23 +00003082 // Handle all use-after-releases.
3083 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3084 V = V ^ RefVal::ErrorUseAfterRelease;
3085 hasErr = V.getKind();
3086 return state.set<RefBindings>(sym, V);
3087 }
3088
Ted Kremenek0d721572008-03-11 17:48:22 +00003089 switch (E) {
3090 default:
3091 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003092
3093 case Dealloc:
3094 // Any use of -dealloc in GC is *bad*.
3095 if (isGCEnabled()) {
3096 V = V ^ RefVal::ErrorDeallocGC;
3097 hasErr = V.getKind();
3098 break;
3099 }
3100
3101 switch (V.getKind()) {
3102 default:
3103 assert(false && "Invalid case.");
3104 case RefVal::Owned:
3105 // The object immediately transitions to the released state.
3106 V = V ^ RefVal::Released;
3107 V.clearCounts();
3108 return state.set<RefBindings>(sym, V);
3109 case RefVal::NotOwned:
3110 V = V ^ RefVal::ErrorDeallocNotOwned;
3111 hasErr = V.getKind();
3112 break;
3113 }
3114 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003115
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003116 case NewAutoreleasePool:
3117 assert(!isGCEnabled());
3118 return state.add<AutoreleaseStack>(sym);
3119
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003120 case MayEscape:
3121 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003122 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003123 break;
3124 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003125
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003126 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003127
Ted Kremenekede40b72008-07-09 18:11:16 +00003128 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003129 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003130 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003131
Ted Kremenek9b112d22009-01-28 21:44:40 +00003132 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003133 if (isGCEnabled())
3134 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003135
3136 // Update the autorelease counts.
3137 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003138
3139 // Fall-through.
3140
Ted Kremenek227c5372008-05-06 02:41:27 +00003141 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003142 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003143
Ted Kremenek0d721572008-03-11 17:48:22 +00003144 case IncRef:
3145 switch (V.getKind()) {
3146 default:
3147 assert(false);
3148
3149 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003150 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003151 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003152 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003153 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003154 // Non-GC cases are handled above.
3155 assert(isGCEnabled());
3156 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003157 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003158 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003159 break;
3160
Ted Kremenek272aa852008-06-25 21:21:56 +00003161 case SelfOwn:
3162 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003163 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003164 case DecRef:
3165 switch (V.getKind()) {
3166 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003167 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003168 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003169
Ted Kremenek272aa852008-06-25 21:21:56 +00003170 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003171 assert(V.getCount() > 0);
3172 if (V.getCount() == 1) V = V ^ RefVal::Released;
3173 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003174 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003175
Ted Kremenek272aa852008-06-25 21:21:56 +00003176 case RefVal::NotOwned:
3177 if (V.getCount() > 0)
3178 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003179 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003180 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003181 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003182 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003183 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003184
Ted Kremenek0d721572008-03-11 17:48:22 +00003185 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003186 // Non-GC cases are handled above.
3187 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003188 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003189 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003190 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003191 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003192 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003193 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003194 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003195}
3196
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003197//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003198// Handle dead symbols and end-of-path.
3199//===----------------------------------------------------------------------===//
3200
3201void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3202 GREndPathNodeBuilder<GRState>& Builder) {
3203
3204 const GRState* St = Builder.getState();
3205 RefBindings B = St->get<RefBindings>();
3206
3207 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3208 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3209
3210 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3211 bool hasLeak = false;
3212
3213 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003214 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3215 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003216
3217 St = X.first;
3218 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3219 }
3220
3221 if (Leaked.empty())
3222 return;
3223
3224 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3225
3226 if (!N)
3227 return;
3228
3229 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3230 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3231
3232 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3233 : leakWithinFunction);
3234 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003235 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003236 BR->EmitReport(report);
3237 }
3238}
3239
3240void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3241 GRExprEngine& Eng,
3242 GRStmtNodeBuilder<GRState>& Builder,
3243 ExplodedNode<GRState>* Pred,
3244 Stmt* S,
3245 const GRState* St,
3246 SymbolReaper& SymReaper) {
3247
Ted Kremenek876d8df2009-02-19 23:47:02 +00003248 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003249 RefBindings B = St->get<RefBindings>();
3250 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3251
3252 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3253 E = SymReaper.dead_end(); I != E; ++I) {
3254
3255 const RefVal* T = B.lookup(*I);
3256 if (!T) continue;
3257
3258 bool hasLeak = false;
3259
3260 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003261 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003262
3263 St = X.first;
3264
3265 if (hasLeak)
3266 Leaked.push_back(std::make_pair(*I,X.second));
3267 }
3268
Ted Kremenek876d8df2009-02-19 23:47:02 +00003269 if (!Leaked.empty()) {
3270 // Create a new intermediate node representing the leak point. We
3271 // use a special program point that represents this checker-specific
3272 // transition. We use the address of RefBIndex as a unique tag for this
3273 // checker. We will create another node (if we don't cache out) that
3274 // removes the retain-count bindings from the state.
3275 // NOTE: We use 'generateNode' so that it does interplay with the
3276 // auto-transition logic.
3277 ExplodedNode<GRState>* N =
3278 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003279
Ted Kremenek876d8df2009-02-19 23:47:02 +00003280 if (!N)
3281 return;
3282
3283 // Generate the bug reports.
3284 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3285 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3286
3287 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3288 : leakWithinFunction);
3289 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003290 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3291 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003292 BR->EmitReport(report);
3293 }
Ted Kremenek708af042009-02-05 06:50:21 +00003294
Ted Kremenek876d8df2009-02-19 23:47:02 +00003295 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003296 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003297
3298 // Now generate a new node that nukes the old bindings.
3299 GRStateRef state(St, Eng.getStateManager());
3300 RefBindings::Factory& F = state.get_context<RefBindings>();
3301
3302 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3303 E = SymReaper.dead_end(); I!=E; ++I)
3304 B = F.Remove(B, *I);
3305
3306 state = state.set<RefBindings>(B);
3307 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003308}
3309
3310void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3311 GRStmtNodeBuilder<GRState>& Builder,
3312 Expr* NodeExpr, Expr* ErrorExpr,
3313 ExplodedNode<GRState>* Pred,
3314 const GRState* St,
3315 RefVal::Kind hasErr, SymbolRef Sym) {
3316 Builder.BuildSinks = true;
3317 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3318
3319 if (!N) return;
3320
3321 CFRefBug *BT = 0;
3322
Ted Kremenek6537a642009-03-17 19:42:23 +00003323 switch (hasErr) {
3324 default:
3325 assert(false && "Unhandled error.");
3326 return;
3327 case RefVal::ErrorUseAfterRelease:
3328 BT = static_cast<CFRefBug*>(useAfterRelease);
3329 break;
3330 case RefVal::ErrorReleaseNotOwned:
3331 BT = static_cast<CFRefBug*>(releaseNotOwned);
3332 break;
3333 case RefVal::ErrorDeallocGC:
3334 BT = static_cast<CFRefBug*>(deallocGC);
3335 break;
3336 case RefVal::ErrorDeallocNotOwned:
3337 BT = static_cast<CFRefBug*>(deallocNotOwned);
3338 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003339 }
3340
Ted Kremenekc26c4692009-02-18 03:48:14 +00003341 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003342 report->addRange(ErrorExpr->getSourceRange());
3343 BR->EmitReport(report);
3344}
3345
3346//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003347// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003348//===----------------------------------------------------------------------===//
3349
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003350GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3351 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003352 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003353}