blob: 3816c560b3b97792b65626df6b9083e5bb5bcc0b [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 Kremenekfd42ffc2009-02-21 18:26:02 +0000122 if ((AtBeginning && StringsEqualNoCase("alloc", s, len)) ||
Ted Kremenekea5a6b02009-02-22 07:32:24 +0000123 (C == NoConvention && StringsEqualNoCase("copy", s, len)))
Ted Kremenek4395b452009-02-21 05:13:43 +0000124 C = CreateRule;
125 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000126 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000127 C = InitRule;
128 break;
129 }
130
131 // If we aren't in the prefix and have a derived convention then just
132 // return it now.
133 if (!InPossiblePrefix && C != NoConvention)
134 return C;
135
136 AtBeginning = false;
137 s = wordEnd;
138 }
139
140 // We will get here if there wasn't more than one word
141 // after the prefix.
142 return C;
143}
144
Ted Kremenekb6f09542008-10-24 21:18:08 +0000145static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000146 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000147}
148
149static bool followsReturnRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000150 NamingConvention C = deriveNamingConvention(s);
151 return C == CreateRule || C == InitRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000152}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000153
Ted Kremenek7d421f32008-04-09 23:49:11 +0000154//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000155// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000156//===----------------------------------------------------------------------===//
157
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000158static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000159 IdentifierInfo* II = &Ctx.Idents.get(name);
160 return Ctx.Selectors.getSelector(0, &II);
161}
162
Ted Kremenek0e344d42008-05-06 00:30:21 +0000163static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
164 IdentifierInfo* II = &Ctx.Idents.get(name);
165 return Ctx.Selectors.getSelector(1, &II);
166}
167
Ted Kremenek272aa852008-06-25 21:21:56 +0000168//===----------------------------------------------------------------------===//
169// Type querying functions.
170//===----------------------------------------------------------------------===//
171
Ted Kremenek17144e82009-01-12 21:45:02 +0000172static bool hasPrefix(const char* s, const char* prefix) {
173 if (!prefix)
174 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000175
Ted Kremenek17144e82009-01-12 21:45:02 +0000176 char c = *s;
177 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000178
Ted Kremenek17144e82009-01-12 21:45:02 +0000179 while (c != '\0' && cP != '\0') {
180 if (c != cP) break;
181 c = *(++s);
182 cP = *(++prefix);
183 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000184
Ted Kremenek17144e82009-01-12 21:45:02 +0000185 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000186}
187
Ted Kremenek17144e82009-01-12 21:45:02 +0000188static bool hasSuffix(const char* s, const char* suffix) {
189 const char* loc = strstr(s, suffix);
190 return loc && strcmp(suffix, loc) == 0;
191}
192
193static bool isRefType(QualType RetTy, const char* prefix,
194 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000195
Ted Kremenek17144e82009-01-12 21:45:02 +0000196 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
197 const char* TDName = TD->getDecl()->getIdentifier()->getName();
198 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
199 }
200
201 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000202 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000203
204 // Is the type void*?
205 const PointerType* PT = RetTy->getAsPointerType();
206 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000207 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000208
209 // Does the name start with the prefix?
210 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000211}
212
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000213//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000214// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000215//===----------------------------------------------------------------------===//
216
Ted Kremenek272aa852008-06-25 21:21:56 +0000217namespace {
218/// ArgEffect is used to summarize a function/method call's effect on a
219/// particular argument.
Ted Kremenek58dd95b2009-02-18 18:54:33 +0000220enum ArgEffect { IncRefMsg, IncRef,
221 DecRefMsg, DecRef,
Ted Kremenek2126bef2009-02-18 21:57:45 +0000222 MakeCollectable,
Ted Kremenek58dd95b2009-02-18 18:54:33 +0000223 DoNothing, DoNothingByRef,
Ted Kremenekede40b72008-07-09 18:11:16 +0000224 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek272aa852008-06-25 21:21:56 +0000225
226/// ArgEffects summarizes the effects of a function/method call on all of
227/// its arguments.
228typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000229}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000230
Ted Kremeneka7338b42008-03-11 06:39:11 +0000231namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000232template <> struct FoldingSetTrait<ArgEffects> {
233 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
234 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
235 ID.AddInteger(I->first);
236 ID.AddInteger((unsigned) I->second);
237 }
238 }
239};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000240} // end llvm namespace
241
242namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000243
244/// RetEffect is used to summarize a function/method call's behavior with
245/// respect to its return value.
246class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000247public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000248 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
249 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000250
251 enum ObjKind { CF, ObjC, AnyObj };
252
Ted Kremeneka7338b42008-03-11 06:39:11 +0000253private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000254 Kind K;
255 ObjKind O;
256 unsigned index;
257
258 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
259 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000260
Ted Kremeneka7338b42008-03-11 06:39:11 +0000261public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000262 Kind getKind() const { return K; }
263
264 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000265
266 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000267 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000268 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000269 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000270
Ted Kremenek272aa852008-06-25 21:21:56 +0000271 static RetEffect MakeAlias(unsigned Idx) {
272 return RetEffect(Alias, Idx);
273 }
274 static RetEffect MakeReceiverAlias() {
275 return RetEffect(ReceiverAlias);
276 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000277 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
278 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000279 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000280 static RetEffect MakeNotOwned(ObjKind o) {
281 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000282 }
283 static RetEffect MakeNoRet() {
284 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000285 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000286
Ted Kremenek272aa852008-06-25 21:21:56 +0000287 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000288 ID.AddInteger((unsigned)K);
289 ID.AddInteger((unsigned)O);
290 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000291 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000292};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000293
Ted Kremenek272aa852008-06-25 21:21:56 +0000294
295class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000296 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
297 /// specifies the argument (starting from 0). This can be sparsely
298 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000299 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000300
301 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
302 /// do not have an entry in Args.
303 ArgEffect DefaultArgEffect;
304
Ted Kremenek272aa852008-06-25 21:21:56 +0000305 /// Receiver - If this summary applies to an Objective-C message expression,
306 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000307 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000308
309 /// Ret - The effect on the return value. Used to indicate if the
310 /// function/method call returns a new tracked symbol, returns an
311 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000312 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000313
Ted Kremenekf2717b02008-07-18 17:24:20 +0000314 /// EndPath - Indicates that execution of this method/function should
315 /// terminate the simulation of a path.
316 bool EndPath;
317
Ted Kremeneka7338b42008-03-11 06:39:11 +0000318public:
319
Ted Kremenekbcaff792008-05-06 15:44:25 +0000320 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000321 ArgEffect ReceiverEff, bool endpath = false)
322 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
323 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000324
Ted Kremenek272aa852008-06-25 21:21:56 +0000325 /// getArg - Return the argument effect on the argument specified by
326 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000327 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000328
Ted Kremenekae855d42008-04-24 17:22:33 +0000329 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000330 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000331
332 // If Args is present, it is likely to contain only 1 element.
333 // Just do a linear search. Do it from the back because functions with
334 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000335 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000336 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
337 I!=E; ++I) {
338
339 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000340 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000341
342 if (idx == I->first)
343 return I->second;
344 }
345
Ted Kremenekbcaff792008-05-06 15:44:25 +0000346 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000347 }
348
Ted Kremenek272aa852008-06-25 21:21:56 +0000349 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000350 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000351 return Ret;
352 }
353
Ted Kremenekf2717b02008-07-18 17:24:20 +0000354 /// isEndPath - Returns true if executing the given method/function should
355 /// terminate the path.
356 bool isEndPath() const { return EndPath; }
357
Ted Kremenek272aa852008-06-25 21:21:56 +0000358 /// getReceiverEffect - Returns the effect on the receiver of the call.
359 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000360 ArgEffect getReceiverEffect() const {
361 return Receiver;
362 }
363
Ted Kremenek2719e982008-06-17 02:43:46 +0000364 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000365
Ted Kremenek2719e982008-06-17 02:43:46 +0000366 ExprIterator begin_args() const { return Args->begin(); }
367 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000368
Ted Kremenek266d8b62008-05-06 02:26:56 +0000369 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000370 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000371 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000372 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000373 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000374 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000375 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000376 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000377 }
378
379 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000380 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000381 }
382};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000383} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000384
Ted Kremenek272aa852008-06-25 21:21:56 +0000385//===----------------------------------------------------------------------===//
386// Data structures for constructing summaries.
387//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000388
Ted Kremenek272aa852008-06-25 21:21:56 +0000389namespace {
390class VISIBILITY_HIDDEN ObjCSummaryKey {
391 IdentifierInfo* II;
392 Selector S;
393public:
394 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
395 : II(ii), S(s) {}
396
397 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
398 : II(d ? d->getIdentifier() : 0), S(s) {}
399
400 ObjCSummaryKey(Selector s)
401 : II(0), S(s) {}
402
403 IdentifierInfo* getIdentifier() const { return II; }
404 Selector getSelector() const { return S; }
405};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000406}
407
408namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000409template <> struct DenseMapInfo<ObjCSummaryKey> {
410 static inline ObjCSummaryKey getEmptyKey() {
411 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
412 DenseMapInfo<Selector>::getEmptyKey());
413 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000414
Ted Kremenek272aa852008-06-25 21:21:56 +0000415 static inline ObjCSummaryKey getTombstoneKey() {
416 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
417 DenseMapInfo<Selector>::getTombstoneKey());
418 }
419
420 static unsigned getHashValue(const ObjCSummaryKey &V) {
421 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
422 & 0x88888888)
423 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
424 & 0x55555555);
425 }
426
427 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
428 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
429 RHS.getIdentifier()) &&
430 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
431 RHS.getSelector());
432 }
433
434 static bool isPod() {
435 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
436 DenseMapInfo<Selector>::isPod();
437 }
438};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000439} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000440
Ted Kremenek84f010c2008-06-23 23:30:29 +0000441namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000442class VISIBILITY_HIDDEN ObjCSummaryCache {
443 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
444 MapTy M;
445public:
446 ObjCSummaryCache() {}
447
448 typedef MapTy::iterator iterator;
449
450 iterator find(ObjCInterfaceDecl* D, Selector S) {
451
452 // Do a lookup with the (D,S) pair. If we find a match return
453 // the iterator.
454 ObjCSummaryKey K(D, S);
455 MapTy::iterator I = M.find(K);
456
457 if (I != M.end() || !D)
458 return I;
459
460 // Walk the super chain. If we find a hit with a parent, we'll end
461 // up returning that summary. We actually allow that key (null,S), as
462 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
463 // generate initial summaries without having to worry about NSObject
464 // being declared.
465 // FIXME: We may change this at some point.
466 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
467 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
468 break;
469
470 if (!C)
471 return I;
472 }
473
474 // Cache the summary with original key to make the next lookup faster
475 // and return the iterator.
476 M[K] = I->second;
477 return I;
478 }
479
Ted Kremenek9449ca92008-08-12 20:41:56 +0000480
Ted Kremenek272aa852008-06-25 21:21:56 +0000481 iterator find(Expr* Receiver, Selector S) {
482 return find(getReceiverDecl(Receiver), S);
483 }
484
485 iterator find(IdentifierInfo* II, Selector S) {
486 // FIXME: Class method lookup. Right now we dont' have a good way
487 // of going between IdentifierInfo* and the class hierarchy.
488 iterator I = M.find(ObjCSummaryKey(II, S));
489 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
490 }
491
492 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
493
494 const PointerType* PT = E->getType()->getAsPointerType();
495 if (!PT) return 0;
496
497 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
498 if (!OI) return 0;
499
500 return OI ? OI->getDecl() : 0;
501 }
502
503 iterator end() { return M.end(); }
504
505 RetainSummary*& operator[](ObjCMessageExpr* ME) {
506
507 Selector S = ME->getSelector();
508
509 if (Expr* Receiver = ME->getReceiver()) {
510 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
511 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
512 }
513
514 return M[ObjCSummaryKey(ME->getClassName(), S)];
515 }
516
517 RetainSummary*& operator[](ObjCSummaryKey K) {
518 return M[K];
519 }
520
521 RetainSummary*& operator[](Selector S) {
522 return M[ ObjCSummaryKey(S) ];
523 }
524};
525} // end anonymous namespace
526
527//===----------------------------------------------------------------------===//
528// Data structures for managing collections of summaries.
529//===----------------------------------------------------------------------===//
530
531namespace {
532class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000533
534 //==-----------------------------------------------------------------==//
535 // Typedefs.
536 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000537
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000538 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
539 ArgEffectsSetTy;
540
541 typedef llvm::FoldingSet<RetainSummary>
542 SummarySetTy;
543
544 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
545 FuncSummariesTy;
546
Ted Kremenek84f010c2008-06-23 23:30:29 +0000547 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000548
549 //==-----------------------------------------------------------------==//
550 // Data.
551 //==-----------------------------------------------------------------==//
552
Ted Kremenek272aa852008-06-25 21:21:56 +0000553 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000554 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000555
Ted Kremenekede40b72008-07-09 18:11:16 +0000556 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
557 /// "CFDictionaryCreate".
558 IdentifierInfo* CFDictionaryCreateII;
559
Ted Kremenek272aa852008-06-25 21:21:56 +0000560 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000561 const bool GCEnabled;
562
Ted Kremenek272aa852008-06-25 21:21:56 +0000563 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000564 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000565
Ted Kremenek272aa852008-06-25 21:21:56 +0000566 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000567 FuncSummariesTy FuncSummaries;
568
Ted Kremenek272aa852008-06-25 21:21:56 +0000569 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
570 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000571 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000572
Ted Kremenek272aa852008-06-25 21:21:56 +0000573 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000574 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000575
Ted Kremenek272aa852008-06-25 21:21:56 +0000576 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000577 ArgEffectsSetTy ArgEffectsSet;
578
Ted Kremenek272aa852008-06-25 21:21:56 +0000579 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
580 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000581 llvm::BumpPtrAllocator BPAlloc;
582
Ted Kremenek272aa852008-06-25 21:21:56 +0000583 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000584 ArgEffects ScratchArgs;
585
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000586 RetainSummary* StopSummary;
587
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000588 //==-----------------------------------------------------------------==//
589 // Methods.
590 //==-----------------------------------------------------------------==//
591
Ted Kremenek272aa852008-06-25 21:21:56 +0000592 /// getArgEffects - Returns a persistent ArgEffects object based on the
593 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000594 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000595
Ted Kremenek562c1302008-05-05 16:51:50 +0000596 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000597
598public:
Ted Kremenek17144e82009-01-12 21:45:02 +0000599 RetainSummary* getUnarySummary(FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000600
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000601 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
602 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000603 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000604
Ted Kremenek266d8b62008-05-06 02:26:56 +0000605 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000606 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000607 ArgEffect DefaultEff = MayEscape,
608 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000609
Ted Kremenek266d8b62008-05-06 02:26:56 +0000610 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000611 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000612 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000613 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000614 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000615
Ted Kremenekbcaff792008-05-06 15:44:25 +0000616 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000617 if (StopSummary)
618 return StopSummary;
619
620 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
621 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000622
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000623 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000624 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000625
Ted Kremenek272aa852008-06-25 21:21:56 +0000626 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000627
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000628 void InitializeClassMethodSummaries();
629 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000630
Ted Kremenek35920ed2009-01-07 00:39:56 +0000631 bool isTrackedObjectType(QualType T);
632
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000633private:
634
Ted Kremenekf2717b02008-07-18 17:24:20 +0000635 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
636 RetainSummary* Summ) {
637 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
638 }
639
Ted Kremenek272aa852008-06-25 21:21:56 +0000640 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
641 ObjCClassMethodSummaries[S] = Summ;
642 }
643
644 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
645 ObjCMethodSummaries[S] = Summ;
646 }
647
Ted Kremenek45642a42008-08-12 18:48:50 +0000648 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenekf2717b02008-07-18 17:24:20 +0000649
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000650 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
651 llvm::SmallVector<IdentifierInfo*, 10> II;
652
653 while (const char* s = va_arg(argp, const char*))
654 II.push_back(&Ctx.Idents.get(s));
655
656 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000657 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
658 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000659
660 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
661 va_list argp;
662 va_start(argp, Summ);
663 addInstMethSummary(Cls, Summ, argp);
664 va_end(argp);
665 }
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000666
667 void addPanicSummary(const char* Cls, ...) {
668 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
669 DoNothing, DoNothing, true);
670 va_list argp;
671 va_start (argp, Cls);
Ted Kremenek45642a42008-08-12 18:48:50 +0000672 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000673 va_end(argp);
674 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000675
Ted Kremeneka7338b42008-03-11 06:39:11 +0000676public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000677
678 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000679 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000680 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000681 GCEnabled(gcenabled), StopSummary(0) {
682
683 InitializeClassMethodSummaries();
684 InitializeMethodSummaries();
685 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000686
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000687 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000688
Ted Kremenekd13c1872008-06-24 03:56:45 +0000689 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000690 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000691 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenek926abf22008-05-06 04:20:12 +0000692
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000693 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000694};
695
696} // end anonymous namespace
697
698//===----------------------------------------------------------------------===//
699// Implementation of checker data structures.
700//===----------------------------------------------------------------------===//
701
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000702RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000703
704 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
705 // mitigating the need to do explicit cleanup of the
706 // Argument-Effect summaries.
707
Ted Kremenek42ea0322008-05-05 23:55:01 +0000708 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
709 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000710 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000711}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000712
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000713ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000714
Ted Kremenekae855d42008-04-24 17:22:33 +0000715 if (ScratchArgs.empty())
716 return NULL;
717
718 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000719 llvm::FoldingSetNodeID profile;
720 profile.Add(ScratchArgs);
721 void* InsertPos;
722
Ted Kremenekae855d42008-04-24 17:22:33 +0000723 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000724 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000725 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000726
Ted Kremenekae855d42008-04-24 17:22:33 +0000727 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000728 ScratchArgs.clear();
729 return &E->getValue();
730 }
731
732 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000733 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000734
735 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000736 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000737
738 ScratchArgs.clear();
739 return &E->getValue();
740}
741
Ted Kremenek266d8b62008-05-06 02:26:56 +0000742RetainSummary*
743RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000744 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000745 ArgEffect DefaultEff,
746 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000747
Ted Kremenekae855d42008-04-24 17:22:33 +0000748 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000749 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000750 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
751 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000752
Ted Kremenekae855d42008-04-24 17:22:33 +0000753 // Look up the uniqued summary, or create one if it doesn't exist.
754 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000755 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000756
757 if (Summ)
758 return Summ;
759
Ted Kremenekae855d42008-04-24 17:22:33 +0000760 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000761 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000762 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000763 SummarySet.InsertNode(Summ, InsertPos);
764
765 return Summ;
766}
767
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000768//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000769// Predicates.
770//===----------------------------------------------------------------------===//
771
772bool RetainSummaryManager::isTrackedObjectType(QualType T) {
773 if (!Ctx.isObjCObjectPointerType(T))
774 return false;
775
776 // Does it subclass NSObject?
777 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
778
779 // We assume that id<..>, id, and "Class" all represent tracked objects.
780 if (!OT)
781 return true;
782
783 // Does the object type subclass NSObject?
784 // FIXME: We can memoize here if this gets too expensive.
785 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
786 ObjCInterfaceDecl* ID = OT->getDecl();
787
788 for ( ; ID ; ID = ID->getSuperClass())
789 if (ID->getIdentifier() == NSObjectII)
790 return true;
791
792 return false;
793}
794
795//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000796// Summary creation for functions (largely uses of Core Foundation).
797//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000798
Ted Kremenek17144e82009-01-12 21:45:02 +0000799static bool isRetain(FunctionDecl* FD, const char* FName) {
800 const char* loc = strstr(FName, "Retain");
801 return loc && loc[sizeof("Retain")-1] == '\0';
802}
803
804static bool isRelease(FunctionDecl* FD, const char* FName) {
805 const char* loc = strstr(FName, "Release");
806 return loc && loc[sizeof("Release")-1] == '\0';
807}
808
Ted Kremenekd13c1872008-06-24 03:56:45 +0000809RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000810
811 SourceLocation Loc = FD->getLocation();
812
813 if (!Loc.isFileID())
814 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000815
Ted Kremenekae855d42008-04-24 17:22:33 +0000816 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000817 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000818
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000819 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000820 return I->second;
821
822 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000823 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000824
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000825 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000826 // We generate "stop" summaries for implicitly defined functions.
827 if (FD->isImplicit()) {
828 S = getPersistentStopSummary();
829 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000830 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000831
Ted Kremenekbfc629c2009-02-23 02:42:56 +0000832 // [PR 3337] Use 'getDesugaredType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000833 // function's type.
834 FunctionType* FT = cast<FunctionType>(FD->getType()->getDesugaredType());
Ted Kremenek17144e82009-01-12 21:45:02 +0000835 const char* FName = FD->getIdentifier()->getName();
836
837 // Inspect the result type.
838 QualType RetTy = FT->getResultType();
839
840 // FIXME: This should all be refactored into a chain of "summary lookup"
841 // filters.
842 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
843 // FIXES: <rdar://problem/6326900>
844 // This should be addressed using a API table. This strcmp is also
845 // a little gross, but there is no need to super optimize here.
846 assert (ScratchArgs.empty());
847 ScratchArgs.push_back(std::make_pair(1, DecRef));
848 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
849 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000850 }
Ted Kremenek17144e82009-01-12 21:45:02 +0000851
852 // Handle: id NSMakeCollectable(CFTypeRef)
853 if (strcmp(FName, "NSMakeCollectable") == 0) {
854 S = (RetTy == Ctx.getObjCIdType())
855 ? getUnarySummary(FT, cfmakecollectable)
856 : getPersistentStopSummary();
857
858 break;
859 }
860
861 if (RetTy->isPointerType()) {
862 // For CoreFoundation ('CF') types.
863 if (isRefType(RetTy, "CF", &Ctx, FName)) {
864 if (isRetain(FD, FName))
865 S = getUnarySummary(FT, cfretain);
866 else if (strstr(FName, "MakeCollectable"))
867 S = getUnarySummary(FT, cfmakecollectable);
868 else
869 S = getCFCreateGetRuleSummary(FD, FName);
870
871 break;
872 }
873
874 // For CoreGraphics ('CG') types.
875 if (isRefType(RetTy, "CG", &Ctx, FName)) {
876 if (isRetain(FD, FName))
877 S = getUnarySummary(FT, cfretain);
878 else
879 S = getCFCreateGetRuleSummary(FD, FName);
880
881 break;
882 }
883
884 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
885 if (isRefType(RetTy, "DADisk") ||
886 isRefType(RetTy, "DADissenter") ||
887 isRefType(RetTy, "DASessionRef")) {
888 S = getCFCreateGetRuleSummary(FD, FName);
889 break;
890 }
891
892 break;
893 }
894
895 // Check for release functions, the only kind of functions that we care
896 // about that don't return a pointer type.
897 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
898 if (isRelease(FD, FName+2))
899 S = getUnarySummary(FT, cfrelease);
900 else {
Ted Kremenek7b293682009-01-29 22:45:13 +0000901 assert (ScratchArgs.empty());
902 // Remaining CoreFoundation and CoreGraphics functions.
903 // We use to assume that they all strictly followed the ownership idiom
904 // and that ownership cannot be transferred. While this is technically
905 // correct, many methods allow a tracked object to escape. For example:
906 //
907 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
908 // CFDictionaryAddValue(y, key, x);
909 // CFRelease(x);
910 // ... it is okay to use 'x' since 'y' has a reference to it
911 //
912 // We handle this and similar cases with the follow heuristic. If the
913 // function name contains "InsertValue", "SetValue" or "AddValue" then
914 // we assume that arguments may "escape."
915 //
916 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
917 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000918 CStrInCStrNoCase(FName, "SetValue") ||
919 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000920 ? MayEscape : DoNothing;
921
922 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000923 }
924 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000925 }
926 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000927
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000928 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000929 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000930}
931
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000932RetainSummary*
933RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
934 const char* FName) {
935
Ted Kremenek562c1302008-05-05 16:51:50 +0000936 if (strstr(FName, "Create") || strstr(FName, "Copy"))
937 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000938
Ted Kremenek562c1302008-05-05 16:51:50 +0000939 if (strstr(FName, "Get"))
940 return getCFSummaryGetRule(FD);
941
942 return 0;
943}
944
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000945RetainSummary*
Ted Kremenek17144e82009-01-12 21:45:02 +0000946RetainSummaryManager::getUnarySummary(FunctionType* FT, UnaryFuncKind func) {
947 // Sanity check that this is *really* a unary function. This can
948 // happen if people do weird things.
949 FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FT);
950 if (!FTP || FTP->getNumArgs() != 1)
951 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000952
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000953 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000954
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000955 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +0000956 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000957 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000958 return getPersistentSummary(RetEffect::MakeAlias(0),
959 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000960 }
961
962 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000963 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000964 return getPersistentSummary(RetEffect::MakeNoRet(),
965 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000966 }
967
968 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +0000969 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
970 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000971 }
972
973 default:
Ted Kremenek562c1302008-05-05 16:51:50 +0000974 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +0000975 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +0000976 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000977}
978
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000979RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000980 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +0000981
982 if (FD->getIdentifier() == CFDictionaryCreateII) {
983 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
984 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
985 }
986
Ted Kremenek68621b92009-01-28 05:56:51 +0000987 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000988}
989
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000990RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000991 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +0000992 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
993 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000994}
995
Ted Kremeneka7338b42008-03-11 06:39:11 +0000996//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000997// Summary creation for Selectors.
998//===----------------------------------------------------------------------===//
999
Ted Kremenekbcaff792008-05-06 15:44:25 +00001000RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001001RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001002 assert(ScratchArgs.empty());
1003
Ted Kremenek802cfc72009-02-20 00:05:35 +00001004 // 'init' methods only return an alias if the return type is a location type.
1005 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001006 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +00001007 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1008 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001009
Ted Kremenek272aa852008-06-25 21:21:56 +00001010 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001011 return Summ;
1012}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001013
Ted Kremenek272aa852008-06-25 21:21:56 +00001014
Ted Kremenekbcaff792008-05-06 15:44:25 +00001015RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001016RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1017 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001018
1019 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001020
Ted Kremenek272aa852008-06-25 21:21:56 +00001021 // Look up a summary in our summary cache.
1022 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001023
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001024 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001025 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001026
Ted Kremenek35920ed2009-01-07 00:39:56 +00001027 // "initXXX": pass-through for receiver.
Ted Kremenek42ea0322008-05-05 23:55:01 +00001028 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001029 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001030
Ted Kremenek4395b452009-02-21 05:13:43 +00001031 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek35920ed2009-01-07 00:39:56 +00001032 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +00001033
Ted Kremenek35920ed2009-01-07 00:39:56 +00001034 // Look for methods that return an owned object.
1035 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek5496f6d2008-05-07 04:25:59 +00001036 return 0;
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001037
Ted Kremenek35920ed2009-01-07 00:39:56 +00001038 if (followsFundamentalRule(s)) {
1039 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001040 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001041 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +00001042 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +00001043 return Summ;
1044 }
Ted Kremenekbcaff792008-05-06 15:44:25 +00001045
Ted Kremenek42ea0322008-05-05 23:55:01 +00001046 return 0;
1047}
1048
Ted Kremeneka7722b72008-05-06 21:26:51 +00001049RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001050RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1051 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +00001052
Ted Kremenek272aa852008-06-25 21:21:56 +00001053 // FIXME: Eventually we should properly do class method summaries, but
1054 // it requires us being able to walk the type hierarchy. Unfortunately,
1055 // we cannot do this with just an IdentifierInfo* for the class name.
1056
Ted Kremeneka7722b72008-05-06 21:26:51 +00001057 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +00001058 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001059
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001060 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001061 return I->second;
1062
Ted Kremenek4c479322008-05-06 23:07:13 +00001063 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001064}
1065
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001066void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001067
1068 assert (ScratchArgs.empty());
1069
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001070 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001071 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001072
Ted Kremenek0e344d42008-05-06 00:30:21 +00001073 RetainSummary* Summ = getPersistentSummary(E);
1074
Ted Kremenek272aa852008-06-25 21:21:56 +00001075 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1076 // NSObject and its derivatives.
1077 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1078 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1079 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001080
1081 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001082 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001083 GetNullarySelector("currentHandler", Ctx),
1084 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001085
1086 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001087 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1088 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1089 GetUnarySelector("addObject", Ctx),
1090 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001091 DoNothing, Autorelease));
Ted Kremenek0e344d42008-05-06 00:30:21 +00001092}
1093
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001094void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001095
1096 assert (ScratchArgs.empty());
1097
Ted Kremeneka7722b72008-05-06 21:26:51 +00001098 // Create the "init" selector. It just acts as a pass-through for the
1099 // receiver.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001100 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
1101 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001102
1103 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001104 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001105 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001106
Ted Kremeneke44927e2008-07-01 17:21:27 +00001107 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001108
1109 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001110 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1111
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001112 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001113 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001114
Ted Kremenek266d8b62008-05-06 02:26:56 +00001115 // Create the "retain" selector.
1116 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001117 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001118 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001119
1120 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001121 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001122 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001123
1124 // Create the "drain" selector.
1125 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001126 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001127
1128 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001129 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001130 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001131
Ted Kremenek45642a42008-08-12 18:48:50 +00001132 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001133 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1134 // self-own themselves. However, they only do this once they are displayed.
1135 // Thus, we need to track an NSWindow's display status.
1136 // This is tracked in <rdar://problem/6062711>.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001137 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001138 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001139
1140 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1141 "styleMask", "backing", "defer", NULL);
1142
1143 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1144 "styleMask", "backing", "defer", "screen", NULL);
1145
1146 // For NSPanel (which subclasses NSWindow), allocated objects are not
1147 // self-owned.
1148 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1149 "styleMask", "backing", "defer", NULL);
1150
1151 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1152 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001153
Ted Kremenekf2717b02008-07-18 17:24:20 +00001154 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001155 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1156 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001157
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001158 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1159 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001160}
1161
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001162//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001163// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001164//===----------------------------------------------------------------------===//
1165
Ted Kremeneka7338b42008-03-11 06:39:11 +00001166namespace {
1167
Ted Kremenek7d421f32008-04-09 23:49:11 +00001168class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001169public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001170 enum Kind {
1171 Owned = 0, // Owning reference.
1172 NotOwned, // Reference is not owned by still valid (not freed).
1173 Released, // Object has been released.
1174 ReturnedOwned, // Returned object passes ownership to caller.
1175 ReturnedNotOwned, // Return object does not pass ownership to caller.
1176 ErrorUseAfterRelease, // Object used after released.
1177 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek311f3d42008-10-22 23:56:21 +00001178 ErrorLeak, // A memory leak due to excessive reference counts.
1179 ErrorLeakReturned // A memory leak due to the returning method not having
1180 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001181 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001182
1183private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001184 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001185 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001186 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001187 QualType T;
1188
Ted Kremenek68621b92009-01-28 05:56:51 +00001189 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1190 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001191
Ted Kremenek68621b92009-01-28 05:56:51 +00001192 RefVal(Kind k, unsigned cnt = 0)
1193 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1194
1195public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001196 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001197
1198 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001199
Ted Kremenek272aa852008-06-25 21:21:56 +00001200 unsigned getCount() const { return Cnt; }
1201 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001202
1203 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001204
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001205 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1206
Ted Kremenek0106e202008-10-24 20:32:50 +00001207 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001208
Ted Kremenekffefc352008-04-11 22:25:11 +00001209 bool isOwned() const {
1210 return getKind() == Owned;
1211 }
1212
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001213 bool isNotOwned() const {
1214 return getKind() == NotOwned;
1215 }
1216
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001217 bool isReturnedOwned() const {
1218 return getKind() == ReturnedOwned;
1219 }
1220
1221 bool isReturnedNotOwned() const {
1222 return getKind() == ReturnedNotOwned;
1223 }
1224
1225 bool isNonLeakError() const {
1226 Kind k = getKind();
1227 return isError(k) && !isLeak(k);
1228 }
1229
1230 // State creation: normal state.
1231
Ted Kremenek68621b92009-01-28 05:56:51 +00001232 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1233 unsigned Count = 1) {
1234 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001235 }
1236
Ted Kremenek68621b92009-01-28 05:56:51 +00001237 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1238 unsigned Count = 0) {
1239 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001240 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001241
1242 static RefVal makeReturnedOwned(unsigned Count) {
1243 return RefVal(ReturnedOwned, Count);
1244 }
1245
1246 static RefVal makeReturnedNotOwned() {
1247 return RefVal(ReturnedNotOwned);
1248 }
1249
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001250 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001251
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001252 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001253 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001254 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001255
Ted Kremenek272aa852008-06-25 21:21:56 +00001256 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001257 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001258 }
1259
1260 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001261 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001262 }
1263
1264 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001265 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001266 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001267
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001268 void Profile(llvm::FoldingSetNodeID& ID) const {
1269 ID.AddInteger((unsigned) kind);
1270 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001271 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001272 }
1273
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001274 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001275};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001276
1277void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001278 if (!T.isNull())
1279 Out << "Tracked Type:" << T.getAsString() << '\n';
1280
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001281 switch (getKind()) {
1282 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001283 case Owned: {
1284 Out << "Owned";
1285 unsigned cnt = getCount();
1286 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001287 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001288 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001289
Ted Kremenekc4f81022008-04-10 23:09:18 +00001290 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001291 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001292 unsigned cnt = getCount();
1293 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001294 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001295 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001296
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001297 case ReturnedOwned: {
1298 Out << "ReturnedOwned";
1299 unsigned cnt = getCount();
1300 if (cnt) Out << " (+ " << cnt << ")";
1301 break;
1302 }
1303
1304 case ReturnedNotOwned: {
1305 Out << "ReturnedNotOwned";
1306 unsigned cnt = getCount();
1307 if (cnt) Out << " (+ " << cnt << ")";
1308 break;
1309 }
1310
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001311 case Released:
1312 Out << "Released";
1313 break;
1314
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001315 case ErrorLeak:
1316 Out << "Leaked";
1317 break;
1318
Ted Kremenek311f3d42008-10-22 23:56:21 +00001319 case ErrorLeakReturned:
1320 Out << "Leaked (Bad naming)";
1321 break;
1322
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001323 case ErrorUseAfterRelease:
1324 Out << "Use-After-Release [ERROR]";
1325 break;
1326
1327 case ErrorReleaseNotOwned:
1328 Out << "Release of Not-Owned [ERROR]";
1329 break;
1330 }
1331}
Ted Kremenek0d721572008-03-11 17:48:22 +00001332
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001333} // end anonymous namespace
1334
1335//===----------------------------------------------------------------------===//
1336// RefBindings - State used to track object reference counts.
1337//===----------------------------------------------------------------------===//
1338
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001339typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001340static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001341static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001342
1343namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001344 template<>
1345 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1346 static inline void* GDMIndex() { return &RefBIndex; }
1347 };
1348}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001349
1350//===----------------------------------------------------------------------===//
1351// ARBindings - State used to track objects in autorelease pools.
1352//===----------------------------------------------------------------------===//
1353
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001354typedef llvm::ImmutableSet<SymbolRef> ARPoolContents;
1355typedef llvm::ImmutableList< std::pair<SymbolRef, ARPoolContents*> > ARBindings;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001356static int AutoRBIndex = 0;
1357
1358namespace clang {
1359 template<>
1360 struct GRStateTrait<ARBindings> : public GRStatePartialTrait<ARBindings> {
1361 static inline void* GDMIndex() { return &AutoRBIndex; }
1362 };
1363}
1364
Ted Kremenek7aef4842008-04-16 20:40:59 +00001365//===----------------------------------------------------------------------===//
1366// Transfer functions.
1367//===----------------------------------------------------------------------===//
1368
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001369namespace {
1370
Ted Kremenek7d421f32008-04-09 23:49:11 +00001371class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001372public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001373 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001374 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001375 virtual void Print(std::ostream& Out, const GRState* state,
1376 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001377 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001378
1379private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001380 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1381 SummaryLogTy;
1382
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001383 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001384 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001385 const LangOptions& LOpts;
Ted Kremenek91781202008-08-17 03:20:02 +00001386
Ted Kremenek708af042009-02-05 06:50:21 +00001387 BugType *useAfterRelease, *releaseNotOwned;
1388 BugType *leakWithinFunction, *leakAtReturn;
1389 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001390
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001391 RefBindings Update(RefBindings B, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenek91781202008-08-17 03:20:02 +00001392 RefVal::Kind& hasErr, RefBindings::Factory& RefBFactory);
Ted Kremenek1feab292008-04-16 04:28:53 +00001393
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001394 RefVal::Kind& Update(GRStateRef& state, SymbolRef sym, RefVal V,
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001395 ArgEffect E, RefVal::Kind& hasErr) {
1396
1397 state = state.set<RefBindings>(Update(state.get<RefBindings>(), sym, V,
Ted Kremenek91781202008-08-17 03:20:02 +00001398 E, hasErr,
1399 state.get_context<RefBindings>()));
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001400 return hasErr;
1401 }
1402
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001403 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1404 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001405 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001406 ExplodedNode<GRState>* Pred,
1407 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001408 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001409
Ted Kremenek0106e202008-10-24 20:32:50 +00001410 std::pair<GRStateRef, bool>
1411 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001412 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001413
Ted Kremeneka7338b42008-03-11 06:39:11 +00001414public:
Ted Kremenek7aef4842008-04-16 20:40:59 +00001415
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001416 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001417 : Summaries(Ctx, gcenabled),
Ted Kremenek708af042009-02-05 06:50:21 +00001418 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1419 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001420
Ted Kremenek708af042009-02-05 06:50:21 +00001421 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001422
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001423 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001424
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001425 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1426 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001427 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001428
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001429 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001430 const LangOptions& getLangOptions() const { return LOpts; }
1431
Ted Kremenekc26c4692009-02-18 03:48:14 +00001432 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1433 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1434 return I == SummaryLog.end() ? 0 : I->second;
1435 }
1436
Ted Kremeneka7338b42008-03-11 06:39:11 +00001437 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001438
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001439 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001440 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001441 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001442 Expr* Ex,
1443 Expr* Receiver,
1444 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001445 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001446 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001447
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001448 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001449 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001450 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001451 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001452 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001453
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001454
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001455 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001456 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001457 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001458 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001459 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001460
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001461 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001462 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001463 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001464 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001465 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001466
Ted Kremeneka42be302009-02-14 01:43:44 +00001467 // Stores.
1468 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1469
Ted Kremenekffefc352008-04-11 22:25:11 +00001470 // End-of-path.
1471
1472 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001473 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001474
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001475 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001476 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001477 GRStmtNodeBuilder<GRState>& Builder,
1478 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001479 Stmt* S, const GRState* state,
1480 SymbolReaper& SymReaper);
1481
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001482 // Return statements.
1483
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001484 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001485 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001486 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001487 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001488 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001489
1490 // Assumptions.
1491
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001492 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001493 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001494 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001495};
1496
1497} // end anonymous namespace
1498
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001499
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001500void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1501 const char* nl, const char* sep) {
1502
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001503 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001504
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001505 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001506 Out << sep << nl;
1507
1508 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1509 Out << (*I).first << " : ";
1510 (*I).second.print(Out);
1511 Out << nl;
1512 }
1513}
1514
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001515static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001516 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001517}
1518
Ted Kremenek266d8b62008-05-06 02:26:56 +00001519static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1520 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001521}
1522
Ted Kremenek227c5372008-05-06 02:41:27 +00001523static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1524 return Summ ? Summ->getReceiverEffect() : DoNothing;
1525}
1526
Ted Kremenekf2717b02008-07-18 17:24:20 +00001527static inline bool IsEndPath(RetainSummary* Summ) {
1528 return Summ ? Summ->isEndPath() : false;
1529}
1530
Ted Kremenek1feab292008-04-16 04:28:53 +00001531
Ted Kremenek272aa852008-06-25 21:21:56 +00001532/// GetReturnType - Used to get the return type of a message expression or
1533/// function call with the intention of affixing that type to a tracked symbol.
1534/// While the the return type can be queried directly from RetEx, when
1535/// invoking class methods we augment to the return type to be that of
1536/// a pointer to the class (as opposed it just being id).
1537static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1538
1539 QualType RetTy = RetE->getType();
1540
1541 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001542 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001543 if (!PT)
1544 return RetTy;
1545
1546 // If RetEx is not a message expression just return its type.
1547 // If RetEx is a message expression, return its types if it is something
1548 /// more specific than id.
1549
1550 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1551
Steve Naroff17c03822009-02-12 17:52:19 +00001552 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001553 return RetTy;
1554
1555 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1556
1557 // At this point we know the return type of the message expression is id.
1558 // If we have an ObjCInterceDecl, we know this is a call to a class method
1559 // whose type we can resolve. In such cases, promote the return type to
1560 // Class*.
1561 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1562}
1563
1564
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001565void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001566 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001567 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001568 Expr* Ex,
1569 Expr* Receiver,
1570 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001571 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001572 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001573
Ted Kremeneka7338b42008-03-11 06:39:11 +00001574 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001575 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001576 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001577
1578 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001579 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001580 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001581 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001582 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001583
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001584 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001585 SVal V = state.GetSVal(*I);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001586
Zhongxing Xu097fc982008-10-17 05:57:07 +00001587 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001588 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001589 if (RefBindings::data_type* T = state.get<RefBindings>(Sym))
1590 if (Update(state, Sym, *T, GetArgE(Summ, idx), hasErr)) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001591 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001592 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001593 break;
1594 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001595 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001596 else if (isa<Loc>(V)) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001597 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001598
1599 if (GetArgE(Summ, idx) == DoNothingByRef)
1600 continue;
1601
1602 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001603
1604 // FIXME: Either this logic should also be replicated in GRSimpleVals
1605 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001606
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001607 // FIXME: We can have collisions on the conjured symbol if the
1608 // expression *I also creates conjured symbols. We probably want
1609 // to identify conjured symbols by an expression pair: the enclosing
1610 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001611 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001612
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001613 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001614
1615 // Blast through AnonTypedRegions to get the original region type.
1616 while (R) {
1617 const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R);
1618 if (!ATR) break;
1619 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1620 }
1621
Ted Kremenekb15eba42008-10-04 05:50:14 +00001622 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001623
1624 // Is the invalidated variable something that we were tracking?
1625 SVal X = state.GetSVal(Loc::MakeVal(R));
1626
1627 if (isa<loc::SymbolVal>(X)) {
1628 SymbolRef Sym = cast<loc::SymbolVal>(X).getSymbol();
1629 state = state.remove<RefBindings>(Sym);
1630 }
1631
Ted Kremenekb15eba42008-10-04 05:50:14 +00001632 // Set the value of the variable to be a conjured symbol.
1633 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekf5da3252008-12-13 21:49:13 +00001634 QualType T = R->getRValueType(Ctx);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001635
Ted Kremenek8f90e712008-10-17 22:23:12 +00001636 // FIXME: handle structs.
Ted Kremenek79413a52008-11-13 06:10:40 +00001637 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001638 SymbolRef NewSym =
Ted Kremenek8f90e712008-10-17 22:23:12 +00001639 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1640
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001641 state = state.BindLoc(Loc::MakeVal(R),
Ted Kremenek8f90e712008-10-17 22:23:12 +00001642 Loc::IsLocType(T)
1643 ? cast<SVal>(loc::SymbolVal(NewSym))
1644 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1645 }
1646 else {
Ted Kremenek09102db2008-11-12 19:22:09 +00001647 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8f90e712008-10-17 22:23:12 +00001648 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001649 }
1650 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001651 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001652 }
1653 else {
1654 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001655 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001656 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001657 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001658 else if (isa<nonloc::LocAsInteger>(V))
1659 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001660 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001661
Ted Kremenek272aa852008-06-25 21:21:56 +00001662 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001663 if (!ErrorExpr && Receiver) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001664 SVal V = state.GetSVal(Receiver);
1665 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001666 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001667 if (const RefVal* T = state.get<RefBindings>(Sym))
1668 if (Update(state, Sym, *T, GetReceiverE(Summ), hasErr)) {
Ted Kremenek227c5372008-05-06 02:41:27 +00001669 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001670 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001671 }
Ted Kremenek227c5372008-05-06 02:41:27 +00001672 }
1673 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001674
Ted Kremenek272aa852008-06-25 21:21:56 +00001675 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001676 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001677 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001678 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001679 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001680 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001681
Ted Kremenekf2717b02008-07-18 17:24:20 +00001682 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001683 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001684
1685 switch (RE.getKind()) {
1686 default:
1687 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001688
Ted Kremenek8f90e712008-10-17 22:23:12 +00001689 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001690
Ted Kremenek455dd862008-04-11 20:23:24 +00001691 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001692 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1693 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001694
Ted Kremenek8f90e712008-10-17 22:23:12 +00001695 // FIXME: We eventually should handle structs and other compound types
1696 // that are returned by value.
1697
1698 QualType T = Ex->getType();
1699
Ted Kremenek79413a52008-11-13 06:10:40 +00001700 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001701 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001702 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001703
Ted Kremenek802cfc72009-02-20 00:05:35 +00001704 SVal X = Loc::IsLocType(T)
Zhongxing Xu097fc982008-10-17 05:57:07 +00001705 ? cast<SVal>(loc::SymbolVal(Sym))
1706 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001707
Ted Kremenek09102db2008-11-12 19:22:09 +00001708 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001709 }
1710
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001711 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00001712 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001713
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001714 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001715 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001716 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001717 assert (idx < (unsigned) (arg_end - arg_beg));
Zhongxing Xu097fc982008-10-17 05:57:07 +00001718 SVal V = state.GetSVal(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00001719 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001720 break;
1721 }
1722
Ted Kremenek227c5372008-05-06 02:41:27 +00001723 case RetEffect::ReceiverAlias: {
1724 assert (Receiver);
Zhongxing Xu097fc982008-10-17 05:57:07 +00001725 SVal V = state.GetSVal(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00001726 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00001727 break;
1728 }
1729
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001730 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001731 case RetEffect::OwnedSymbol: {
1732 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001733 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek68621b92009-01-28 05:56:51 +00001734 QualType RetT = GetReturnType(Ex, Eng.getContext());
1735 state =
1736 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001737 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001738
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001739 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremeneke62fd052009-01-28 22:27:59 +00001740 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1741 bool isFeasible;
1742 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1743 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1744 }
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001745
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001746 break;
1747 }
1748
1749 case RetEffect::NotOwnedSymbol: {
1750 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001751 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001752 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001753
Ted Kremenek68621b92009-01-28 05:56:51 +00001754 state =
1755 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001756 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001757 break;
1758 }
1759 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001760
Ted Kremenek0dd65012009-02-18 02:00:25 +00001761 // Generate a sink node if we are at the end of a path.
1762 GRExprEngine::NodeTy *NewNode =
1763 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1764 : Builder.MakeNode(Dst, Ex, Pred, state);
1765
1766 // Annotate the edge with summary we used.
1767 // FIXME: This assumes that we always use the same summary when generating
1768 // this node.
1769 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001770}
1771
1772
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001773void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001774 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001775 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001776 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001777 ExplodedNode<GRState>* Pred) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001778
Zhongxing Xu097fc982008-10-17 05:57:07 +00001779 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1780 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001781
1782 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1783 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001784}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001785
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001786void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001787 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001788 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001789 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001790 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00001791 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001792
Ted Kremenek272aa852008-06-25 21:21:56 +00001793 if (Expr* Receiver = ME->getReceiver()) {
1794 // We need the type-information of the tracked receiver object
1795 // Retrieve it from the state.
1796 ObjCInterfaceDecl* ID = 0;
1797
1798 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1799 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001800 const GRState* St = Builder.GetState(Pred);
Zhongxing Xu097fc982008-10-17 05:57:07 +00001801 SVal V = Eng.getStateManager().GetSVal(St, Receiver );
Ted Kremenek272aa852008-06-25 21:21:56 +00001802
Zhongxing Xu097fc982008-10-17 05:57:07 +00001803 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001804 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek272aa852008-06-25 21:21:56 +00001805
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001806 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00001807 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001808
1809 if (const PointerType* PT = Ty->getAsPointerType()) {
1810 QualType PointeeTy = PT->getPointeeType();
1811
1812 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1813 ID = IT->getDecl();
1814 }
1815 }
1816 }
1817
1818 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00001819
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001820 // Special-case: are we sending a mesage to "self"?
1821 // This is a hack. When we have full-IP this should be removed.
1822 if (!Summ) {
1823 ObjCMethodDecl* MD =
1824 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1825
1826 if (MD) {
1827 if (Expr* Receiver = ME->getReceiver()) {
1828 SVal X = Eng.getStateManager().GetSVal(St, Receiver);
1829 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00001830 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1831 // Create a summmary where all of the arguments "StopTracking".
1832 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1833 DoNothing,
1834 StopTracking);
1835 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001836 }
1837 }
1838 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001839 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001840 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001841 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1842 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001843
Ted Kremenek926abf22008-05-06 04:20:12 +00001844 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1845 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001846}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001847
1848namespace {
1849class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1850 GRStateRef state;
1851public:
1852 StopTrackingCallback(GRStateRef st) : state(st) {}
1853 GRStateRef getState() { return state; }
1854
1855 bool VisitSymbol(SymbolRef sym) {
1856 state = state.remove<RefBindings>(sym);
1857 return true;
1858 }
Ted Kremenek926abf22008-05-06 04:20:12 +00001859
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001860 const GRState* getState() const { return state.getState(); }
1861};
1862} // end anonymous namespace
1863
1864
Ted Kremeneka42be302009-02-14 01:43:44 +00001865void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00001866 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00001867 bool escapes = false;
1868
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001869 // A value escapes in three possible cases (this may change):
1870 //
1871 // (1) we are binding to something that is not a memory region.
1872 // (2) we are binding to a memregion that does not have stack storage
1873 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00001874 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00001875 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001876
Ted Kremeneka42be302009-02-14 01:43:44 +00001877 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00001878 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00001879 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00001880 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1881 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001882
1883 if (!escapes) {
1884 // To test (3), generate a new state with the binding removed. If it is
1885 // the same state, then it escapes (since the store cannot represent
1886 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00001887 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001888 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001889 }
Ted Kremeneka42be302009-02-14 01:43:44 +00001890
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001891 // If our store can represent the binding and we aren't storing to something
1892 // that doesn't have local storage then just return and have the simulation
1893 // state continue as is.
1894 if (!escapes)
1895 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001896
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001897 // Otherwise, find all symbols referenced by 'val' that we are tracking
1898 // and stop tracking them.
1899 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001900}
1901
Ted Kremenek0106e202008-10-24 20:32:50 +00001902std::pair<GRStateRef,bool>
1903CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1904 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001905 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00001906 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001907
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001908 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00001909 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00001910 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001911
Ted Kremenek311f3d42008-10-22 23:56:21 +00001912 if (V.isReturnedOwned() && V.getCount() == 0)
1913 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00001914 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00001915 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00001916 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00001917 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
1918 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00001919 }
1920 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001921
Ted Kremenek311f3d42008-10-22 23:56:21 +00001922 // All other cases.
1923
1924 hasLeak = V.isOwned() ||
1925 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001926
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001927 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00001928 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001929
Ted Kremenek0106e202008-10-24 20:32:50 +00001930 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
1931 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001932}
1933
Ted Kremenek541db372008-04-24 23:57:27 +00001934
Ted Kremenekffefc352008-04-11 22:25:11 +00001935
Ted Kremenek541db372008-04-24 23:57:27 +00001936// Dead symbols.
1937
Ted Kremenek708af042009-02-05 06:50:21 +00001938
Ted Kremenek541db372008-04-24 23:57:27 +00001939
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001940 // Return statements.
1941
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001942void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001943 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001944 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001945 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001946 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001947
1948 Expr* RetE = S->getRetValue();
1949 if (!RetE) return;
1950
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001951 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Zhongxing Xu097fc982008-10-17 05:57:07 +00001952 SVal V = state.GetSVal(RetE);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001953
Zhongxing Xu097fc982008-10-17 05:57:07 +00001954 if (!isa<loc::SymbolVal>(V))
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001955 return;
1956
1957 // Get the reference count binding (if any).
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001958 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001959 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001960
1961 if (!T)
1962 return;
1963
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001964 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00001965 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001966
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001967 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001968 case RefVal::Owned: {
1969 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001970 assert (cnt > 0);
1971 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001972 break;
1973 }
1974
1975 case RefVal::NotOwned: {
1976 unsigned cnt = X.getCount();
1977 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1978 : RefVal::makeReturnedNotOwned();
1979 break;
1980 }
1981
1982 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001983 return;
1984 }
1985
1986 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00001987 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001988 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001989}
1990
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001991// Assumptions.
1992
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001993const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
1994 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001995 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001996 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001997
1998 // FIXME: We may add to the interface of EvalAssume the list of symbols
1999 // whose assumptions have changed. For now we just iterate through the
2000 // bindings and check if any of the tracked symbols are NULL. This isn't
2001 // too bad since the number of symbols we will track in practice are
2002 // probably small and EvalAssume is only called at branches and a few
2003 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002004 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002005
2006 if (B.isEmpty())
2007 return St;
2008
2009 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002010
2011 GRStateRef state(St, VMgr);
2012 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002013
2014 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002015 // Check if the symbol is null (or equal to any constant).
2016 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002017 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002018 changed = true;
2019 B = RefBFactory.Remove(B, I.getKey());
2020 }
2021 }
2022
Ted Kremenek91781202008-08-17 03:20:02 +00002023 if (changed)
2024 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002025
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002026 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002027}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002028
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002029RefBindings CFRefCount::Update(RefBindings B, SymbolRef sym,
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002030 RefVal V, ArgEffect E,
Ted Kremenek91781202008-08-17 03:20:02 +00002031 RefVal::Kind& hasErr,
2032 RefBindings::Factory& RefBFactory) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002033
2034 // In GC mode [... release] and [... retain] do nothing.
2035 switch (E) {
2036 default: break;
2037 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2038 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002039 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002040 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002041
Ted Kremenek0d721572008-03-11 17:48:22 +00002042 switch (E) {
2043 default:
2044 assert (false && "Unhandled CFRef transition.");
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002045
2046 case MayEscape:
2047 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002048 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002049 break;
2050 }
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002051 // Fall-through.
Ted Kremenekede40b72008-07-09 18:11:16 +00002052 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002053 case DoNothing:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002054 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002055 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002056 hasErr = V.getKind();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002057 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002058 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002059 return B;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002060
Ted Kremenek9b112d22009-01-28 21:44:40 +00002061 case Autorelease:
2062 if (isGCEnabled()) return B;
2063 // Fall-through.
Ted Kremenek227c5372008-05-06 02:41:27 +00002064 case StopTracking:
2065 return RefBFactory.Remove(B, sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002066
Ted Kremenek0d721572008-03-11 17:48:22 +00002067 case IncRef:
2068 switch (V.getKind()) {
2069 default:
2070 assert(false);
2071
2072 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002073 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002074 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002075 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002076 case RefVal::Released:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002077 if (isGCEnabled())
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002078 V = (V ^ RefVal::Owned) + 1;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002079 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002080 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002081 hasErr = V.getKind();
2082 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002083 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002084 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002085 break;
2086
Ted Kremenek272aa852008-06-25 21:21:56 +00002087 case SelfOwn:
2088 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002089 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002090 case DecRef:
2091 switch (V.getKind()) {
2092 default:
2093 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002094
Ted Kremenek272aa852008-06-25 21:21:56 +00002095 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002096 assert(V.getCount() > 0);
2097 if (V.getCount() == 1) V = V ^ RefVal::Released;
2098 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002099 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002100
Ted Kremenek272aa852008-06-25 21:21:56 +00002101 case RefVal::NotOwned:
2102 if (V.getCount() > 0)
2103 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002104 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002105 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002106 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002107 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002108 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002109
2110 case RefVal::Released:
Ted Kremenek272aa852008-06-25 21:21:56 +00002111 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002112 hasErr = V.getKind();
Ted Kremenek0d721572008-03-11 17:48:22 +00002113 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002114 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002115 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002116 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002117 return RefBFactory.Add(B, sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002118}
2119
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002120//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002121// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002122//===----------------------------------------------------------------------===//
2123
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002124namespace {
2125
2126 //===-------------===//
2127 // Bug Descriptions. //
2128 //===-------------===//
2129
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002130 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002131 protected:
2132 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002133
2134 CFRefBug(CFRefCount* tf, const char* name)
2135 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002136 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002137
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002138 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002139 const CFRefCount& getTF() const { return TF; }
2140
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002141 // FIXME: Eventually remove.
2142 virtual const char* getDescription() const = 0;
2143
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002144 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002145 };
2146
2147 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2148 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002149 UseAfterRelease(CFRefCount* tf)
2150 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002151
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002152 const char* getDescription() const {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002153 return "Reference-counted object is used after it is released.";
Ted Kremenek708af042009-02-05 06:50:21 +00002154 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002155 };
2156
2157 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2158 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002159 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2160
2161 const char* getDescription() const {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002162 return "Incorrect decrement of the reference count of a "
Ted Kremeneka8503952008-04-18 04:55:01 +00002163 "CoreFoundation object: "
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002164 "The object is not owned at this point by the caller.";
2165 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002166 };
2167
2168 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002169 const bool isReturn;
2170 protected:
2171 Leak(CFRefCount* tf, const char* name, bool isRet)
2172 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002173 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002174
Ted Kremenek44274e62009-02-07 22:38:00 +00002175 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002176
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002177 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002178 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002179
2180 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2181 public:
2182 LeakAtReturn(CFRefCount* tf, const char* name)
2183 : Leak(tf, name, true) {}
2184 };
2185
2186 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2187 public:
2188 LeakWithinFunction(CFRefCount* tf, const char* name)
2189 : Leak(tf, name, false) {}
2190 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002191
2192 //===---------===//
2193 // Bug Reports. //
2194 //===---------===//
2195
2196 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002197 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002198 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002199 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002200 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002201 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2202 ExplodedNode<GRState> *n, SymbolRef sym)
2203 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002204
2205 virtual ~CFRefReport() {}
2206
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002207 CFRefBug& getBugType() {
2208 return (CFRefBug&) RangedBugReport::getBugType();
2209 }
2210 const CFRefBug& getBugType() const {
2211 return (const CFRefBug&) RangedBugReport::getBugType();
2212 }
2213
2214 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2215 const SourceRange*& end) {
2216
Ted Kremenek198cae02008-05-02 20:53:50 +00002217 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002218 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002219 else
2220 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002221 }
2222
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002223 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002224
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002225 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2226 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002227
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002228 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002229
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002230 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2231 const ExplodedNode<GRState>* PrevN,
2232 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002233 BugReporter& BR,
2234 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002235 };
2236
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002237 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002238 SourceLocation AllocSite;
2239 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002240 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002241 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2242 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002243 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002244
2245 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2246 const ExplodedNode<GRState>* N);
2247
Ted Kremenek86617f42009-02-07 22:19:59 +00002248 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002249 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002250} // end anonymous namespace
2251
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002252void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002253 useAfterRelease = new UseAfterRelease(this);
2254 BR.Register(useAfterRelease);
2255
2256 releaseNotOwned = new BadRelease(this);
2257 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002258
2259 // First register "return" leaks.
2260 const char* name = 0;
2261
2262 if (isGCEnabled())
2263 name = "[naming convention] leak of returned object (GC)";
2264 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2265 name = "[naming convention] leak of returned object (hybrid MM, "
2266 "non-GC)";
2267 else {
2268 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2269 name = "[naming convention] leak of returned object";
2270 }
2271
Ted Kremenek708af042009-02-05 06:50:21 +00002272 leakAtReturn = new LeakAtReturn(this, name);
2273 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002274
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002275 // Second, register leaks within a function/method.
2276 if (isGCEnabled())
2277 name = "leak (GC)";
2278 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2279 name = "leak (hybrid MM, non-GC)";
2280 else {
2281 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2282 name = "leak";
2283 }
2284
Ted Kremenek708af042009-02-05 06:50:21 +00002285 leakWithinFunction = new LeakWithinFunction(this, name);
2286 BR.Register(leakWithinFunction);
2287
2288 // Save the reference to the BugReporter.
2289 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002290}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002291
2292static const char* Msgs[] = {
2293 "Code is compiled in garbage collection only mode" // GC only
2294 " (the bug occurs with garbage collection enabled).",
2295
2296 "Code is compiled without garbage collection.", // No GC.
2297
2298 "Code is compiled for use with and without garbage collection (GC)."
2299 " The bug occurs with GC enabled.", // Hybrid, with GC.
2300
2301 "Code is compiled for use with and without garbage collection (GC)."
2302 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2303};
2304
2305std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2306 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2307
2308 switch (TF.getLangOptions().getGCMode()) {
2309 default:
2310 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002311
2312 case LangOptions::GCOnly:
2313 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002314 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2315
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002316 case LangOptions::NonGC:
2317 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002318 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2319
2320 case LangOptions::HybridGC:
2321 if (TF.isGCEnabled())
2322 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2323 else
2324 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2325 }
2326}
2327
Ted Kremenek2126bef2009-02-18 21:57:45 +00002328static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2329 ArgEffect X) {
2330 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2331 I!=E; ++I)
2332 if (*I == X) return true;
2333
2334 return false;
2335}
2336
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002337PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2338 const ExplodedNode<GRState>* PrevN,
2339 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002340 BugReporter& BR,
2341 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002342
Ted Kremenek71745d92009-01-28 05:29:13 +00002343 // Check if the type state has changed.
2344 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2345 GRStateRef PrevSt(PrevN->getState(), StMgr);
2346 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002347
Ted Kremenek71745d92009-01-28 05:29:13 +00002348 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2349 if (!CurrT) return NULL;
2350
2351 const RefVal& CurrV = *CurrT;
2352 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002353
Ted Kremenek2126bef2009-02-18 21:57:45 +00002354 // Create a string buffer to constain all the useful things we want
2355 // to tell the user.
2356 std::string sbuf;
2357 llvm::raw_string_ostream os(sbuf);
2358
Ted Kremenekc26c4692009-02-18 03:48:14 +00002359 // This is the allocation site since the previous node had no bindings
2360 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002361 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002362 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2363
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002364 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2365 // Get the name of the callee (if it is available).
2366 SVal X = CurrSt.GetSVal(CE->getCallee());
2367 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2368 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2369 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002370 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002371 }
2372 else {
2373 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002374 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002375 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002376
Ted Kremenek18878b12009-01-28 06:06:36 +00002377 if (CurrV.getObjKind() == RetEffect::CF) {
2378 os << " returns a Core Foundation object with a ";
2379 }
2380 else {
2381 assert (CurrV.getObjKind() == RetEffect::ObjC);
2382 os << " returns an Objective-C object with a ";
2383 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002384
Ted Kremenekabe30922009-01-28 06:25:48 +00002385 if (CurrV.isOwned()) {
2386 os << "+1 retain count (owning reference).";
2387
2388 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2389 assert(CurrV.getObjKind() == RetEffect::CF);
2390 os << " "
2391 "Core Foundation objects are not automatically garbage collected.";
2392 }
2393 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002394 else {
2395 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002396 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002397 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002398
Ted Kremeneka8503952008-04-18 04:55:01 +00002399 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenekbc543722009-01-28 04:47:13 +00002400 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002401
2402 if (Expr* Exp = dyn_cast<Expr>(S))
2403 P->addRange(Exp->getSourceRange());
2404
2405 return P;
2406 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002407
Ted Kremenek2126bef2009-02-18 21:57:45 +00002408 // Gather up the effects that were performed on the object at this
2409 // program point
2410 llvm::SmallVector<ArgEffect, 2> AEffects;
2411
Ted Kremenekc26c4692009-02-18 03:48:14 +00002412 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2413 // We only have summaries attached to nodes after evaluating CallExpr and
2414 // ObjCMessageExprs.
2415 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2416
Ted Kremenekc26c4692009-02-18 03:48:14 +00002417 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2418 // Iterate through the parameter expressions and see if the symbol
2419 // was ever passed as an argument.
2420 unsigned i = 0;
2421
2422 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2423 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002424
Ted Kremenekc26c4692009-02-18 03:48:14 +00002425 // Retrieve the value of the arugment.
2426 SVal X = CurrSt.GetSVal(*AI);
Ted Kremenek2126bef2009-02-18 21:57:45 +00002427
Ted Kremenekc26c4692009-02-18 03:48:14 +00002428 // Is it the symbol we're interested in?
2429 if (!isa<loc::SymbolVal>(X) ||
2430 Sym != cast<loc::SymbolVal>(X).getSymbol())
2431 continue;
Ted Kremenek752b5842008-04-18 05:32:44 +00002432
Ted Kremenekc26c4692009-02-18 03:48:14 +00002433 // We have an argument. Get the effect!
2434 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002435 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002436 }
2437 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2438 if (Expr *receiver = ME->getReceiver()) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002439 SVal RetV = CurrSt.GetSVal(receiver);
2440 if (isa<loc::SymbolVal>(RetV) &&
2441 Sym == cast<loc::SymbolVal>(RetV).getSymbol()) {
2442 // The symbol we are tracking is the receiver.
2443 AEffects.push_back(Summ->getReceiverEffect());
2444 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002445 }
2446 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002447 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002448
Ted Kremenek2126bef2009-02-18 21:57:45 +00002449 do {
2450 // Get the previous type state.
2451 RefVal PrevV = *PrevT;
2452
2453 // Specially handle CFMakeCollectable and friends.
2454 if (contains(AEffects, MakeCollectable)) {
2455 // Get the name of the function.
2456 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2457 loc::FuncVal FV =
2458 cast<loc::FuncVal>(CurrSt.GetSVal(cast<CallExpr>(S)->getCallee()));
2459 const std::string& FName = FV.getDecl()->getNameAsString();
2460
2461 if (TF.isGCEnabled()) {
2462 // Determine if the object's reference count was pushed to zero.
2463 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2464
2465 os << "In GC mode a call to '" << FName
2466 << "' decrements an object's retain count and registers the "
2467 "object with the garbage collector. ";
2468
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002469 if (CurrV.getKind() == RefVal::Released) {
2470 assert(CurrV.getCount() == 0);
2471 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002472 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002473 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002474 else
2475 os << "An object must have a 0 retain count to be garbage collected. "
2476 "After this call its retain count is +" << CurrV.getCount()
2477 << '.';
2478 }
2479 else
2480 os << "When GC is not enabled a call to '" << FName
2481 << "' has no effect on its argument.";
2482
2483 // Nothing more to say.
2484 break;
2485 }
2486
2487 // Determine if the typestate has changed.
2488 if (!(PrevV == CurrV))
2489 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002490 case RefVal::Owned:
2491 case RefVal::NotOwned:
2492
2493 if (PrevV.getCount() == CurrV.getCount())
2494 return 0;
2495
2496 if (PrevV.getCount() > CurrV.getCount())
2497 os << "Reference count decremented.";
2498 else
2499 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002500
Ted Kremenekc26c4692009-02-18 03:48:14 +00002501 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002502 os << " The object now has +" << Count;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002503
2504 if (Count > 1)
2505 os << " retain counts.";
2506 else
2507 os << " retain count.";
2508 }
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002509
2510 if (PrevV.getKind() == RefVal::Released) {
2511 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2512 os << " The object is not eligible for garbage collection until the "
2513 "retain count reaches 0 again.";
2514 }
2515
Ted Kremenekc26c4692009-02-18 03:48:14 +00002516 break;
2517
2518 case RefVal::Released:
2519 os << "Object released.";
2520 break;
2521
2522 case RefVal::ReturnedOwned:
2523 os << "Object returned to caller as an owning reference (single retain "
2524 "count transferred to caller).";
2525 break;
2526
2527 case RefVal::ReturnedNotOwned:
2528 os << "Object returned to caller with a +0 (non-owning) retain count.";
2529 break;
2530
2531 default:
2532 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002533 }
2534
2535 // Emit any remaining diagnostics for the argument effects (if any).
2536 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2537 E=AEffects.end(); I != E; ++I) {
2538
2539 // A bunch of things have alternate behavior under GC.
2540 if (TF.isGCEnabled())
2541 switch (*I) {
2542 default: break;
2543 case Autorelease:
2544 os << "In GC mode an 'autorelease' has no effect.";
2545 continue;
2546 case IncRefMsg:
2547 os << "In GC mode the 'retain' message has no effect.";
2548 continue;
2549 case DecRefMsg:
2550 os << "In GC mode the 'release' message has no effect.";
2551 continue;
2552 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002553 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002554 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002555
2556 if (os.str().empty())
2557 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002558
2559 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2560 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenekbc543722009-01-28 04:47:13 +00002561 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002562
2563 // Add the range by scanning the children of the statement for any bindings
2564 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002565 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2566 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek335a3022009-01-28 05:06:46 +00002567 SVal X = CurrSt.GetSVal(Exp);
Zhongxing Xu097fc982008-10-17 05:57:07 +00002568 if (loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&X))
Ted Kremenekfd3f8da2009-02-18 22:17:20 +00002569 if (SV->getSymbol() == Sym) {
2570 P->addRange(Exp->getSourceRange());
2571 break;
2572 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002573 }
2574
2575 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002576}
2577
Ted Kremenekb15eba42008-10-04 05:50:14 +00002578namespace {
2579class VISIBILITY_HIDDEN FindUniqueBinding :
2580 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002581 SymbolRef Sym;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002582 MemRegion* Binding;
2583 bool First;
2584
2585 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002586 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002587
Zhongxing Xu097fc982008-10-17 05:57:07 +00002588 bool HandleBinding(StoreManager& SMgr, Store store, MemRegion* R, SVal val) {
2589 if (const loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&val)) {
Ted Kremenekb15eba42008-10-04 05:50:14 +00002590 if (SV->getSymbol() != Sym)
2591 return true;
2592 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002593 else if (const nonloc::SymbolVal* SV=dyn_cast<nonloc::SymbolVal>(&val)) {
Ted Kremenekb15eba42008-10-04 05:50:14 +00002594 if (SV->getSymbol() != Sym)
2595 return true;
2596 }
2597 else
2598 return true;
2599
2600 if (Binding) {
2601 First = false;
2602 return false;
2603 }
2604 else
2605 Binding = R;
2606
2607 return true;
2608 }
2609
2610 operator bool() { return First && Binding; }
2611 MemRegion* getRegion() { return Binding; }
2612};
2613}
2614
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002615static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00002616GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002617 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00002618
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002619 // Find both first node that referred to the tracked symbol and the
2620 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002621 const ExplodedNode<GRState>* Last = N;
2622 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002623
2624 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002625 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002626 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002627
Ted Kremenek6064a362008-07-07 16:21:19 +00002628 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002629 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002630
Ted Kremenek86617f42009-02-07 22:19:59 +00002631 FindUniqueBinding FB(Sym);
2632 StateMgr.iterBindings(St, FB);
2633 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002634
Ted Kremenekd7e26782008-05-16 18:33:44 +00002635 Last = N;
2636 N = N->pred_empty() ? NULL : *(N->pred_begin());
2637 }
2638
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002639 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002640}
Ted Kremenek4c479322008-05-06 23:07:13 +00002641
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002642PathDiagnosticPiece*
2643CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002644
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002645 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek86953652008-05-22 23:45:19 +00002646 // Tell the BugReporter to report cases when the tracked symbol is
2647 // assigned to different variables, etc.
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002648 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002649 return RangedBugReport::getEndPath(BR, EndN);
2650}
2651
2652PathDiagnosticPiece*
2653CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2654
2655 GRBugReporter& BR = cast<GRBugReporter>(br);
2656 // Tell the BugReporter to report cases when the tracked symbol is
2657 // assigned to different variables, etc.
2658 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2659
2660 // We are reporting a leak. Walk up the graph to get to the first node where
2661 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00002662 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002663 const ExplodedNode<GRState>* AllocNode = 0;
2664 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002665
2666 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00002667 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002668
Ted Kremenekd7e26782008-05-16 18:33:44 +00002669 // Get the allocate site.
2670 assert (AllocNode);
2671 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002672
Ted Kremenekea794e92008-05-05 18:50:19 +00002673 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00002674 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002675
Ted Kremeneke0336742009-02-18 23:28:26 +00002676 // Get the leak site. We want to find the last place where the symbol
2677 // was used in an expression.
2678 const ExplodedNode<GRState>* LeakN = EndN;
2679 Stmt *S = 0;
Ted Kremenekea794e92008-05-05 18:50:19 +00002680
Ted Kremeneke0336742009-02-18 23:28:26 +00002681 while (LeakN) {
2682 ProgramPoint P = LeakN->getLocation();
Ted Kremeneke0336742009-02-18 23:28:26 +00002683
2684 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2685 S = PS->getStmt();
2686 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
2687 S = BE->getSrc()->getTerminator();
2688
2689 if (S) {
2690 // Scan 'S' for uses of Sym.
2691 GRStateRef state(LeakN->getState(), BR.getStateManager());
2692 bool foundSymbol = false;
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002693
2694 // First check if 'S' itself binds to the symbol.
2695 if (Expr *Ex = dyn_cast<Expr>(S)) {
2696 SVal X = state.GetSVal(Ex);
2697 if (isa<loc::SymbolVal>(X) &&
2698 cast<loc::SymbolVal>(X).getSymbol() == Sym)
2699 foundSymbol = true;
2700 }
2701
2702 if (!foundSymbol)
2703 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2704 I!=E; ++I)
2705 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
2706 SVal X = state.GetSVal(Ex);
2707 if (isa<loc::SymbolVal>(X) &&
2708 cast<loc::SymbolVal>(X).getSymbol() == Sym){
2709 foundSymbol = true;
2710 break;
2711 }
Ted Kremeneke0336742009-02-18 23:28:26 +00002712 }
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002713
Ted Kremeneke0336742009-02-18 23:28:26 +00002714 if (foundSymbol)
2715 break;
2716 }
2717
2718 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2719 }
2720
2721 assert(LeakN && S && "No leak site found.");
Ted Kremenekea794e92008-05-05 18:50:19 +00002722
Ted Kremenekea794e92008-05-05 18:50:19 +00002723 // Generate the diagnostic.
Ted Kremenek323207b2009-02-18 22:59:04 +00002724 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenek59f9fe12009-02-07 21:59:45 +00002725 std::string sbuf;
2726 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00002727
Ted Kremenekea794e92008-05-05 18:50:19 +00002728 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002729
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002730 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002731 os << " and stored into '" << FirstBinding->getString() << '\'';
2732
Ted Kremenek311f3d42008-10-22 23:56:21 +00002733 // Get the retain count.
2734 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2735
2736 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00002737 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2738 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2739 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00002740 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2741 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00002742 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00002743 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00002744 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002745 " in the Memory Management Guide for Cocoa (object leaked).";
2746 }
2747 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00002748 os << " is no longer referenced after this point and has a retain count of"
2749 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002750 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002751
Ted Kremenek323207b2009-02-18 22:59:04 +00002752 return new PathDiagnosticPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002753}
2754
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002755
Ted Kremenekc26c4692009-02-18 03:48:14 +00002756CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2757 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00002758 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002759 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00002760{
2761
Ted Kremenekd7e26782008-05-16 18:33:44 +00002762 // Most bug reports are cached at the location where they occured.
2763 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00002764 // allocated, and only report a single path. To do this, we need to find
2765 // the allocation site of a piece of tracked memory, which we do via a
2766 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2767 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2768 // that all ancestor nodes that represent the allocation site have the
2769 // same SourceLocation.
2770 const ExplodedNode<GRState>* AllocNode = 0;
2771
2772 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00002773 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00002774
Ted Kremenek86617f42009-02-07 22:19:59 +00002775 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00002776 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00002777 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00002778
2779 // Fill in the description of the bug.
2780 Description.clear();
2781 llvm::raw_string_ostream os(Description);
2782 SourceManager& SMgr = Eng.getContext().getSourceManager();
2783 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00002784 os << "Potential leak of object allocated on line " << AllocLine;
2785
2786 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2787 if (AllocBinding)
2788 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00002789}
2790
Ted Kremeneka7338b42008-03-11 06:39:11 +00002791//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00002792// Handle dead symbols and end-of-path.
2793//===----------------------------------------------------------------------===//
2794
2795void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2796 GREndPathNodeBuilder<GRState>& Builder) {
2797
2798 const GRState* St = Builder.getState();
2799 RefBindings B = St->get<RefBindings>();
2800
2801 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2802 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2803
2804 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2805 bool hasLeak = false;
2806
2807 std::pair<GRStateRef, bool> X =
2808 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2809 (*I).first, (*I).second, hasLeak);
2810
2811 St = X.first;
2812 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2813 }
2814
2815 if (Leaked.empty())
2816 return;
2817
2818 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2819
2820 if (!N)
2821 return;
2822
2823 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2824 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2825
2826 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2827 : leakWithinFunction);
2828 assert(BT && "BugType not initialized.");
Ted Kremenekc26c4692009-02-18 03:48:14 +00002829 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00002830 BR->EmitReport(report);
2831 }
2832}
2833
2834void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2835 GRExprEngine& Eng,
2836 GRStmtNodeBuilder<GRState>& Builder,
2837 ExplodedNode<GRState>* Pred,
2838 Stmt* S,
2839 const GRState* St,
2840 SymbolReaper& SymReaper) {
2841
Ted Kremenek876d8df2009-02-19 23:47:02 +00002842 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00002843 RefBindings B = St->get<RefBindings>();
2844 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2845
2846 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2847 E = SymReaper.dead_end(); I != E; ++I) {
2848
2849 const RefVal* T = B.lookup(*I);
2850 if (!T) continue;
2851
2852 bool hasLeak = false;
2853
2854 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00002855 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00002856
2857 St = X.first;
2858
2859 if (hasLeak)
2860 Leaked.push_back(std::make_pair(*I,X.second));
2861 }
2862
Ted Kremenek876d8df2009-02-19 23:47:02 +00002863 if (!Leaked.empty()) {
2864 // Create a new intermediate node representing the leak point. We
2865 // use a special program point that represents this checker-specific
2866 // transition. We use the address of RefBIndex as a unique tag for this
2867 // checker. We will create another node (if we don't cache out) that
2868 // removes the retain-count bindings from the state.
2869 // NOTE: We use 'generateNode' so that it does interplay with the
2870 // auto-transition logic.
2871 ExplodedNode<GRState>* N =
2872 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00002873
Ted Kremenek876d8df2009-02-19 23:47:02 +00002874 if (!N)
2875 return;
2876
2877 // Generate the bug reports.
2878 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
2879 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2880
2881 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2882 : leakWithinFunction);
2883 assert(BT && "BugType not initialized.");
2884 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
2885 BR->EmitReport(report);
2886 }
Ted Kremenek708af042009-02-05 06:50:21 +00002887
Ted Kremenek876d8df2009-02-19 23:47:02 +00002888 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00002889 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00002890
2891 // Now generate a new node that nukes the old bindings.
2892 GRStateRef state(St, Eng.getStateManager());
2893 RefBindings::Factory& F = state.get_context<RefBindings>();
2894
2895 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2896 E = SymReaper.dead_end(); I!=E; ++I)
2897 B = F.Remove(B, *I);
2898
2899 state = state.set<RefBindings>(B);
2900 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00002901}
2902
2903void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2904 GRStmtNodeBuilder<GRState>& Builder,
2905 Expr* NodeExpr, Expr* ErrorExpr,
2906 ExplodedNode<GRState>* Pred,
2907 const GRState* St,
2908 RefVal::Kind hasErr, SymbolRef Sym) {
2909 Builder.BuildSinks = true;
2910 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2911
2912 if (!N) return;
2913
2914 CFRefBug *BT = 0;
2915
2916 if (hasErr == RefVal::ErrorUseAfterRelease)
2917 BT = static_cast<CFRefBug*>(useAfterRelease);
2918 else {
2919 assert(hasErr == RefVal::ErrorReleaseNotOwned);
2920 BT = static_cast<CFRefBug*>(releaseNotOwned);
2921 }
2922
Ted Kremenekc26c4692009-02-18 03:48:14 +00002923 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00002924 report->addRange(ErrorExpr->getSourceRange());
2925 BR->EmitReport(report);
2926}
2927
2928//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00002929// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002930//===----------------------------------------------------------------------===//
2931
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002932GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2933 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00002934 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00002935}