blob: efd1c85f2b97deb5109c481df3abdd7f6b287fc4 [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 Kremenek064ef322009-02-23 16:51:39 +0000599 RetainSummary* getUnarySummary(const 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 Kremenek064ef322009-02-23 16:51:39 +0000832 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000833 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000834 const FunctionType* FT = FD->getType()->getAsFunctionType();
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 Kremenek064ef322009-02-23 16:51:39 +0000946RetainSummaryManager::getUnarySummary(const FunctionType* FT,
947 UnaryFuncKind func) {
948
Ted Kremenek17144e82009-01-12 21:45:02 +0000949 // Sanity check that this is *really* a unary function. This can
950 // happen if people do weird things.
Ted Kremenek064ef322009-02-23 16:51:39 +0000951 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +0000952 if (!FTP || FTP->getNumArgs() != 1)
953 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000954
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000955 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000956
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000957 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +0000958 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000959 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000960 return getPersistentSummary(RetEffect::MakeAlias(0),
961 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000962 }
963
964 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000965 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000966 return getPersistentSummary(RetEffect::MakeNoRet(),
967 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000968 }
969
970 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +0000971 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
972 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000973 }
974
975 default:
Ted Kremenek562c1302008-05-05 16:51:50 +0000976 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +0000977 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +0000978 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000979}
980
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000981RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000982 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +0000983
984 if (FD->getIdentifier() == CFDictionaryCreateII) {
985 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
986 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
987 }
988
Ted Kremenek68621b92009-01-28 05:56:51 +0000989 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000990}
991
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000992RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000993 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +0000994 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
995 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000996}
997
Ted Kremeneka7338b42008-03-11 06:39:11 +0000998//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000999// Summary creation for Selectors.
1000//===----------------------------------------------------------------------===//
1001
Ted Kremenekbcaff792008-05-06 15:44:25 +00001002RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001003RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001004 assert(ScratchArgs.empty());
1005
Ted Kremenek802cfc72009-02-20 00:05:35 +00001006 // 'init' methods only return an alias if the return type is a location type.
1007 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001008 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +00001009 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1010 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001011
Ted Kremenek272aa852008-06-25 21:21:56 +00001012 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001013 return Summ;
1014}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001015
Ted Kremenek272aa852008-06-25 21:21:56 +00001016
Ted Kremenekbcaff792008-05-06 15:44:25 +00001017RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001018RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1019 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001020
1021 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001022
Ted Kremenek272aa852008-06-25 21:21:56 +00001023 // Look up a summary in our summary cache.
1024 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001025
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001026 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001027 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001028
Ted Kremenek35920ed2009-01-07 00:39:56 +00001029 // "initXXX": pass-through for receiver.
Ted Kremenek42ea0322008-05-05 23:55:01 +00001030 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001031 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001032
Ted Kremenek4395b452009-02-21 05:13:43 +00001033 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek35920ed2009-01-07 00:39:56 +00001034 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +00001035
Ted Kremenek35920ed2009-01-07 00:39:56 +00001036 // Look for methods that return an owned object.
1037 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek5496f6d2008-05-07 04:25:59 +00001038 return 0;
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001039
Ted Kremenek35920ed2009-01-07 00:39:56 +00001040 if (followsFundamentalRule(s)) {
1041 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001042 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001043 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +00001044 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +00001045 return Summ;
1046 }
Ted Kremenekbcaff792008-05-06 15:44:25 +00001047
Ted Kremenek42ea0322008-05-05 23:55:01 +00001048 return 0;
1049}
1050
Ted Kremeneka7722b72008-05-06 21:26:51 +00001051RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001052RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1053 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +00001054
Ted Kremenek272aa852008-06-25 21:21:56 +00001055 // FIXME: Eventually we should properly do class method summaries, but
1056 // it requires us being able to walk the type hierarchy. Unfortunately,
1057 // we cannot do this with just an IdentifierInfo* for the class name.
1058
Ted Kremeneka7722b72008-05-06 21:26:51 +00001059 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +00001060 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001061
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001062 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001063 return I->second;
1064
Ted Kremenek4c479322008-05-06 23:07:13 +00001065 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001066}
1067
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001068void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001069
1070 assert (ScratchArgs.empty());
1071
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001072 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001073 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001074
Ted Kremenek0e344d42008-05-06 00:30:21 +00001075 RetainSummary* Summ = getPersistentSummary(E);
1076
Ted Kremenek272aa852008-06-25 21:21:56 +00001077 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1078 // NSObject and its derivatives.
1079 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1080 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1081 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001082
1083 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001084 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001085 GetNullarySelector("currentHandler", Ctx),
1086 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001087
1088 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001089 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1090 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1091 GetUnarySelector("addObject", Ctx),
1092 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001093 DoNothing, Autorelease));
Ted Kremenek0e344d42008-05-06 00:30:21 +00001094}
1095
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001096void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001097
1098 assert (ScratchArgs.empty());
1099
Ted Kremeneka7722b72008-05-06 21:26:51 +00001100 // Create the "init" selector. It just acts as a pass-through for the
1101 // receiver.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001102 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
1103 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001104
1105 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001106 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001107 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001108
Ted Kremeneke44927e2008-07-01 17:21:27 +00001109 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001110
1111 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001112 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1113
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001114 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001115 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001116
Ted Kremenek266d8b62008-05-06 02:26:56 +00001117 // Create the "retain" selector.
1118 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001119 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001120 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001121
1122 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001123 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001124 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001125
1126 // Create the "drain" selector.
1127 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001128 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001129
1130 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001131 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001132 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001133
Ted Kremenek45642a42008-08-12 18:48:50 +00001134 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001135 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1136 // self-own themselves. However, they only do this once they are displayed.
1137 // Thus, we need to track an NSWindow's display status.
1138 // This is tracked in <rdar://problem/6062711>.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001139 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001140 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001141
1142 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1143 "styleMask", "backing", "defer", NULL);
1144
1145 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1146 "styleMask", "backing", "defer", "screen", NULL);
1147
1148 // For NSPanel (which subclasses NSWindow), allocated objects are not
1149 // self-owned.
1150 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1151 "styleMask", "backing", "defer", NULL);
1152
1153 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1154 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001155
Ted Kremenekf2717b02008-07-18 17:24:20 +00001156 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001157 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1158 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001159
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001160 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1161 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001162}
1163
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001164//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001165// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001166//===----------------------------------------------------------------------===//
1167
Ted Kremeneka7338b42008-03-11 06:39:11 +00001168namespace {
1169
Ted Kremenek7d421f32008-04-09 23:49:11 +00001170class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001171public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001172 enum Kind {
1173 Owned = 0, // Owning reference.
1174 NotOwned, // Reference is not owned by still valid (not freed).
1175 Released, // Object has been released.
1176 ReturnedOwned, // Returned object passes ownership to caller.
1177 ReturnedNotOwned, // Return object does not pass ownership to caller.
1178 ErrorUseAfterRelease, // Object used after released.
1179 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek311f3d42008-10-22 23:56:21 +00001180 ErrorLeak, // A memory leak due to excessive reference counts.
1181 ErrorLeakReturned // A memory leak due to the returning method not having
1182 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001183 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001184
1185private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001186 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001187 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001188 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001189 QualType T;
1190
Ted Kremenek68621b92009-01-28 05:56:51 +00001191 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1192 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001193
Ted Kremenek68621b92009-01-28 05:56:51 +00001194 RefVal(Kind k, unsigned cnt = 0)
1195 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1196
1197public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001198 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001199
1200 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001201
Ted Kremenek272aa852008-06-25 21:21:56 +00001202 unsigned getCount() const { return Cnt; }
1203 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001204
1205 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001206
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001207 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1208
Ted Kremenek0106e202008-10-24 20:32:50 +00001209 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001210
Ted Kremenekffefc352008-04-11 22:25:11 +00001211 bool isOwned() const {
1212 return getKind() == Owned;
1213 }
1214
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001215 bool isNotOwned() const {
1216 return getKind() == NotOwned;
1217 }
1218
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001219 bool isReturnedOwned() const {
1220 return getKind() == ReturnedOwned;
1221 }
1222
1223 bool isReturnedNotOwned() const {
1224 return getKind() == ReturnedNotOwned;
1225 }
1226
1227 bool isNonLeakError() const {
1228 Kind k = getKind();
1229 return isError(k) && !isLeak(k);
1230 }
1231
1232 // State creation: normal state.
1233
Ted Kremenek68621b92009-01-28 05:56:51 +00001234 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1235 unsigned Count = 1) {
1236 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001237 }
1238
Ted Kremenek68621b92009-01-28 05:56:51 +00001239 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1240 unsigned Count = 0) {
1241 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001242 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001243
1244 static RefVal makeReturnedOwned(unsigned Count) {
1245 return RefVal(ReturnedOwned, Count);
1246 }
1247
1248 static RefVal makeReturnedNotOwned() {
1249 return RefVal(ReturnedNotOwned);
1250 }
1251
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001252 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001253
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001254 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001255 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001256 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001257
Ted Kremenek272aa852008-06-25 21:21:56 +00001258 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001259 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001260 }
1261
1262 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001263 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001264 }
1265
1266 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001267 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001268 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001269
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001270 void Profile(llvm::FoldingSetNodeID& ID) const {
1271 ID.AddInteger((unsigned) kind);
1272 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001273 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001274 }
1275
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001276 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001277};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001278
1279void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001280 if (!T.isNull())
1281 Out << "Tracked Type:" << T.getAsString() << '\n';
1282
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001283 switch (getKind()) {
1284 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001285 case Owned: {
1286 Out << "Owned";
1287 unsigned cnt = getCount();
1288 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001289 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001290 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001291
Ted Kremenekc4f81022008-04-10 23:09:18 +00001292 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001293 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001294 unsigned cnt = getCount();
1295 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001296 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001297 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001298
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001299 case ReturnedOwned: {
1300 Out << "ReturnedOwned";
1301 unsigned cnt = getCount();
1302 if (cnt) Out << " (+ " << cnt << ")";
1303 break;
1304 }
1305
1306 case ReturnedNotOwned: {
1307 Out << "ReturnedNotOwned";
1308 unsigned cnt = getCount();
1309 if (cnt) Out << " (+ " << cnt << ")";
1310 break;
1311 }
1312
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001313 case Released:
1314 Out << "Released";
1315 break;
1316
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001317 case ErrorLeak:
1318 Out << "Leaked";
1319 break;
1320
Ted Kremenek311f3d42008-10-22 23:56:21 +00001321 case ErrorLeakReturned:
1322 Out << "Leaked (Bad naming)";
1323 break;
1324
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001325 case ErrorUseAfterRelease:
1326 Out << "Use-After-Release [ERROR]";
1327 break;
1328
1329 case ErrorReleaseNotOwned:
1330 Out << "Release of Not-Owned [ERROR]";
1331 break;
1332 }
1333}
Ted Kremenek0d721572008-03-11 17:48:22 +00001334
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001335} // end anonymous namespace
1336
1337//===----------------------------------------------------------------------===//
1338// RefBindings - State used to track object reference counts.
1339//===----------------------------------------------------------------------===//
1340
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001341typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001342static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001343static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001344
1345namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001346 template<>
1347 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1348 static inline void* GDMIndex() { return &RefBIndex; }
1349 };
1350}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001351
1352//===----------------------------------------------------------------------===//
1353// ARBindings - State used to track objects in autorelease pools.
1354//===----------------------------------------------------------------------===//
1355
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001356typedef llvm::ImmutableSet<SymbolRef> ARPoolContents;
1357typedef llvm::ImmutableList< std::pair<SymbolRef, ARPoolContents*> > ARBindings;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001358static int AutoRBIndex = 0;
1359
1360namespace clang {
1361 template<>
1362 struct GRStateTrait<ARBindings> : public GRStatePartialTrait<ARBindings> {
1363 static inline void* GDMIndex() { return &AutoRBIndex; }
1364 };
1365}
1366
Ted Kremenek7aef4842008-04-16 20:40:59 +00001367//===----------------------------------------------------------------------===//
1368// Transfer functions.
1369//===----------------------------------------------------------------------===//
1370
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001371namespace {
1372
Ted Kremenek7d421f32008-04-09 23:49:11 +00001373class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001374public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001375 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001376 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001377 virtual void Print(std::ostream& Out, const GRState* state,
1378 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001379 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001380
1381private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001382 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1383 SummaryLogTy;
1384
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001385 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001386 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001387 const LangOptions& LOpts;
Ted Kremenek91781202008-08-17 03:20:02 +00001388
Ted Kremenek708af042009-02-05 06:50:21 +00001389 BugType *useAfterRelease, *releaseNotOwned;
1390 BugType *leakWithinFunction, *leakAtReturn;
1391 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001392
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001393 RefBindings Update(RefBindings B, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenek91781202008-08-17 03:20:02 +00001394 RefVal::Kind& hasErr, RefBindings::Factory& RefBFactory);
Ted Kremenek1feab292008-04-16 04:28:53 +00001395
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001396 RefVal::Kind& Update(GRStateRef& state, SymbolRef sym, RefVal V,
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001397 ArgEffect E, RefVal::Kind& hasErr) {
1398
1399 state = state.set<RefBindings>(Update(state.get<RefBindings>(), sym, V,
Ted Kremenek91781202008-08-17 03:20:02 +00001400 E, hasErr,
1401 state.get_context<RefBindings>()));
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001402 return hasErr;
1403 }
1404
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001405 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1406 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001407 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001408 ExplodedNode<GRState>* Pred,
1409 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001410 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001411
Ted Kremenek0106e202008-10-24 20:32:50 +00001412 std::pair<GRStateRef, bool>
1413 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001414 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001415
Ted Kremeneka7338b42008-03-11 06:39:11 +00001416public:
Ted Kremenek7aef4842008-04-16 20:40:59 +00001417
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001418 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001419 : Summaries(Ctx, gcenabled),
Ted Kremenek708af042009-02-05 06:50:21 +00001420 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1421 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001422
Ted Kremenek708af042009-02-05 06:50:21 +00001423 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001424
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001425 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001426
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001427 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1428 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001429 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001430
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001431 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001432 const LangOptions& getLangOptions() const { return LOpts; }
1433
Ted Kremenekc26c4692009-02-18 03:48:14 +00001434 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1435 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1436 return I == SummaryLog.end() ? 0 : I->second;
1437 }
1438
Ted Kremeneka7338b42008-03-11 06:39:11 +00001439 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001440
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001441 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001442 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001443 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001444 Expr* Ex,
1445 Expr* Receiver,
1446 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001447 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001448 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001449
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001450 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001451 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001452 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001453 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001454 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001455
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001456
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001457 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001458 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001459 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001460 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001461 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001462
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001463 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001464 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001465 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001466 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001467 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001468
Ted Kremeneka42be302009-02-14 01:43:44 +00001469 // Stores.
1470 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1471
Ted Kremenekffefc352008-04-11 22:25:11 +00001472 // End-of-path.
1473
1474 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001475 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001476
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001477 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001478 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001479 GRStmtNodeBuilder<GRState>& Builder,
1480 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001481 Stmt* S, const GRState* state,
1482 SymbolReaper& SymReaper);
1483
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001484 // Return statements.
1485
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001486 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001487 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001488 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001489 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001490 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001491
1492 // Assumptions.
1493
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001494 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001495 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001496 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001497};
1498
1499} // end anonymous namespace
1500
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001501
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001502void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1503 const char* nl, const char* sep) {
1504
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001505 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001506
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001507 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001508 Out << sep << nl;
1509
1510 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1511 Out << (*I).first << " : ";
1512 (*I).second.print(Out);
1513 Out << nl;
1514 }
1515}
1516
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001517static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001518 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001519}
1520
Ted Kremenek266d8b62008-05-06 02:26:56 +00001521static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1522 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001523}
1524
Ted Kremenek227c5372008-05-06 02:41:27 +00001525static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1526 return Summ ? Summ->getReceiverEffect() : DoNothing;
1527}
1528
Ted Kremenekf2717b02008-07-18 17:24:20 +00001529static inline bool IsEndPath(RetainSummary* Summ) {
1530 return Summ ? Summ->isEndPath() : false;
1531}
1532
Ted Kremenek1feab292008-04-16 04:28:53 +00001533
Ted Kremenek272aa852008-06-25 21:21:56 +00001534/// GetReturnType - Used to get the return type of a message expression or
1535/// function call with the intention of affixing that type to a tracked symbol.
1536/// While the the return type can be queried directly from RetEx, when
1537/// invoking class methods we augment to the return type to be that of
1538/// a pointer to the class (as opposed it just being id).
1539static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1540
1541 QualType RetTy = RetE->getType();
1542
1543 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001544 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001545 if (!PT)
1546 return RetTy;
1547
1548 // If RetEx is not a message expression just return its type.
1549 // If RetEx is a message expression, return its types if it is something
1550 /// more specific than id.
1551
1552 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1553
Steve Naroff17c03822009-02-12 17:52:19 +00001554 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001555 return RetTy;
1556
1557 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1558
1559 // At this point we know the return type of the message expression is id.
1560 // If we have an ObjCInterceDecl, we know this is a call to a class method
1561 // whose type we can resolve. In such cases, promote the return type to
1562 // Class*.
1563 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1564}
1565
1566
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001567void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001568 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001569 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001570 Expr* Ex,
1571 Expr* Receiver,
1572 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001573 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001574 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001575
Ted Kremeneka7338b42008-03-11 06:39:11 +00001576 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001577 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001578 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001579
1580 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001581 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001582 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001583 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001584 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001585
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001586 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001587 SVal V = state.GetSVal(*I);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001588
Zhongxing Xu097fc982008-10-17 05:57:07 +00001589 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001590 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001591 if (RefBindings::data_type* T = state.get<RefBindings>(Sym))
1592 if (Update(state, Sym, *T, GetArgE(Summ, idx), hasErr)) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001593 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001594 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001595 break;
1596 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001597 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001598 else if (isa<Loc>(V)) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001599 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001600
1601 if (GetArgE(Summ, idx) == DoNothingByRef)
1602 continue;
1603
1604 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001605
1606 // FIXME: Either this logic should also be replicated in GRSimpleVals
1607 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001608
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001609 // FIXME: We can have collisions on the conjured symbol if the
1610 // expression *I also creates conjured symbols. We probably want
1611 // to identify conjured symbols by an expression pair: the enclosing
1612 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001613 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001614
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001615 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001616
1617 // Blast through AnonTypedRegions to get the original region type.
1618 while (R) {
1619 const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R);
1620 if (!ATR) break;
1621 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1622 }
1623
Ted Kremenekb15eba42008-10-04 05:50:14 +00001624 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001625
1626 // Is the invalidated variable something that we were tracking?
1627 SVal X = state.GetSVal(Loc::MakeVal(R));
1628
1629 if (isa<loc::SymbolVal>(X)) {
1630 SymbolRef Sym = cast<loc::SymbolVal>(X).getSymbol();
1631 state = state.remove<RefBindings>(Sym);
1632 }
1633
Ted Kremenekb15eba42008-10-04 05:50:14 +00001634 // Set the value of the variable to be a conjured symbol.
1635 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekf5da3252008-12-13 21:49:13 +00001636 QualType T = R->getRValueType(Ctx);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001637
Ted Kremenek8f90e712008-10-17 22:23:12 +00001638 // FIXME: handle structs.
Ted Kremenek79413a52008-11-13 06:10:40 +00001639 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001640 SymbolRef NewSym =
Ted Kremenek8f90e712008-10-17 22:23:12 +00001641 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1642
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001643 state = state.BindLoc(Loc::MakeVal(R),
Ted Kremenek8f90e712008-10-17 22:23:12 +00001644 Loc::IsLocType(T)
1645 ? cast<SVal>(loc::SymbolVal(NewSym))
1646 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1647 }
1648 else {
Ted Kremenek09102db2008-11-12 19:22:09 +00001649 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8f90e712008-10-17 22:23:12 +00001650 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001651 }
1652 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001653 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001654 }
1655 else {
1656 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001657 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001658 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001659 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001660 else if (isa<nonloc::LocAsInteger>(V))
1661 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001662 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001663
Ted Kremenek272aa852008-06-25 21:21:56 +00001664 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001665 if (!ErrorExpr && Receiver) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001666 SVal V = state.GetSVal(Receiver);
1667 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001668 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001669 if (const RefVal* T = state.get<RefBindings>(Sym))
1670 if (Update(state, Sym, *T, GetReceiverE(Summ), hasErr)) {
Ted Kremenek227c5372008-05-06 02:41:27 +00001671 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001672 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001673 }
Ted Kremenek227c5372008-05-06 02:41:27 +00001674 }
1675 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001676
Ted Kremenek272aa852008-06-25 21:21:56 +00001677 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001678 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001679 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001680 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001681 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001682 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001683
Ted Kremenekf2717b02008-07-18 17:24:20 +00001684 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001685 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001686
1687 switch (RE.getKind()) {
1688 default:
1689 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001690
Ted Kremenek8f90e712008-10-17 22:23:12 +00001691 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001692
Ted Kremenek455dd862008-04-11 20:23:24 +00001693 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001694 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1695 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001696
Ted Kremenek8f90e712008-10-17 22:23:12 +00001697 // FIXME: We eventually should handle structs and other compound types
1698 // that are returned by value.
1699
1700 QualType T = Ex->getType();
1701
Ted Kremenek79413a52008-11-13 06:10:40 +00001702 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001703 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001704 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001705
Ted Kremenek802cfc72009-02-20 00:05:35 +00001706 SVal X = Loc::IsLocType(T)
Zhongxing Xu097fc982008-10-17 05:57:07 +00001707 ? cast<SVal>(loc::SymbolVal(Sym))
1708 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001709
Ted Kremenek09102db2008-11-12 19:22:09 +00001710 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001711 }
1712
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001713 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00001714 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001715
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001716 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001717 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001718 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001719 assert (idx < (unsigned) (arg_end - arg_beg));
Zhongxing Xu097fc982008-10-17 05:57:07 +00001720 SVal V = state.GetSVal(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00001721 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001722 break;
1723 }
1724
Ted Kremenek227c5372008-05-06 02:41:27 +00001725 case RetEffect::ReceiverAlias: {
1726 assert (Receiver);
Zhongxing Xu097fc982008-10-17 05:57:07 +00001727 SVal V = state.GetSVal(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00001728 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00001729 break;
1730 }
1731
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001732 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001733 case RetEffect::OwnedSymbol: {
1734 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001735 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek68621b92009-01-28 05:56:51 +00001736 QualType RetT = GetReturnType(Ex, Eng.getContext());
1737 state =
1738 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001739 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001740
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001741 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremeneke62fd052009-01-28 22:27:59 +00001742 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1743 bool isFeasible;
1744 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1745 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1746 }
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001747
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001748 break;
1749 }
1750
1751 case RetEffect::NotOwnedSymbol: {
1752 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001753 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001754 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001755
Ted Kremenek68621b92009-01-28 05:56:51 +00001756 state =
1757 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001758 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001759 break;
1760 }
1761 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001762
Ted Kremenek0dd65012009-02-18 02:00:25 +00001763 // Generate a sink node if we are at the end of a path.
1764 GRExprEngine::NodeTy *NewNode =
1765 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1766 : Builder.MakeNode(Dst, Ex, Pred, state);
1767
1768 // Annotate the edge with summary we used.
1769 // FIXME: This assumes that we always use the same summary when generating
1770 // this node.
1771 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001772}
1773
1774
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001775void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001776 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001777 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001778 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001779 ExplodedNode<GRState>* Pred) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001780
Zhongxing Xu097fc982008-10-17 05:57:07 +00001781 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1782 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001783
1784 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1785 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001786}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001787
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001788void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001789 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001790 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001791 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001792 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00001793 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001794
Ted Kremenek272aa852008-06-25 21:21:56 +00001795 if (Expr* Receiver = ME->getReceiver()) {
1796 // We need the type-information of the tracked receiver object
1797 // Retrieve it from the state.
1798 ObjCInterfaceDecl* ID = 0;
1799
1800 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1801 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001802 const GRState* St = Builder.GetState(Pred);
Zhongxing Xu097fc982008-10-17 05:57:07 +00001803 SVal V = Eng.getStateManager().GetSVal(St, Receiver );
Ted Kremenek272aa852008-06-25 21:21:56 +00001804
Zhongxing Xu097fc982008-10-17 05:57:07 +00001805 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001806 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek272aa852008-06-25 21:21:56 +00001807
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001808 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00001809 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001810
1811 if (const PointerType* PT = Ty->getAsPointerType()) {
1812 QualType PointeeTy = PT->getPointeeType();
1813
1814 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1815 ID = IT->getDecl();
1816 }
1817 }
1818 }
1819
1820 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00001821
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001822 // Special-case: are we sending a mesage to "self"?
1823 // This is a hack. When we have full-IP this should be removed.
1824 if (!Summ) {
1825 ObjCMethodDecl* MD =
1826 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1827
1828 if (MD) {
1829 if (Expr* Receiver = ME->getReceiver()) {
1830 SVal X = Eng.getStateManager().GetSVal(St, Receiver);
1831 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00001832 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1833 // Create a summmary where all of the arguments "StopTracking".
1834 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1835 DoNothing,
1836 StopTracking);
1837 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001838 }
1839 }
1840 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001841 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001842 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001843 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1844 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001845
Ted Kremenek926abf22008-05-06 04:20:12 +00001846 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1847 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001848}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001849
1850namespace {
1851class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1852 GRStateRef state;
1853public:
1854 StopTrackingCallback(GRStateRef st) : state(st) {}
1855 GRStateRef getState() { return state; }
1856
1857 bool VisitSymbol(SymbolRef sym) {
1858 state = state.remove<RefBindings>(sym);
1859 return true;
1860 }
Ted Kremenek926abf22008-05-06 04:20:12 +00001861
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001862 const GRState* getState() const { return state.getState(); }
1863};
1864} // end anonymous namespace
1865
1866
Ted Kremeneka42be302009-02-14 01:43:44 +00001867void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00001868 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00001869 bool escapes = false;
1870
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001871 // A value escapes in three possible cases (this may change):
1872 //
1873 // (1) we are binding to something that is not a memory region.
1874 // (2) we are binding to a memregion that does not have stack storage
1875 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00001876 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00001877 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001878
Ted Kremeneka42be302009-02-14 01:43:44 +00001879 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00001880 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00001881 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00001882 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1883 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001884
1885 if (!escapes) {
1886 // To test (3), generate a new state with the binding removed. If it is
1887 // the same state, then it escapes (since the store cannot represent
1888 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00001889 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001890 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001891 }
Ted Kremeneka42be302009-02-14 01:43:44 +00001892
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001893 // If our store can represent the binding and we aren't storing to something
1894 // that doesn't have local storage then just return and have the simulation
1895 // state continue as is.
1896 if (!escapes)
1897 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001898
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001899 // Otherwise, find all symbols referenced by 'val' that we are tracking
1900 // and stop tracking them.
1901 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001902}
1903
Ted Kremenek0106e202008-10-24 20:32:50 +00001904std::pair<GRStateRef,bool>
1905CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1906 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001907 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00001908 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001909
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001910 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00001911 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00001912 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001913
Ted Kremenek311f3d42008-10-22 23:56:21 +00001914 if (V.isReturnedOwned() && V.getCount() == 0)
1915 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00001916 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00001917 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00001918 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00001919 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
1920 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00001921 }
1922 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001923
Ted Kremenek311f3d42008-10-22 23:56:21 +00001924 // All other cases.
1925
1926 hasLeak = V.isOwned() ||
1927 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001928
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001929 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00001930 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001931
Ted Kremenek0106e202008-10-24 20:32:50 +00001932 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
1933 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001934}
1935
Ted Kremenek541db372008-04-24 23:57:27 +00001936
Ted Kremenekffefc352008-04-11 22:25:11 +00001937
Ted Kremenek541db372008-04-24 23:57:27 +00001938// Dead symbols.
1939
Ted Kremenek708af042009-02-05 06:50:21 +00001940
Ted Kremenek541db372008-04-24 23:57:27 +00001941
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001942 // Return statements.
1943
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001944void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001945 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001946 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001947 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001948 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001949
1950 Expr* RetE = S->getRetValue();
1951 if (!RetE) return;
1952
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001953 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Zhongxing Xu097fc982008-10-17 05:57:07 +00001954 SVal V = state.GetSVal(RetE);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001955
Zhongxing Xu097fc982008-10-17 05:57:07 +00001956 if (!isa<loc::SymbolVal>(V))
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001957 return;
1958
1959 // Get the reference count binding (if any).
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001960 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001961 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001962
1963 if (!T)
1964 return;
1965
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001966 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00001967 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001968
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001969 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001970 case RefVal::Owned: {
1971 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001972 assert (cnt > 0);
1973 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001974 break;
1975 }
1976
1977 case RefVal::NotOwned: {
1978 unsigned cnt = X.getCount();
1979 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1980 : RefVal::makeReturnedNotOwned();
1981 break;
1982 }
1983
1984 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001985 return;
1986 }
1987
1988 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00001989 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001990 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001991}
1992
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001993// Assumptions.
1994
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001995const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
1996 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001997 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001998 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001999
2000 // FIXME: We may add to the interface of EvalAssume the list of symbols
2001 // whose assumptions have changed. For now we just iterate through the
2002 // bindings and check if any of the tracked symbols are NULL. This isn't
2003 // too bad since the number of symbols we will track in practice are
2004 // probably small and EvalAssume is only called at branches and a few
2005 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002006 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002007
2008 if (B.isEmpty())
2009 return St;
2010
2011 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002012
2013 GRStateRef state(St, VMgr);
2014 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002015
2016 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002017 // Check if the symbol is null (or equal to any constant).
2018 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002019 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002020 changed = true;
2021 B = RefBFactory.Remove(B, I.getKey());
2022 }
2023 }
2024
Ted Kremenek91781202008-08-17 03:20:02 +00002025 if (changed)
2026 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002027
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002028 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002029}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002030
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002031RefBindings CFRefCount::Update(RefBindings B, SymbolRef sym,
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002032 RefVal V, ArgEffect E,
Ted Kremenek91781202008-08-17 03:20:02 +00002033 RefVal::Kind& hasErr,
2034 RefBindings::Factory& RefBFactory) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002035
2036 // In GC mode [... release] and [... retain] do nothing.
2037 switch (E) {
2038 default: break;
2039 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2040 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002041 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002042 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002043
Ted Kremenek0d721572008-03-11 17:48:22 +00002044 switch (E) {
2045 default:
2046 assert (false && "Unhandled CFRef transition.");
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002047
2048 case MayEscape:
2049 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002050 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002051 break;
2052 }
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002053 // Fall-through.
Ted Kremenekede40b72008-07-09 18:11:16 +00002054 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002055 case DoNothing:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002056 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002057 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002058 hasErr = V.getKind();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002059 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002060 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002061 return B;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002062
Ted Kremenek9b112d22009-01-28 21:44:40 +00002063 case Autorelease:
2064 if (isGCEnabled()) return B;
2065 // Fall-through.
Ted Kremenek227c5372008-05-06 02:41:27 +00002066 case StopTracking:
2067 return RefBFactory.Remove(B, sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002068
Ted Kremenek0d721572008-03-11 17:48:22 +00002069 case IncRef:
2070 switch (V.getKind()) {
2071 default:
2072 assert(false);
2073
2074 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002075 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002076 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002077 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002078 case RefVal::Released:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002079 if (isGCEnabled())
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002080 V = (V ^ RefVal::Owned) + 1;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002081 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002082 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002083 hasErr = V.getKind();
2084 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002085 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002086 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002087 break;
2088
Ted Kremenek272aa852008-06-25 21:21:56 +00002089 case SelfOwn:
2090 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002091 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002092 case DecRef:
2093 switch (V.getKind()) {
2094 default:
2095 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002096
Ted Kremenek272aa852008-06-25 21:21:56 +00002097 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002098 assert(V.getCount() > 0);
2099 if (V.getCount() == 1) V = V ^ RefVal::Released;
2100 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002101 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002102
Ted Kremenek272aa852008-06-25 21:21:56 +00002103 case RefVal::NotOwned:
2104 if (V.getCount() > 0)
2105 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002106 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002107 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002108 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002109 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002110 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002111
2112 case RefVal::Released:
Ted Kremenek272aa852008-06-25 21:21:56 +00002113 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002114 hasErr = V.getKind();
Ted Kremenek0d721572008-03-11 17:48:22 +00002115 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002116 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002117 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002118 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002119 return RefBFactory.Add(B, sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002120}
2121
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002122//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002123// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002124//===----------------------------------------------------------------------===//
2125
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002126namespace {
2127
2128 //===-------------===//
2129 // Bug Descriptions. //
2130 //===-------------===//
2131
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002132 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002133 protected:
2134 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002135
2136 CFRefBug(CFRefCount* tf, const char* name)
2137 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002138 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002139
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002140 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002141 const CFRefCount& getTF() const { return TF; }
2142
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002143 // FIXME: Eventually remove.
2144 virtual const char* getDescription() const = 0;
2145
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002146 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002147 };
2148
2149 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2150 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002151 UseAfterRelease(CFRefCount* tf)
2152 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002153
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002154 const char* getDescription() const {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002155 return "Reference-counted object is used after it is released.";
Ted Kremenek708af042009-02-05 06:50:21 +00002156 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002157 };
2158
2159 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2160 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002161 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2162
2163 const char* getDescription() const {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002164 return "Incorrect decrement of the reference count of a "
Ted Kremeneka8503952008-04-18 04:55:01 +00002165 "CoreFoundation object: "
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002166 "The object is not owned at this point by the caller.";
2167 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002168 };
2169
2170 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002171 const bool isReturn;
2172 protected:
2173 Leak(CFRefCount* tf, const char* name, bool isRet)
2174 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002175 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002176
Ted Kremenek44274e62009-02-07 22:38:00 +00002177 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002178
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002179 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002180 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002181
2182 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2183 public:
2184 LeakAtReturn(CFRefCount* tf, const char* name)
2185 : Leak(tf, name, true) {}
2186 };
2187
2188 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2189 public:
2190 LeakWithinFunction(CFRefCount* tf, const char* name)
2191 : Leak(tf, name, false) {}
2192 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002193
2194 //===---------===//
2195 // Bug Reports. //
2196 //===---------===//
2197
2198 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002199 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002200 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002201 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002202 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002203 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2204 ExplodedNode<GRState> *n, SymbolRef sym)
2205 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002206
2207 virtual ~CFRefReport() {}
2208
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002209 CFRefBug& getBugType() {
2210 return (CFRefBug&) RangedBugReport::getBugType();
2211 }
2212 const CFRefBug& getBugType() const {
2213 return (const CFRefBug&) RangedBugReport::getBugType();
2214 }
2215
2216 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2217 const SourceRange*& end) {
2218
Ted Kremenek198cae02008-05-02 20:53:50 +00002219 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002220 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002221 else
2222 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002223 }
2224
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002225 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002226
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002227 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2228 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002229
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002230 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002231
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002232 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2233 const ExplodedNode<GRState>* PrevN,
2234 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002235 BugReporter& BR,
2236 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002237 };
2238
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002239 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002240 SourceLocation AllocSite;
2241 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002242 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002243 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2244 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002245 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002246
2247 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2248 const ExplodedNode<GRState>* N);
2249
Ted Kremenek86617f42009-02-07 22:19:59 +00002250 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002251 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002252} // end anonymous namespace
2253
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002254void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002255 useAfterRelease = new UseAfterRelease(this);
2256 BR.Register(useAfterRelease);
2257
2258 releaseNotOwned = new BadRelease(this);
2259 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002260
2261 // First register "return" leaks.
2262 const char* name = 0;
2263
2264 if (isGCEnabled())
2265 name = "[naming convention] leak of returned object (GC)";
2266 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2267 name = "[naming convention] leak of returned object (hybrid MM, "
2268 "non-GC)";
2269 else {
2270 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2271 name = "[naming convention] leak of returned object";
2272 }
2273
Ted Kremenek708af042009-02-05 06:50:21 +00002274 leakAtReturn = new LeakAtReturn(this, name);
2275 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002276
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002277 // Second, register leaks within a function/method.
2278 if (isGCEnabled())
2279 name = "leak (GC)";
2280 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2281 name = "leak (hybrid MM, non-GC)";
2282 else {
2283 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2284 name = "leak";
2285 }
2286
Ted Kremenek708af042009-02-05 06:50:21 +00002287 leakWithinFunction = new LeakWithinFunction(this, name);
2288 BR.Register(leakWithinFunction);
2289
2290 // Save the reference to the BugReporter.
2291 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002292}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002293
2294static const char* Msgs[] = {
2295 "Code is compiled in garbage collection only mode" // GC only
2296 " (the bug occurs with garbage collection enabled).",
2297
2298 "Code is compiled without garbage collection.", // No GC.
2299
2300 "Code is compiled for use with and without garbage collection (GC)."
2301 " The bug occurs with GC enabled.", // Hybrid, with GC.
2302
2303 "Code is compiled for use with and without garbage collection (GC)."
2304 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2305};
2306
2307std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2308 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2309
2310 switch (TF.getLangOptions().getGCMode()) {
2311 default:
2312 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002313
2314 case LangOptions::GCOnly:
2315 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002316 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2317
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002318 case LangOptions::NonGC:
2319 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002320 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2321
2322 case LangOptions::HybridGC:
2323 if (TF.isGCEnabled())
2324 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2325 else
2326 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2327 }
2328}
2329
Ted Kremenek2126bef2009-02-18 21:57:45 +00002330static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2331 ArgEffect X) {
2332 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2333 I!=E; ++I)
2334 if (*I == X) return true;
2335
2336 return false;
2337}
2338
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002339PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2340 const ExplodedNode<GRState>* PrevN,
2341 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002342 BugReporter& BR,
2343 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002344
Ted Kremenek71745d92009-01-28 05:29:13 +00002345 // Check if the type state has changed.
2346 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2347 GRStateRef PrevSt(PrevN->getState(), StMgr);
2348 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002349
Ted Kremenek71745d92009-01-28 05:29:13 +00002350 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2351 if (!CurrT) return NULL;
2352
2353 const RefVal& CurrV = *CurrT;
2354 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002355
Ted Kremenek2126bef2009-02-18 21:57:45 +00002356 // Create a string buffer to constain all the useful things we want
2357 // to tell the user.
2358 std::string sbuf;
2359 llvm::raw_string_ostream os(sbuf);
2360
Ted Kremenekc26c4692009-02-18 03:48:14 +00002361 // This is the allocation site since the previous node had no bindings
2362 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002363 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002364 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2365
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002366 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2367 // Get the name of the callee (if it is available).
2368 SVal X = CurrSt.GetSVal(CE->getCallee());
2369 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2370 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2371 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002372 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002373 }
2374 else {
2375 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002376 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002377 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002378
Ted Kremenek18878b12009-01-28 06:06:36 +00002379 if (CurrV.getObjKind() == RetEffect::CF) {
2380 os << " returns a Core Foundation object with a ";
2381 }
2382 else {
2383 assert (CurrV.getObjKind() == RetEffect::ObjC);
2384 os << " returns an Objective-C object with a ";
2385 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002386
Ted Kremenekabe30922009-01-28 06:25:48 +00002387 if (CurrV.isOwned()) {
2388 os << "+1 retain count (owning reference).";
2389
2390 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2391 assert(CurrV.getObjKind() == RetEffect::CF);
2392 os << " "
2393 "Core Foundation objects are not automatically garbage collected.";
2394 }
2395 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002396 else {
2397 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002398 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002399 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002400
Ted Kremeneka8503952008-04-18 04:55:01 +00002401 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenekbc543722009-01-28 04:47:13 +00002402 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002403
2404 if (Expr* Exp = dyn_cast<Expr>(S))
2405 P->addRange(Exp->getSourceRange());
2406
2407 return P;
2408 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002409
Ted Kremenek2126bef2009-02-18 21:57:45 +00002410 // Gather up the effects that were performed on the object at this
2411 // program point
2412 llvm::SmallVector<ArgEffect, 2> AEffects;
2413
Ted Kremenekc26c4692009-02-18 03:48:14 +00002414 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2415 // We only have summaries attached to nodes after evaluating CallExpr and
2416 // ObjCMessageExprs.
2417 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2418
Ted Kremenekc26c4692009-02-18 03:48:14 +00002419 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2420 // Iterate through the parameter expressions and see if the symbol
2421 // was ever passed as an argument.
2422 unsigned i = 0;
2423
2424 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2425 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002426
Ted Kremenekc26c4692009-02-18 03:48:14 +00002427 // Retrieve the value of the arugment.
2428 SVal X = CurrSt.GetSVal(*AI);
Ted Kremenek2126bef2009-02-18 21:57:45 +00002429
Ted Kremenekc26c4692009-02-18 03:48:14 +00002430 // Is it the symbol we're interested in?
2431 if (!isa<loc::SymbolVal>(X) ||
2432 Sym != cast<loc::SymbolVal>(X).getSymbol())
2433 continue;
Ted Kremenek752b5842008-04-18 05:32:44 +00002434
Ted Kremenekc26c4692009-02-18 03:48:14 +00002435 // We have an argument. Get the effect!
2436 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002437 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002438 }
2439 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2440 if (Expr *receiver = ME->getReceiver()) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002441 SVal RetV = CurrSt.GetSVal(receiver);
2442 if (isa<loc::SymbolVal>(RetV) &&
2443 Sym == cast<loc::SymbolVal>(RetV).getSymbol()) {
2444 // The symbol we are tracking is the receiver.
2445 AEffects.push_back(Summ->getReceiverEffect());
2446 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002447 }
2448 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002449 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002450
Ted Kremenek2126bef2009-02-18 21:57:45 +00002451 do {
2452 // Get the previous type state.
2453 RefVal PrevV = *PrevT;
2454
2455 // Specially handle CFMakeCollectable and friends.
2456 if (contains(AEffects, MakeCollectable)) {
2457 // Get the name of the function.
2458 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2459 loc::FuncVal FV =
2460 cast<loc::FuncVal>(CurrSt.GetSVal(cast<CallExpr>(S)->getCallee()));
2461 const std::string& FName = FV.getDecl()->getNameAsString();
2462
2463 if (TF.isGCEnabled()) {
2464 // Determine if the object's reference count was pushed to zero.
2465 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2466
2467 os << "In GC mode a call to '" << FName
2468 << "' decrements an object's retain count and registers the "
2469 "object with the garbage collector. ";
2470
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002471 if (CurrV.getKind() == RefVal::Released) {
2472 assert(CurrV.getCount() == 0);
2473 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002474 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002475 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002476 else
2477 os << "An object must have a 0 retain count to be garbage collected. "
2478 "After this call its retain count is +" << CurrV.getCount()
2479 << '.';
2480 }
2481 else
2482 os << "When GC is not enabled a call to '" << FName
2483 << "' has no effect on its argument.";
2484
2485 // Nothing more to say.
2486 break;
2487 }
2488
2489 // Determine if the typestate has changed.
2490 if (!(PrevV == CurrV))
2491 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002492 case RefVal::Owned:
2493 case RefVal::NotOwned:
2494
2495 if (PrevV.getCount() == CurrV.getCount())
2496 return 0;
2497
2498 if (PrevV.getCount() > CurrV.getCount())
2499 os << "Reference count decremented.";
2500 else
2501 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002502
Ted Kremenekc26c4692009-02-18 03:48:14 +00002503 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002504 os << " The object now has +" << Count;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002505
2506 if (Count > 1)
2507 os << " retain counts.";
2508 else
2509 os << " retain count.";
2510 }
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002511
2512 if (PrevV.getKind() == RefVal::Released) {
2513 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2514 os << " The object is not eligible for garbage collection until the "
2515 "retain count reaches 0 again.";
2516 }
2517
Ted Kremenekc26c4692009-02-18 03:48:14 +00002518 break;
2519
2520 case RefVal::Released:
2521 os << "Object released.";
2522 break;
2523
2524 case RefVal::ReturnedOwned:
2525 os << "Object returned to caller as an owning reference (single retain "
2526 "count transferred to caller).";
2527 break;
2528
2529 case RefVal::ReturnedNotOwned:
2530 os << "Object returned to caller with a +0 (non-owning) retain count.";
2531 break;
2532
2533 default:
2534 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002535 }
2536
2537 // Emit any remaining diagnostics for the argument effects (if any).
2538 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2539 E=AEffects.end(); I != E; ++I) {
2540
2541 // A bunch of things have alternate behavior under GC.
2542 if (TF.isGCEnabled())
2543 switch (*I) {
2544 default: break;
2545 case Autorelease:
2546 os << "In GC mode an 'autorelease' has no effect.";
2547 continue;
2548 case IncRefMsg:
2549 os << "In GC mode the 'retain' message has no effect.";
2550 continue;
2551 case DecRefMsg:
2552 os << "In GC mode the 'release' message has no effect.";
2553 continue;
2554 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002555 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002556 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002557
2558 if (os.str().empty())
2559 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002560
2561 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2562 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenekbc543722009-01-28 04:47:13 +00002563 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002564
2565 // Add the range by scanning the children of the statement for any bindings
2566 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002567 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2568 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek335a3022009-01-28 05:06:46 +00002569 SVal X = CurrSt.GetSVal(Exp);
Zhongxing Xu097fc982008-10-17 05:57:07 +00002570 if (loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&X))
Ted Kremenekfd3f8da2009-02-18 22:17:20 +00002571 if (SV->getSymbol() == Sym) {
2572 P->addRange(Exp->getSourceRange());
2573 break;
2574 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002575 }
2576
2577 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002578}
2579
Ted Kremenekb15eba42008-10-04 05:50:14 +00002580namespace {
2581class VISIBILITY_HIDDEN FindUniqueBinding :
2582 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002583 SymbolRef Sym;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002584 MemRegion* Binding;
2585 bool First;
2586
2587 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002588 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002589
Zhongxing Xu097fc982008-10-17 05:57:07 +00002590 bool HandleBinding(StoreManager& SMgr, Store store, MemRegion* R, SVal val) {
2591 if (const loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&val)) {
Ted Kremenekb15eba42008-10-04 05:50:14 +00002592 if (SV->getSymbol() != Sym)
2593 return true;
2594 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002595 else if (const nonloc::SymbolVal* SV=dyn_cast<nonloc::SymbolVal>(&val)) {
Ted Kremenekb15eba42008-10-04 05:50:14 +00002596 if (SV->getSymbol() != Sym)
2597 return true;
2598 }
2599 else
2600 return true;
2601
2602 if (Binding) {
2603 First = false;
2604 return false;
2605 }
2606 else
2607 Binding = R;
2608
2609 return true;
2610 }
2611
2612 operator bool() { return First && Binding; }
2613 MemRegion* getRegion() { return Binding; }
2614};
2615}
2616
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002617static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00002618GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002619 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00002620
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002621 // Find both first node that referred to the tracked symbol and the
2622 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002623 const ExplodedNode<GRState>* Last = N;
2624 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002625
2626 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002627 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002628 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002629
Ted Kremenek6064a362008-07-07 16:21:19 +00002630 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002631 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002632
Ted Kremenek86617f42009-02-07 22:19:59 +00002633 FindUniqueBinding FB(Sym);
2634 StateMgr.iterBindings(St, FB);
2635 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002636
Ted Kremenekd7e26782008-05-16 18:33:44 +00002637 Last = N;
2638 N = N->pred_empty() ? NULL : *(N->pred_begin());
2639 }
2640
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002641 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002642}
Ted Kremenek4c479322008-05-06 23:07:13 +00002643
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002644PathDiagnosticPiece*
2645CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002646
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002647 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek86953652008-05-22 23:45:19 +00002648 // Tell the BugReporter to report cases when the tracked symbol is
2649 // assigned to different variables, etc.
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002650 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002651 return RangedBugReport::getEndPath(BR, EndN);
2652}
2653
2654PathDiagnosticPiece*
2655CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2656
2657 GRBugReporter& BR = cast<GRBugReporter>(br);
2658 // Tell the BugReporter to report cases when the tracked symbol is
2659 // assigned to different variables, etc.
2660 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2661
2662 // We are reporting a leak. Walk up the graph to get to the first node where
2663 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00002664 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002665 const ExplodedNode<GRState>* AllocNode = 0;
2666 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002667
2668 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00002669 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002670
Ted Kremenekd7e26782008-05-16 18:33:44 +00002671 // Get the allocate site.
2672 assert (AllocNode);
2673 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002674
Ted Kremenekea794e92008-05-05 18:50:19 +00002675 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00002676 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002677
Ted Kremeneke0336742009-02-18 23:28:26 +00002678 // Get the leak site. We want to find the last place where the symbol
2679 // was used in an expression.
2680 const ExplodedNode<GRState>* LeakN = EndN;
2681 Stmt *S = 0;
Ted Kremenekea794e92008-05-05 18:50:19 +00002682
Ted Kremeneke0336742009-02-18 23:28:26 +00002683 while (LeakN) {
2684 ProgramPoint P = LeakN->getLocation();
Ted Kremeneke0336742009-02-18 23:28:26 +00002685
2686 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2687 S = PS->getStmt();
2688 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
2689 S = BE->getSrc()->getTerminator();
2690
2691 if (S) {
2692 // Scan 'S' for uses of Sym.
2693 GRStateRef state(LeakN->getState(), BR.getStateManager());
2694 bool foundSymbol = false;
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002695
2696 // First check if 'S' itself binds to the symbol.
2697 if (Expr *Ex = dyn_cast<Expr>(S)) {
2698 SVal X = state.GetSVal(Ex);
2699 if (isa<loc::SymbolVal>(X) &&
2700 cast<loc::SymbolVal>(X).getSymbol() == Sym)
2701 foundSymbol = true;
2702 }
2703
2704 if (!foundSymbol)
2705 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2706 I!=E; ++I)
2707 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
2708 SVal X = state.GetSVal(Ex);
2709 if (isa<loc::SymbolVal>(X) &&
2710 cast<loc::SymbolVal>(X).getSymbol() == Sym){
2711 foundSymbol = true;
2712 break;
2713 }
Ted Kremeneke0336742009-02-18 23:28:26 +00002714 }
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002715
Ted Kremeneke0336742009-02-18 23:28:26 +00002716 if (foundSymbol)
2717 break;
2718 }
2719
2720 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2721 }
2722
2723 assert(LeakN && S && "No leak site found.");
Ted Kremenekea794e92008-05-05 18:50:19 +00002724
Ted Kremenekea794e92008-05-05 18:50:19 +00002725 // Generate the diagnostic.
Ted Kremenek323207b2009-02-18 22:59:04 +00002726 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenek59f9fe12009-02-07 21:59:45 +00002727 std::string sbuf;
2728 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00002729
Ted Kremenekea794e92008-05-05 18:50:19 +00002730 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002731
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002732 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002733 os << " and stored into '" << FirstBinding->getString() << '\'';
2734
Ted Kremenek311f3d42008-10-22 23:56:21 +00002735 // Get the retain count.
2736 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2737
2738 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00002739 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2740 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2741 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00002742 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2743 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00002744 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00002745 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00002746 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002747 " in the Memory Management Guide for Cocoa (object leaked).";
2748 }
2749 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00002750 os << " is no longer referenced after this point and has a retain count of"
2751 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002752 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002753
Ted Kremenek323207b2009-02-18 22:59:04 +00002754 return new PathDiagnosticPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002755}
2756
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002757
Ted Kremenekc26c4692009-02-18 03:48:14 +00002758CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2759 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00002760 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002761 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00002762{
2763
Ted Kremenekd7e26782008-05-16 18:33:44 +00002764 // Most bug reports are cached at the location where they occured.
2765 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00002766 // allocated, and only report a single path. To do this, we need to find
2767 // the allocation site of a piece of tracked memory, which we do via a
2768 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2769 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2770 // that all ancestor nodes that represent the allocation site have the
2771 // same SourceLocation.
2772 const ExplodedNode<GRState>* AllocNode = 0;
2773
2774 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00002775 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00002776
Ted Kremenek86617f42009-02-07 22:19:59 +00002777 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00002778 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00002779 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00002780
2781 // Fill in the description of the bug.
2782 Description.clear();
2783 llvm::raw_string_ostream os(Description);
2784 SourceManager& SMgr = Eng.getContext().getSourceManager();
2785 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00002786 os << "Potential leak of object allocated on line " << AllocLine;
2787
2788 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2789 if (AllocBinding)
2790 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00002791}
2792
Ted Kremeneka7338b42008-03-11 06:39:11 +00002793//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00002794// Handle dead symbols and end-of-path.
2795//===----------------------------------------------------------------------===//
2796
2797void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2798 GREndPathNodeBuilder<GRState>& Builder) {
2799
2800 const GRState* St = Builder.getState();
2801 RefBindings B = St->get<RefBindings>();
2802
2803 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2804 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2805
2806 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2807 bool hasLeak = false;
2808
2809 std::pair<GRStateRef, bool> X =
2810 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2811 (*I).first, (*I).second, hasLeak);
2812
2813 St = X.first;
2814 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2815 }
2816
2817 if (Leaked.empty())
2818 return;
2819
2820 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2821
2822 if (!N)
2823 return;
2824
2825 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2826 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2827
2828 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2829 : leakWithinFunction);
2830 assert(BT && "BugType not initialized.");
Ted Kremenekc26c4692009-02-18 03:48:14 +00002831 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00002832 BR->EmitReport(report);
2833 }
2834}
2835
2836void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2837 GRExprEngine& Eng,
2838 GRStmtNodeBuilder<GRState>& Builder,
2839 ExplodedNode<GRState>* Pred,
2840 Stmt* S,
2841 const GRState* St,
2842 SymbolReaper& SymReaper) {
2843
Ted Kremenek876d8df2009-02-19 23:47:02 +00002844 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00002845 RefBindings B = St->get<RefBindings>();
2846 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2847
2848 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2849 E = SymReaper.dead_end(); I != E; ++I) {
2850
2851 const RefVal* T = B.lookup(*I);
2852 if (!T) continue;
2853
2854 bool hasLeak = false;
2855
2856 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00002857 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00002858
2859 St = X.first;
2860
2861 if (hasLeak)
2862 Leaked.push_back(std::make_pair(*I,X.second));
2863 }
2864
Ted Kremenek876d8df2009-02-19 23:47:02 +00002865 if (!Leaked.empty()) {
2866 // Create a new intermediate node representing the leak point. We
2867 // use a special program point that represents this checker-specific
2868 // transition. We use the address of RefBIndex as a unique tag for this
2869 // checker. We will create another node (if we don't cache out) that
2870 // removes the retain-count bindings from the state.
2871 // NOTE: We use 'generateNode' so that it does interplay with the
2872 // auto-transition logic.
2873 ExplodedNode<GRState>* N =
2874 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00002875
Ted Kremenek876d8df2009-02-19 23:47:02 +00002876 if (!N)
2877 return;
2878
2879 // Generate the bug reports.
2880 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
2881 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2882
2883 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2884 : leakWithinFunction);
2885 assert(BT && "BugType not initialized.");
2886 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
2887 BR->EmitReport(report);
2888 }
Ted Kremenek708af042009-02-05 06:50:21 +00002889
Ted Kremenek876d8df2009-02-19 23:47:02 +00002890 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00002891 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00002892
2893 // Now generate a new node that nukes the old bindings.
2894 GRStateRef state(St, Eng.getStateManager());
2895 RefBindings::Factory& F = state.get_context<RefBindings>();
2896
2897 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2898 E = SymReaper.dead_end(); I!=E; ++I)
2899 B = F.Remove(B, *I);
2900
2901 state = state.set<RefBindings>(B);
2902 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00002903}
2904
2905void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2906 GRStmtNodeBuilder<GRState>& Builder,
2907 Expr* NodeExpr, Expr* ErrorExpr,
2908 ExplodedNode<GRState>* Pred,
2909 const GRState* St,
2910 RefVal::Kind hasErr, SymbolRef Sym) {
2911 Builder.BuildSinks = true;
2912 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2913
2914 if (!N) return;
2915
2916 CFRefBug *BT = 0;
2917
2918 if (hasErr == RefVal::ErrorUseAfterRelease)
2919 BT = static_cast<CFRefBug*>(useAfterRelease);
2920 else {
2921 assert(hasErr == RefVal::ErrorReleaseNotOwned);
2922 BT = static_cast<CFRefBug*>(releaseNotOwned);
2923 }
2924
Ted Kremenekc26c4692009-02-18 03:48:14 +00002925 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00002926 report->addRange(ErrorExpr->getSourceRange());
2927 BR->EmitReport(report);
2928}
2929
2930//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00002931// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002932//===----------------------------------------------------------------------===//
2933
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002934GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2935 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00002936 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00002937}