blob: b6c11c9cfc82951b117863a86540d6039f3d4272 [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
152static bool followsReturnRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000153 NamingConvention C = deriveNamingConvention(s);
154 return C == CreateRule || C == InitRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000155}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000156
Ted Kremenek7d421f32008-04-09 23:49:11 +0000157//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000158// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000159//===----------------------------------------------------------------------===//
160
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000161static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000162 IdentifierInfo* II = &Ctx.Idents.get(name);
163 return Ctx.Selectors.getSelector(0, &II);
164}
165
Ted Kremenek0e344d42008-05-06 00:30:21 +0000166static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(1, &II);
169}
170
Ted Kremenek272aa852008-06-25 21:21:56 +0000171//===----------------------------------------------------------------------===//
172// Type querying functions.
173//===----------------------------------------------------------------------===//
174
Ted Kremenek17144e82009-01-12 21:45:02 +0000175static bool hasPrefix(const char* s, const char* prefix) {
176 if (!prefix)
177 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000178
Ted Kremenek17144e82009-01-12 21:45:02 +0000179 char c = *s;
180 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000181
Ted Kremenek17144e82009-01-12 21:45:02 +0000182 while (c != '\0' && cP != '\0') {
183 if (c != cP) break;
184 c = *(++s);
185 cP = *(++prefix);
186 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000187
Ted Kremenek17144e82009-01-12 21:45:02 +0000188 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000189}
190
Ted Kremenek17144e82009-01-12 21:45:02 +0000191static bool hasSuffix(const char* s, const char* suffix) {
192 const char* loc = strstr(s, suffix);
193 return loc && strcmp(suffix, loc) == 0;
194}
195
196static bool isRefType(QualType RetTy, const char* prefix,
197 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000198
Ted Kremenek17144e82009-01-12 21:45:02 +0000199 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
200 const char* TDName = TD->getDecl()->getIdentifier()->getName();
201 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
202 }
203
204 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000205 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000206
207 // Is the type void*?
208 const PointerType* PT = RetTy->getAsPointerType();
209 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Does the name start with the prefix?
213 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000214}
215
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000216//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000217// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000218//===----------------------------------------------------------------------===//
219
Ted Kremenek272aa852008-06-25 21:21:56 +0000220namespace {
221/// ArgEffect is used to summarize a function/method call's effect on a
222/// particular argument.
Ted Kremenek58dd95b2009-02-18 18:54:33 +0000223enum ArgEffect { IncRefMsg, IncRef,
224 DecRefMsg, DecRef,
Ted Kremenek2126bef2009-02-18 21:57:45 +0000225 MakeCollectable,
Ted Kremenek58dd95b2009-02-18 18:54:33 +0000226 DoNothing, DoNothingByRef,
Ted Kremenekaac82832009-02-23 17:45:03 +0000227 StopTracking, MayEscape, SelfOwn, Autorelease,
228 NewAutoreleasePool };
Ted Kremenek272aa852008-06-25 21:21:56 +0000229
230/// ArgEffects summarizes the effects of a function/method call on all of
231/// its arguments.
232typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000233}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000234
Ted Kremeneka7338b42008-03-11 06:39:11 +0000235namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000236template <> struct FoldingSetTrait<ArgEffects> {
237 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
238 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
239 ID.AddInteger(I->first);
240 ID.AddInteger((unsigned) I->second);
241 }
242 }
243};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000244} // end llvm namespace
245
246namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000247
248/// RetEffect is used to summarize a function/method call's behavior with
249/// respect to its return value.
250class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000251public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000252 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
253 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000254
255 enum ObjKind { CF, ObjC, AnyObj };
256
Ted Kremeneka7338b42008-03-11 06:39:11 +0000257private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000258 Kind K;
259 ObjKind O;
260 unsigned index;
261
262 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
263 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000264
Ted Kremeneka7338b42008-03-11 06:39:11 +0000265public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000266 Kind getKind() const { return K; }
267
268 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000269
270 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000271 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000272 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000273 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000274
Ted Kremenek272aa852008-06-25 21:21:56 +0000275 static RetEffect MakeAlias(unsigned Idx) {
276 return RetEffect(Alias, Idx);
277 }
278 static RetEffect MakeReceiverAlias() {
279 return RetEffect(ReceiverAlias);
280 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000281 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
282 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000283 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000284 static RetEffect MakeNotOwned(ObjKind o) {
285 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000286 }
287 static RetEffect MakeNoRet() {
288 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000289 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000290
Ted Kremenek272aa852008-06-25 21:21:56 +0000291 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000292 ID.AddInteger((unsigned)K);
293 ID.AddInteger((unsigned)O);
294 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000295 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000296};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000297
Ted Kremenek272aa852008-06-25 21:21:56 +0000298
299class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000300 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
301 /// specifies the argument (starting from 0). This can be sparsely
302 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000303 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000304
305 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
306 /// do not have an entry in Args.
307 ArgEffect DefaultArgEffect;
308
Ted Kremenek272aa852008-06-25 21:21:56 +0000309 /// Receiver - If this summary applies to an Objective-C message expression,
310 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000311 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000312
313 /// Ret - The effect on the return value. Used to indicate if the
314 /// function/method call returns a new tracked symbol, returns an
315 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000316 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000317
Ted Kremenekf2717b02008-07-18 17:24:20 +0000318 /// EndPath - Indicates that execution of this method/function should
319 /// terminate the simulation of a path.
320 bool EndPath;
321
Ted Kremeneka7338b42008-03-11 06:39:11 +0000322public:
323
Ted Kremenekbcaff792008-05-06 15:44:25 +0000324 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000325 ArgEffect ReceiverEff, bool endpath = false)
326 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
327 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000328
Ted Kremenek272aa852008-06-25 21:21:56 +0000329 /// getArg - Return the argument effect on the argument specified by
330 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000331 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000332
Ted Kremenekae855d42008-04-24 17:22:33 +0000333 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000334 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000335
336 // If Args is present, it is likely to contain only 1 element.
337 // Just do a linear search. Do it from the back because functions with
338 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000339 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000340 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
341 I!=E; ++I) {
342
343 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000344 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000345
346 if (idx == I->first)
347 return I->second;
348 }
349
Ted Kremenekbcaff792008-05-06 15:44:25 +0000350 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000351 }
352
Ted Kremenek272aa852008-06-25 21:21:56 +0000353 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000354 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000355 return Ret;
356 }
357
Ted Kremenekf2717b02008-07-18 17:24:20 +0000358 /// isEndPath - Returns true if executing the given method/function should
359 /// terminate the path.
360 bool isEndPath() const { return EndPath; }
361
Ted Kremenek272aa852008-06-25 21:21:56 +0000362 /// getReceiverEffect - Returns the effect on the receiver of the call.
363 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000364 ArgEffect getReceiverEffect() const {
365 return Receiver;
366 }
367
Ted Kremenek2719e982008-06-17 02:43:46 +0000368 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000369
Ted Kremenek2719e982008-06-17 02:43:46 +0000370 ExprIterator begin_args() const { return Args->begin(); }
371 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000372
Ted Kremenek266d8b62008-05-06 02:26:56 +0000373 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000374 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000375 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000376 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000377 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000378 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000379 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000380 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000381 }
382
383 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000384 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000385 }
386};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000387} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000388
Ted Kremenek272aa852008-06-25 21:21:56 +0000389//===----------------------------------------------------------------------===//
390// Data structures for constructing summaries.
391//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000392
Ted Kremenek272aa852008-06-25 21:21:56 +0000393namespace {
394class VISIBILITY_HIDDEN ObjCSummaryKey {
395 IdentifierInfo* II;
396 Selector S;
397public:
398 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
399 : II(ii), S(s) {}
400
401 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
402 : II(d ? d->getIdentifier() : 0), S(s) {}
403
404 ObjCSummaryKey(Selector s)
405 : II(0), S(s) {}
406
407 IdentifierInfo* getIdentifier() const { return II; }
408 Selector getSelector() const { return S; }
409};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000410}
411
412namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000413template <> struct DenseMapInfo<ObjCSummaryKey> {
414 static inline ObjCSummaryKey getEmptyKey() {
415 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
416 DenseMapInfo<Selector>::getEmptyKey());
417 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000418
Ted Kremenek272aa852008-06-25 21:21:56 +0000419 static inline ObjCSummaryKey getTombstoneKey() {
420 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
421 DenseMapInfo<Selector>::getTombstoneKey());
422 }
423
424 static unsigned getHashValue(const ObjCSummaryKey &V) {
425 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
426 & 0x88888888)
427 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
428 & 0x55555555);
429 }
430
431 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
432 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
433 RHS.getIdentifier()) &&
434 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
435 RHS.getSelector());
436 }
437
438 static bool isPod() {
439 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
440 DenseMapInfo<Selector>::isPod();
441 }
442};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000443} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000444
Ted Kremenek84f010c2008-06-23 23:30:29 +0000445namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000446class VISIBILITY_HIDDEN ObjCSummaryCache {
447 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
448 MapTy M;
449public:
450 ObjCSummaryCache() {}
451
452 typedef MapTy::iterator iterator;
453
454 iterator find(ObjCInterfaceDecl* D, Selector S) {
455
456 // Do a lookup with the (D,S) pair. If we find a match return
457 // the iterator.
458 ObjCSummaryKey K(D, S);
459 MapTy::iterator I = M.find(K);
460
461 if (I != M.end() || !D)
462 return I;
463
464 // Walk the super chain. If we find a hit with a parent, we'll end
465 // up returning that summary. We actually allow that key (null,S), as
466 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
467 // generate initial summaries without having to worry about NSObject
468 // being declared.
469 // FIXME: We may change this at some point.
470 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
471 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
472 break;
473
474 if (!C)
475 return I;
476 }
477
478 // Cache the summary with original key to make the next lookup faster
479 // and return the iterator.
480 M[K] = I->second;
481 return I;
482 }
483
Ted Kremenek9449ca92008-08-12 20:41:56 +0000484
Ted Kremenek272aa852008-06-25 21:21:56 +0000485 iterator find(Expr* Receiver, Selector S) {
486 return find(getReceiverDecl(Receiver), S);
487 }
488
489 iterator find(IdentifierInfo* II, Selector S) {
490 // FIXME: Class method lookup. Right now we dont' have a good way
491 // of going between IdentifierInfo* and the class hierarchy.
492 iterator I = M.find(ObjCSummaryKey(II, S));
493 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
494 }
495
496 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
497
498 const PointerType* PT = E->getType()->getAsPointerType();
499 if (!PT) return 0;
500
501 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
502 if (!OI) return 0;
503
504 return OI ? OI->getDecl() : 0;
505 }
506
507 iterator end() { return M.end(); }
508
509 RetainSummary*& operator[](ObjCMessageExpr* ME) {
510
511 Selector S = ME->getSelector();
512
513 if (Expr* Receiver = ME->getReceiver()) {
514 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
515 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
516 }
517
518 return M[ObjCSummaryKey(ME->getClassName(), S)];
519 }
520
521 RetainSummary*& operator[](ObjCSummaryKey K) {
522 return M[K];
523 }
524
525 RetainSummary*& operator[](Selector S) {
526 return M[ ObjCSummaryKey(S) ];
527 }
528};
529} // end anonymous namespace
530
531//===----------------------------------------------------------------------===//
532// Data structures for managing collections of summaries.
533//===----------------------------------------------------------------------===//
534
535namespace {
536class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000537
538 //==-----------------------------------------------------------------==//
539 // Typedefs.
540 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000541
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000542 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
543 ArgEffectsSetTy;
544
545 typedef llvm::FoldingSet<RetainSummary>
546 SummarySetTy;
547
548 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
549 FuncSummariesTy;
550
Ted Kremenek84f010c2008-06-23 23:30:29 +0000551 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000552
553 //==-----------------------------------------------------------------==//
554 // Data.
555 //==-----------------------------------------------------------------==//
556
Ted Kremenek272aa852008-06-25 21:21:56 +0000557 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000558 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000559
Ted Kremenekede40b72008-07-09 18:11:16 +0000560 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
561 /// "CFDictionaryCreate".
562 IdentifierInfo* CFDictionaryCreateII;
563
Ted Kremenek272aa852008-06-25 21:21:56 +0000564 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000565 const bool GCEnabled;
566
Ted Kremenek272aa852008-06-25 21:21:56 +0000567 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000568 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000569
Ted Kremenek272aa852008-06-25 21:21:56 +0000570 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000571 FuncSummariesTy FuncSummaries;
572
Ted Kremenek272aa852008-06-25 21:21:56 +0000573 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
574 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000575 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000576
Ted Kremenek272aa852008-06-25 21:21:56 +0000577 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000578 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000579
Ted Kremenek272aa852008-06-25 21:21:56 +0000580 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000581 ArgEffectsSetTy ArgEffectsSet;
582
Ted Kremenek272aa852008-06-25 21:21:56 +0000583 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
584 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000585 llvm::BumpPtrAllocator BPAlloc;
586
Ted Kremenek272aa852008-06-25 21:21:56 +0000587 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000588 ArgEffects ScratchArgs;
589
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000590 RetainSummary* StopSummary;
591
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000592 //==-----------------------------------------------------------------==//
593 // Methods.
594 //==-----------------------------------------------------------------==//
595
Ted Kremenek272aa852008-06-25 21:21:56 +0000596 /// getArgEffects - Returns a persistent ArgEffects object based on the
597 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000598 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000599
Ted Kremenek562c1302008-05-05 16:51:50 +0000600 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000601
602public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000603 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000604
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000605 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
606 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000607 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000608
Ted Kremenek266d8b62008-05-06 02:26:56 +0000609 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000610 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000611 ArgEffect DefaultEff = MayEscape,
612 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000613
Ted Kremenek266d8b62008-05-06 02:26:56 +0000614 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000615 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000616 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000617 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000618 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000619
Ted Kremenekbcaff792008-05-06 15:44:25 +0000620 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000621 if (StopSummary)
622 return StopSummary;
623
624 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
625 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000626
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000627 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000628 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000629
Ted Kremenek272aa852008-06-25 21:21:56 +0000630 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000631
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000632 void InitializeClassMethodSummaries();
633 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000634
Ted Kremenek35920ed2009-01-07 00:39:56 +0000635 bool isTrackedObjectType(QualType T);
636
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000637private:
638
Ted Kremenekf2717b02008-07-18 17:24:20 +0000639 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
640 RetainSummary* Summ) {
641 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
642 }
643
Ted Kremenek272aa852008-06-25 21:21:56 +0000644 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
645 ObjCClassMethodSummaries[S] = Summ;
646 }
647
648 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
649 ObjCMethodSummaries[S] = Summ;
650 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000651
652 void addClassMethSummary(const char* Cls, const char* nullaryName,
653 RetainSummary *Summ) {
654 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
655 Selector S = GetNullarySelector(nullaryName, Ctx);
656 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
657 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000658
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000659 void addInstMethSummary(const char* Cls, const char* nullaryName,
660 RetainSummary *Summ) {
661 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
662 Selector S = GetNullarySelector(nullaryName, Ctx);
663 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
664 }
665
Ted Kremenek45642a42008-08-12 18:48:50 +0000666 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenekf2717b02008-07-18 17:24:20 +0000667
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000668 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
669 llvm::SmallVector<IdentifierInfo*, 10> II;
670
671 while (const char* s = va_arg(argp, const char*))
672 II.push_back(&Ctx.Idents.get(s));
673
674 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000675 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
676 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000677
678 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
679 va_list argp;
680 va_start(argp, Summ);
681 addInstMethSummary(Cls, Summ, argp);
682 va_end(argp);
683 }
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000684
685 void addPanicSummary(const char* Cls, ...) {
686 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
687 DoNothing, DoNothing, true);
688 va_list argp;
689 va_start (argp, Cls);
Ted Kremenek45642a42008-08-12 18:48:50 +0000690 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000691 va_end(argp);
692 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000693
Ted Kremeneka7338b42008-03-11 06:39:11 +0000694public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000695
696 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000697 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000698 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000699 GCEnabled(gcenabled), StopSummary(0) {
700
701 InitializeClassMethodSummaries();
702 InitializeMethodSummaries();
703 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000704
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000705 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000706
Ted Kremenekd13c1872008-06-24 03:56:45 +0000707 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000708 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000709 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenek926abf22008-05-06 04:20:12 +0000710
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000711 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000712};
713
714} // end anonymous namespace
715
716//===----------------------------------------------------------------------===//
717// Implementation of checker data structures.
718//===----------------------------------------------------------------------===//
719
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000720RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000721
722 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
723 // mitigating the need to do explicit cleanup of the
724 // Argument-Effect summaries.
725
Ted Kremenek42ea0322008-05-05 23:55:01 +0000726 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
727 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000728 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000729}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000730
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000731ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000732
Ted Kremenekae855d42008-04-24 17:22:33 +0000733 if (ScratchArgs.empty())
734 return NULL;
735
736 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000737 llvm::FoldingSetNodeID profile;
738 profile.Add(ScratchArgs);
739 void* InsertPos;
740
Ted Kremenekae855d42008-04-24 17:22:33 +0000741 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000742 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000743 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000744
Ted Kremenekae855d42008-04-24 17:22:33 +0000745 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000746 ScratchArgs.clear();
747 return &E->getValue();
748 }
749
750 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000751 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000752
753 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000754 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000755
756 ScratchArgs.clear();
757 return &E->getValue();
758}
759
Ted Kremenek266d8b62008-05-06 02:26:56 +0000760RetainSummary*
761RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000762 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000763 ArgEffect DefaultEff,
764 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000765
Ted Kremenekae855d42008-04-24 17:22:33 +0000766 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000767 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000768 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
769 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000770
Ted Kremenekae855d42008-04-24 17:22:33 +0000771 // Look up the uniqued summary, or create one if it doesn't exist.
772 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000773 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000774
775 if (Summ)
776 return Summ;
777
Ted Kremenekae855d42008-04-24 17:22:33 +0000778 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000779 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000780 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000781 SummarySet.InsertNode(Summ, InsertPos);
782
783 return Summ;
784}
785
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000786//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000787// Predicates.
788//===----------------------------------------------------------------------===//
789
790bool RetainSummaryManager::isTrackedObjectType(QualType T) {
791 if (!Ctx.isObjCObjectPointerType(T))
792 return false;
793
794 // Does it subclass NSObject?
795 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
796
797 // We assume that id<..>, id, and "Class" all represent tracked objects.
798 if (!OT)
799 return true;
800
801 // Does the object type subclass NSObject?
802 // FIXME: We can memoize here if this gets too expensive.
803 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
804 ObjCInterfaceDecl* ID = OT->getDecl();
805
806 for ( ; ID ; ID = ID->getSuperClass())
807 if (ID->getIdentifier() == NSObjectII)
808 return true;
809
810 return false;
811}
812
813//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000814// Summary creation for functions (largely uses of Core Foundation).
815//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000816
Ted Kremenek17144e82009-01-12 21:45:02 +0000817static bool isRetain(FunctionDecl* FD, const char* FName) {
818 const char* loc = strstr(FName, "Retain");
819 return loc && loc[sizeof("Retain")-1] == '\0';
820}
821
822static bool isRelease(FunctionDecl* FD, const char* FName) {
823 const char* loc = strstr(FName, "Release");
824 return loc && loc[sizeof("Release")-1] == '\0';
825}
826
Ted Kremenekd13c1872008-06-24 03:56:45 +0000827RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000828
829 SourceLocation Loc = FD->getLocation();
830
831 if (!Loc.isFileID())
832 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000833
Ted Kremenekae855d42008-04-24 17:22:33 +0000834 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000835 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000836
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000837 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000838 return I->second;
839
840 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000841 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000842
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000843 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000844 // We generate "stop" summaries for implicitly defined functions.
845 if (FD->isImplicit()) {
846 S = getPersistentStopSummary();
847 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000848 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000849
Ted Kremenek064ef322009-02-23 16:51:39 +0000850 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000851 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000852 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000853 const char* FName = FD->getIdentifier()->getName();
854
Ted Kremenek38c6f022009-03-05 22:11:14 +0000855 // Strip away preceding '_'. Doing this here will effect all the checks
856 // down below.
857 while (*FName == '_') ++FName;
858
Ted Kremenek17144e82009-01-12 21:45:02 +0000859 // Inspect the result type.
860 QualType RetTy = FT->getResultType();
861
862 // FIXME: This should all be refactored into a chain of "summary lookup"
863 // filters.
864 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
865 // FIXES: <rdar://problem/6326900>
866 // This should be addressed using a API table. This strcmp is also
867 // a little gross, but there is no need to super optimize here.
868 assert (ScratchArgs.empty());
869 ScratchArgs.push_back(std::make_pair(1, DecRef));
870 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
871 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000872 }
Ted Kremenek17144e82009-01-12 21:45:02 +0000873
874 // Handle: id NSMakeCollectable(CFTypeRef)
875 if (strcmp(FName, "NSMakeCollectable") == 0) {
876 S = (RetTy == Ctx.getObjCIdType())
877 ? getUnarySummary(FT, cfmakecollectable)
878 : getPersistentStopSummary();
879
880 break;
881 }
882
883 if (RetTy->isPointerType()) {
884 // For CoreFoundation ('CF') types.
885 if (isRefType(RetTy, "CF", &Ctx, FName)) {
886 if (isRetain(FD, FName))
887 S = getUnarySummary(FT, cfretain);
888 else if (strstr(FName, "MakeCollectable"))
889 S = getUnarySummary(FT, cfmakecollectable);
890 else
891 S = getCFCreateGetRuleSummary(FD, FName);
892
893 break;
894 }
895
896 // For CoreGraphics ('CG') types.
897 if (isRefType(RetTy, "CG", &Ctx, FName)) {
898 if (isRetain(FD, FName))
899 S = getUnarySummary(FT, cfretain);
900 else
901 S = getCFCreateGetRuleSummary(FD, FName);
902
903 break;
904 }
905
906 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
907 if (isRefType(RetTy, "DADisk") ||
908 isRefType(RetTy, "DADissenter") ||
909 isRefType(RetTy, "DASessionRef")) {
910 S = getCFCreateGetRuleSummary(FD, FName);
911 break;
912 }
913
914 break;
915 }
916
917 // Check for release functions, the only kind of functions that we care
918 // about that don't return a pointer type.
919 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000920 // Test for 'CGCF'.
921 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
922 FName += 4;
923 else
924 FName += 2;
925
926 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000927 S = getUnarySummary(FT, cfrelease);
928 else {
Ted Kremenek7b293682009-01-29 22:45:13 +0000929 assert (ScratchArgs.empty());
930 // Remaining CoreFoundation and CoreGraphics functions.
931 // We use to assume that they all strictly followed the ownership idiom
932 // and that ownership cannot be transferred. While this is technically
933 // correct, many methods allow a tracked object to escape. For example:
934 //
935 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
936 // CFDictionaryAddValue(y, key, x);
937 // CFRelease(x);
938 // ... it is okay to use 'x' since 'y' has a reference to it
939 //
940 // We handle this and similar cases with the follow heuristic. If the
941 // function name contains "InsertValue", "SetValue" or "AddValue" then
942 // we assume that arguments may "escape."
943 //
944 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
945 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000946 CStrInCStrNoCase(FName, "SetValue") ||
947 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000948 ? MayEscape : DoNothing;
949
950 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000951 }
952 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000953 }
954 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000955
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000956 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000957 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000958}
959
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000960RetainSummary*
961RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
962 const char* FName) {
963
Ted Kremenek562c1302008-05-05 16:51:50 +0000964 if (strstr(FName, "Create") || strstr(FName, "Copy"))
965 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000966
Ted Kremenek562c1302008-05-05 16:51:50 +0000967 if (strstr(FName, "Get"))
968 return getCFSummaryGetRule(FD);
969
970 return 0;
971}
972
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000973RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +0000974RetainSummaryManager::getUnarySummary(const FunctionType* FT,
975 UnaryFuncKind func) {
976
Ted Kremenek17144e82009-01-12 21:45:02 +0000977 // Sanity check that this is *really* a unary function. This can
978 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000979 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +0000980 if (!FTP || FTP->getNumArgs() != 1)
981 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000982
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000983 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000984
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000985 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +0000986 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000987 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000988 return getPersistentSummary(RetEffect::MakeAlias(0),
989 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000990 }
991
992 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000993 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000994 return getPersistentSummary(RetEffect::MakeNoRet(),
995 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000996 }
997
998 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +0000999 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1000 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001001 }
1002
1003 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001004 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001005 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001006 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001007}
1008
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001009RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001010 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001011
1012 if (FD->getIdentifier() == CFDictionaryCreateII) {
1013 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1014 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1015 }
1016
Ted Kremenek68621b92009-01-28 05:56:51 +00001017 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001018}
1019
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001020RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001021 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001022 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1023 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001024}
1025
Ted Kremeneka7338b42008-03-11 06:39:11 +00001026//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001027// Summary creation for Selectors.
1028//===----------------------------------------------------------------------===//
1029
Ted Kremenekbcaff792008-05-06 15:44:25 +00001030RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001031RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001032 assert(ScratchArgs.empty());
1033
Ted Kremenek802cfc72009-02-20 00:05:35 +00001034 // 'init' methods only return an alias if the return type is a location type.
1035 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001036 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +00001037 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1038 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001039
Ted Kremenek272aa852008-06-25 21:21:56 +00001040 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001041 return Summ;
1042}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001043
Ted Kremenek272aa852008-06-25 21:21:56 +00001044
Ted Kremenekbcaff792008-05-06 15:44:25 +00001045RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001046RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1047 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001048
1049 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001050
Ted Kremenek272aa852008-06-25 21:21:56 +00001051 // Look up a summary in our summary cache.
1052 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001053
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001054 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001055 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001056
Ted Kremenek35920ed2009-01-07 00:39:56 +00001057 // "initXXX": pass-through for receiver.
Ted Kremenek42ea0322008-05-05 23:55:01 +00001058 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001059 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001060
Ted Kremenek4395b452009-02-21 05:13:43 +00001061 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek35920ed2009-01-07 00:39:56 +00001062 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +00001063
Ted Kremenek35920ed2009-01-07 00:39:56 +00001064 // Look for methods that return an owned object.
1065 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek5496f6d2008-05-07 04:25:59 +00001066 return 0;
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001067
Ted Kremenek35920ed2009-01-07 00:39:56 +00001068 if (followsFundamentalRule(s)) {
1069 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001070 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001071 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +00001072 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +00001073 return Summ;
1074 }
Ted Kremenekbcaff792008-05-06 15:44:25 +00001075
Ted Kremenek42ea0322008-05-05 23:55:01 +00001076 return 0;
1077}
1078
Ted Kremeneka7722b72008-05-06 21:26:51 +00001079RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001080RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1081 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +00001082
Ted Kremenek272aa852008-06-25 21:21:56 +00001083 // FIXME: Eventually we should properly do class method summaries, but
1084 // it requires us being able to walk the type hierarchy. Unfortunately,
1085 // we cannot do this with just an IdentifierInfo* for the class name.
1086
Ted Kremeneka7722b72008-05-06 21:26:51 +00001087 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +00001088 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001089
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001090 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001091 return I->second;
1092
Ted Kremenek4c479322008-05-06 23:07:13 +00001093 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001094}
1095
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001096void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001097
1098 assert (ScratchArgs.empty());
1099
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001100 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001101 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001102
Ted Kremenek0e344d42008-05-06 00:30:21 +00001103 RetainSummary* Summ = getPersistentSummary(E);
1104
Ted Kremenek272aa852008-06-25 21:21:56 +00001105 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1106 // NSObject and its derivatives.
1107 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1108 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1109 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001110
1111 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001112 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001113 GetNullarySelector("currentHandler", Ctx),
1114 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001115
1116 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001117 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1118 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1119 GetUnarySelector("addObject", Ctx),
1120 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001121 DoNothing, Autorelease));
Ted Kremenek0e344d42008-05-06 00:30:21 +00001122}
1123
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001124void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001125
1126 assert (ScratchArgs.empty());
1127
Ted Kremeneka7722b72008-05-06 21:26:51 +00001128 // Create the "init" selector. It just acts as a pass-through for the
1129 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001130 RetainSummary* InitSumm =
1131 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001132 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001133
1134 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001135 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001136 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001137
Ted Kremeneke44927e2008-07-01 17:21:27 +00001138 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001139
1140 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001141 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1142
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001143 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001144 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001145
Ted Kremenek266d8b62008-05-06 02:26:56 +00001146 // Create the "retain" selector.
1147 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001148 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001149 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001150
1151 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001152 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001153 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001154
1155 // Create the "drain" selector.
1156 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001157 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001158
1159 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001160 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001161 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001162
Ted Kremenekaac82832009-02-23 17:45:03 +00001163 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001164 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001165 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001166 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001167
Ted Kremenek45642a42008-08-12 18:48:50 +00001168 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001169 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1170 // self-own themselves. However, they only do this once they are displayed.
1171 // Thus, we need to track an NSWindow's display status.
1172 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001173 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1174 addClassMethSummary("NSWindow", "alloc",
1175 getPersistentSummary(RetEffect::MakeNoRet()));
1176
1177#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001178 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001179 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001180
1181 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1182 "styleMask", "backing", "defer", NULL);
1183
1184 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1185 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001186#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001187
1188 // For NSPanel (which subclasses NSWindow), allocated objects are not
1189 // self-owned.
1190 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1191 "styleMask", "backing", "defer", NULL);
1192
1193 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1194 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001195
Ted Kremenekf2717b02008-07-18 17:24:20 +00001196 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001197 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1198 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001199
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001200 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1201 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001202}
1203
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001204//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001205// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001206//===----------------------------------------------------------------------===//
1207
Ted Kremeneka7338b42008-03-11 06:39:11 +00001208namespace {
1209
Ted Kremenek7d421f32008-04-09 23:49:11 +00001210class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001211public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001212 enum Kind {
1213 Owned = 0, // Owning reference.
1214 NotOwned, // Reference is not owned by still valid (not freed).
1215 Released, // Object has been released.
1216 ReturnedOwned, // Returned object passes ownership to caller.
1217 ReturnedNotOwned, // Return object does not pass ownership to caller.
1218 ErrorUseAfterRelease, // Object used after released.
1219 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek311f3d42008-10-22 23:56:21 +00001220 ErrorLeak, // A memory leak due to excessive reference counts.
1221 ErrorLeakReturned // A memory leak due to the returning method not having
1222 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001223 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001224
1225private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001226 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001227 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001228 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001229 QualType T;
1230
Ted Kremenek68621b92009-01-28 05:56:51 +00001231 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1232 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001233
Ted Kremenek68621b92009-01-28 05:56:51 +00001234 RefVal(Kind k, unsigned cnt = 0)
1235 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1236
1237public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001238 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001239
1240 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001241
Ted Kremenek272aa852008-06-25 21:21:56 +00001242 unsigned getCount() const { return Cnt; }
1243 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001244
1245 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001246
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001247 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1248
Ted Kremenek0106e202008-10-24 20:32:50 +00001249 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001250
Ted Kremenekffefc352008-04-11 22:25:11 +00001251 bool isOwned() const {
1252 return getKind() == Owned;
1253 }
1254
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001255 bool isNotOwned() const {
1256 return getKind() == NotOwned;
1257 }
1258
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001259 bool isReturnedOwned() const {
1260 return getKind() == ReturnedOwned;
1261 }
1262
1263 bool isReturnedNotOwned() const {
1264 return getKind() == ReturnedNotOwned;
1265 }
1266
1267 bool isNonLeakError() const {
1268 Kind k = getKind();
1269 return isError(k) && !isLeak(k);
1270 }
1271
1272 // State creation: normal state.
1273
Ted Kremenek68621b92009-01-28 05:56:51 +00001274 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1275 unsigned Count = 1) {
1276 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001277 }
1278
Ted Kremenek68621b92009-01-28 05:56:51 +00001279 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1280 unsigned Count = 0) {
1281 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001282 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001283
1284 static RefVal makeReturnedOwned(unsigned Count) {
1285 return RefVal(ReturnedOwned, Count);
1286 }
1287
1288 static RefVal makeReturnedNotOwned() {
1289 return RefVal(ReturnedNotOwned);
1290 }
1291
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001292 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001293
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001294 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001295 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001296 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001297
Ted Kremenek272aa852008-06-25 21:21:56 +00001298 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001299 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001300 }
1301
1302 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001303 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001304 }
1305
1306 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001307 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001308 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001309
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001310 void Profile(llvm::FoldingSetNodeID& ID) const {
1311 ID.AddInteger((unsigned) kind);
1312 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001313 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001314 }
1315
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001316 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001317};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001318
1319void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001320 if (!T.isNull())
1321 Out << "Tracked Type:" << T.getAsString() << '\n';
1322
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001323 switch (getKind()) {
1324 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001325 case Owned: {
1326 Out << "Owned";
1327 unsigned cnt = getCount();
1328 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001329 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001330 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001331
Ted Kremenekc4f81022008-04-10 23:09:18 +00001332 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001333 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001334 unsigned cnt = getCount();
1335 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001336 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001337 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001338
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001339 case ReturnedOwned: {
1340 Out << "ReturnedOwned";
1341 unsigned cnt = getCount();
1342 if (cnt) Out << " (+ " << cnt << ")";
1343 break;
1344 }
1345
1346 case ReturnedNotOwned: {
1347 Out << "ReturnedNotOwned";
1348 unsigned cnt = getCount();
1349 if (cnt) Out << " (+ " << cnt << ")";
1350 break;
1351 }
1352
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001353 case Released:
1354 Out << "Released";
1355 break;
1356
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001357 case ErrorLeak:
1358 Out << "Leaked";
1359 break;
1360
Ted Kremenek311f3d42008-10-22 23:56:21 +00001361 case ErrorLeakReturned:
1362 Out << "Leaked (Bad naming)";
1363 break;
1364
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001365 case ErrorUseAfterRelease:
1366 Out << "Use-After-Release [ERROR]";
1367 break;
1368
1369 case ErrorReleaseNotOwned:
1370 Out << "Release of Not-Owned [ERROR]";
1371 break;
1372 }
1373}
Ted Kremenek0d721572008-03-11 17:48:22 +00001374
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001375} // end anonymous namespace
1376
1377//===----------------------------------------------------------------------===//
1378// RefBindings - State used to track object reference counts.
1379//===----------------------------------------------------------------------===//
1380
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001381typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001382static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001383static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001384
1385namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001386 template<>
1387 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1388 static inline void* GDMIndex() { return &RefBIndex; }
1389 };
1390}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001391
1392//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001393// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001394//===----------------------------------------------------------------------===//
1395
Ted Kremenekb6578942009-02-24 19:15:11 +00001396typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1397typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1398typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001399
Ted Kremenekb6578942009-02-24 19:15:11 +00001400static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001401static int AutoRBIndex = 0;
1402
Ted Kremenekb6578942009-02-24 19:15:11 +00001403namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001404namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001405
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001406namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001407template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001408 : public GRStatePartialTrait<ARStack> {
1409 static inline void* GDMIndex() { return &AutoRBIndex; }
1410};
1411
1412template<> struct GRStateTrait<AutoreleasePoolContents>
1413 : public GRStatePartialTrait<ARPoolContents> {
1414 static inline void* GDMIndex() { return &AutoRCIndex; }
1415};
1416} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001417
Ted Kremenek7aef4842008-04-16 20:40:59 +00001418//===----------------------------------------------------------------------===//
1419// Transfer functions.
1420//===----------------------------------------------------------------------===//
1421
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001422namespace {
1423
Ted Kremenek7d421f32008-04-09 23:49:11 +00001424class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001425public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001426 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001427 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001428 virtual void Print(std::ostream& Out, const GRState* state,
1429 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001430 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001431
1432private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001433 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1434 SummaryLogTy;
1435
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001436 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001437 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001438 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001439 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001440
Ted Kremenek708af042009-02-05 06:50:21 +00001441 BugType *useAfterRelease, *releaseNotOwned;
1442 BugType *leakWithinFunction, *leakAtReturn;
1443 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001444
Ted Kremenekb6578942009-02-24 19:15:11 +00001445 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1446 RefVal::Kind& hasErr);
1447
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001448 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1449 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001450 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001451 ExplodedNode<GRState>* Pred,
1452 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001453 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001454
Ted Kremenek0106e202008-10-24 20:32:50 +00001455 std::pair<GRStateRef, bool>
1456 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001457 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001458
Ted Kremenekb6578942009-02-24 19:15:11 +00001459public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001460 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001461 : Summaries(Ctx, gcenabled),
Ted Kremenek708af042009-02-05 06:50:21 +00001462 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1463 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001464
Ted Kremenek708af042009-02-05 06:50:21 +00001465 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001466
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001467 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001468
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001469 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1470 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001471 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001472
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001473 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001474 const LangOptions& getLangOptions() const { return LOpts; }
1475
Ted Kremenekc26c4692009-02-18 03:48:14 +00001476 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1477 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1478 return I == SummaryLog.end() ? 0 : I->second;
1479 }
1480
Ted Kremeneka7338b42008-03-11 06:39:11 +00001481 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001482
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001483 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001484 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001485 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001486 Expr* Ex,
1487 Expr* Receiver,
1488 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001489 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001490 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001491
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001492 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001493 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001494 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001495 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001496 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001497
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001498
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001499 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001500 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001501 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001502 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001503 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001504
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001505 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001506 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001507 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001508 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001509 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001510
Ted Kremeneka42be302009-02-14 01:43:44 +00001511 // Stores.
1512 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1513
Ted Kremenekffefc352008-04-11 22:25:11 +00001514 // End-of-path.
1515
1516 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001517 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001518
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001519 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001520 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001521 GRStmtNodeBuilder<GRState>& Builder,
1522 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001523 Stmt* S, const GRState* state,
1524 SymbolReaper& SymReaper);
1525
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001526 // Return statements.
1527
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001528 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001529 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001530 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001531 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001532 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001533
1534 // Assumptions.
1535
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001536 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001537 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001538 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001539};
1540
1541} // end anonymous namespace
1542
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001543
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001544void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1545 const char* nl, const char* sep) {
1546
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001547 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001548
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001549 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001550 Out << sep << nl;
1551
1552 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1553 Out << (*I).first << " : ";
1554 (*I).second.print(Out);
1555 Out << nl;
1556 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001557
1558 // Print the autorelease stack.
1559 ARStack stack = state->get<AutoreleaseStack>();
1560 if (!stack.isEmpty()) {
1561 Out << sep << nl << "AR pool stack:";
1562
1563 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1564 Out << ' ' << (*I);
1565
1566 Out << nl;
1567 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001568}
1569
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001570static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001571 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001572}
1573
Ted Kremenek266d8b62008-05-06 02:26:56 +00001574static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1575 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001576}
1577
Ted Kremenek227c5372008-05-06 02:41:27 +00001578static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1579 return Summ ? Summ->getReceiverEffect() : DoNothing;
1580}
1581
Ted Kremenekf2717b02008-07-18 17:24:20 +00001582static inline bool IsEndPath(RetainSummary* Summ) {
1583 return Summ ? Summ->isEndPath() : false;
1584}
1585
Ted Kremenek1feab292008-04-16 04:28:53 +00001586
Ted Kremenek272aa852008-06-25 21:21:56 +00001587/// GetReturnType - Used to get the return type of a message expression or
1588/// function call with the intention of affixing that type to a tracked symbol.
1589/// While the the return type can be queried directly from RetEx, when
1590/// invoking class methods we augment to the return type to be that of
1591/// a pointer to the class (as opposed it just being id).
1592static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1593
1594 QualType RetTy = RetE->getType();
1595
1596 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001597 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001598 if (!PT)
1599 return RetTy;
1600
1601 // If RetEx is not a message expression just return its type.
1602 // If RetEx is a message expression, return its types if it is something
1603 /// more specific than id.
1604
1605 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1606
Steve Naroff17c03822009-02-12 17:52:19 +00001607 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001608 return RetTy;
1609
1610 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1611
1612 // At this point we know the return type of the message expression is id.
1613 // If we have an ObjCInterceDecl, we know this is a call to a class method
1614 // whose type we can resolve. In such cases, promote the return type to
1615 // Class*.
1616 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1617}
1618
1619
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001620void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001621 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001622 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001623 Expr* Ex,
1624 Expr* Receiver,
1625 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001626 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001627 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001628
Ted Kremeneka7338b42008-03-11 06:39:11 +00001629 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001630 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001631 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001632
1633 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001634 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001635 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001636 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001637 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001638
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001639 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001640 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001641 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001642
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001643 if (Sym.isValid())
Ted Kremenekb6578942009-02-24 19:15:11 +00001644 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1645 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1646 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001647 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001648 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001649 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001650 }
1651 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00001652 }
Ted Kremenekede40b72008-07-09 18:11:16 +00001653
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001654 if (isa<Loc>(V)) {
1655 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001656 if (GetArgE(Summ, idx) == DoNothingByRef)
1657 continue;
1658
1659 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001660
1661 // FIXME: Either this logic should also be replicated in GRSimpleVals
1662 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001663
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001664 // FIXME: We can have collisions on the conjured symbol if the
1665 // expression *I also creates conjured symbols. We probably want
1666 // to identify conjured symbols by an expression pair: the enclosing
1667 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001668 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001669
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001670 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001671
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001672 // Blast through TypedViewRegions to get the original region type.
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001673 while (R) {
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001674 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001675 if (!ATR) break;
1676 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1677 }
1678
Ted Kremenek53b24182009-03-04 22:56:43 +00001679 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001680 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001681 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001682
Ted Kremenek53b24182009-03-04 22:56:43 +00001683 // Remove any existing reference-count binding.
1684 if (Sym.isValid()) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001685
Ted Kremenek53b24182009-03-04 22:56:43 +00001686 if (R->isBoundable(Ctx)) {
1687 // Set the value of the variable to be a conjured symbol.
1688 unsigned Count = Builder.getCurrentBlockCount();
1689 QualType T = R->getRValueType(Ctx);
1690
1691 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
1692 SymbolRef NewSym =
1693 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1694
1695 state = state.BindLoc(Loc::MakeVal(R),
1696 Loc::IsLocType(T)
1697 ? cast<SVal>(loc::SymbolVal(NewSym))
1698 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1699 }
1700 else if (const RecordType *RT = T->getAsStructureType()) {
1701 // Handle structs in a not so awesome way. Here we just
1702 // eagerly bind new symbols to the fields. In reality we
1703 // should have the store manager handle this. The idea is just
1704 // to prototype some basic functionality here. All of this logic
1705 // should one day soon just go away.
1706 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1707
1708 // No record definition. There is nothing we can do.
1709 if (!RD)
1710 continue;
1711
1712 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1713
1714 // Iterate through the fields and construct new symbols.
1715 for (RecordDecl::field_iterator FI=RD->field_begin(),
1716 FE=RD->field_end(); FI!=FE; ++FI) {
1717
1718 // For now just handle scalar fields.
1719 FieldDecl *FD = *FI;
1720 QualType FT = FD->getType();
1721
1722 if (Loc::IsLocType(FT) ||
1723 (FT->isIntegerType() && FT->isScalarType())) {
1724
1725 // Tag the symbol with the field decl so that we generate
1726 // a unique symbol.
1727 SymbolRef NewSym =
1728 Eng.getSymbolManager().getConjuredSymbol(*I, FT, Count, FD);
1729
1730 // Create a region.
1731 // FIXME: How do we handle 'typedefs' in TypeViewRegions?
1732 // e.g.:
1733 // typedef struct *s foo;
1734 //
1735 // ((foo) x)->f vs. x->f
1736 //
1737 // The cast will add a ViewTypeRegion. Probably RegionStore
1738 // needs to reason about typedefs explicitly when binding
1739 // fields and elements.
1740 //
1741 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
1742
1743 state = state.BindLoc(Loc::MakeVal(FR),
1744 Loc::IsLocType(FT)
1745 ? cast<SVal>(loc::SymbolVal(NewSym))
1746 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1747 }
1748 }
1749 }
1750 else {
1751 // Just blast away other values.
1752 state = state.BindLoc(*MR, UnknownVal());
1753 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00001754 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001755 }
1756 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001757 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001758 }
1759 else {
1760 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001761 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001762 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001763 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001764 else if (isa<nonloc::LocAsInteger>(V))
1765 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001766 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001767
Ted Kremenek272aa852008-06-25 21:21:56 +00001768 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001769 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001770 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001771 if (Sym.isValid()) {
Ted Kremenekb6578942009-02-24 19:15:11 +00001772 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1773 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1774 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00001775 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001776 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001777 }
Ted Kremenekb6578942009-02-24 19:15:11 +00001778 }
Ted Kremenek227c5372008-05-06 02:41:27 +00001779 }
1780 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001781
Ted Kremenek272aa852008-06-25 21:21:56 +00001782 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001783 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001784 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001785 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001786 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001787 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001788
Ted Kremenekf2717b02008-07-18 17:24:20 +00001789 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001790 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001791
1792 switch (RE.getKind()) {
1793 default:
1794 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001795
Ted Kremenek8f90e712008-10-17 22:23:12 +00001796 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001797
Ted Kremenek455dd862008-04-11 20:23:24 +00001798 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001799 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1800 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001801
Ted Kremenek8f90e712008-10-17 22:23:12 +00001802 // FIXME: We eventually should handle structs and other compound types
1803 // that are returned by value.
1804
1805 QualType T = Ex->getType();
1806
Ted Kremenek79413a52008-11-13 06:10:40 +00001807 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001808 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001809 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001810
Ted Kremenek802cfc72009-02-20 00:05:35 +00001811 SVal X = Loc::IsLocType(T)
Zhongxing Xu097fc982008-10-17 05:57:07 +00001812 ? cast<SVal>(loc::SymbolVal(Sym))
1813 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001814
Ted Kremenek09102db2008-11-12 19:22:09 +00001815 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001816 }
1817
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001818 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00001819 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001820
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001821 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001822 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001823 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001824 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001825 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00001826 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001827 break;
1828 }
1829
Ted Kremenek227c5372008-05-06 02:41:27 +00001830 case RetEffect::ReceiverAlias: {
1831 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001832 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00001833 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00001834 break;
1835 }
1836
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001837 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001838 case RetEffect::OwnedSymbol: {
1839 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001840 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek68621b92009-01-28 05:56:51 +00001841 QualType RetT = GetReturnType(Ex, Eng.getContext());
1842 state =
1843 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001844 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001845
Ted Kremenek45c52a12009-03-09 22:46:49 +00001846
1847 // FIXME: Add a flag to the checker where allocations are assumed to
1848 // *not fail.
1849#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00001850 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1851 bool isFeasible;
1852 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1853 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1854 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00001855#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001856
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001857 break;
1858 }
1859
1860 case RetEffect::NotOwnedSymbol: {
1861 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001862 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001863 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001864
Ted Kremenek68621b92009-01-28 05:56:51 +00001865 state =
1866 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001867 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001868 break;
1869 }
1870 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001871
Ted Kremenek0dd65012009-02-18 02:00:25 +00001872 // Generate a sink node if we are at the end of a path.
1873 GRExprEngine::NodeTy *NewNode =
1874 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1875 : Builder.MakeNode(Dst, Ex, Pred, state);
1876
1877 // Annotate the edge with summary we used.
1878 // FIXME: This assumes that we always use the same summary when generating
1879 // this node.
1880 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001881}
1882
1883
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001884void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001885 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001886 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001887 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001888 ExplodedNode<GRState>* Pred) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001889
Zhongxing Xu097fc982008-10-17 05:57:07 +00001890 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1891 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001892
1893 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1894 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001895}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001896
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001897void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001898 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001899 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001900 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001901 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00001902 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001903
Ted Kremenek272aa852008-06-25 21:21:56 +00001904 if (Expr* Receiver = ME->getReceiver()) {
1905 // We need the type-information of the tracked receiver object
1906 // Retrieve it from the state.
1907 ObjCInterfaceDecl* ID = 0;
1908
1909 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1910 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001911 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001912 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00001913
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001914 SymbolRef Sym = V.getAsLocSymbol();
1915 if (Sym.isValid()) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001916 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00001917 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001918
1919 if (const PointerType* PT = Ty->getAsPointerType()) {
1920 QualType PointeeTy = PT->getPointeeType();
1921
1922 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1923 ID = IT->getDecl();
1924 }
1925 }
1926 }
1927
1928 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00001929
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001930 // Special-case: are we sending a mesage to "self"?
1931 // This is a hack. When we have full-IP this should be removed.
1932 if (!Summ) {
1933 ObjCMethodDecl* MD =
1934 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1935
1936 if (MD) {
1937 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001938 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001939 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00001940 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1941 // Create a summmary where all of the arguments "StopTracking".
1942 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1943 DoNothing,
1944 StopTracking);
1945 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001946 }
1947 }
1948 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001949 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001950 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001951 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1952 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001953
Ted Kremenek926abf22008-05-06 04:20:12 +00001954 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1955 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001956}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001957
1958namespace {
1959class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1960 GRStateRef state;
1961public:
1962 StopTrackingCallback(GRStateRef st) : state(st) {}
1963 GRStateRef getState() { return state; }
1964
1965 bool VisitSymbol(SymbolRef sym) {
1966 state = state.remove<RefBindings>(sym);
1967 return true;
1968 }
Ted Kremenek926abf22008-05-06 04:20:12 +00001969
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001970 const GRState* getState() const { return state.getState(); }
1971};
1972} // end anonymous namespace
1973
1974
Ted Kremeneka42be302009-02-14 01:43:44 +00001975void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00001976 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00001977 bool escapes = false;
1978
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001979 // A value escapes in three possible cases (this may change):
1980 //
1981 // (1) we are binding to something that is not a memory region.
1982 // (2) we are binding to a memregion that does not have stack storage
1983 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00001984 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00001985 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001986
Ted Kremeneka42be302009-02-14 01:43:44 +00001987 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00001988 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00001989 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00001990 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1991 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001992
1993 if (!escapes) {
1994 // To test (3), generate a new state with the binding removed. If it is
1995 // the same state, then it escapes (since the store cannot represent
1996 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00001997 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001998 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001999 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002000
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002001 // If our store can represent the binding and we aren't storing to something
2002 // that doesn't have local storage then just return and have the simulation
2003 // state continue as is.
2004 if (!escapes)
2005 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002006
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002007 // Otherwise, find all symbols referenced by 'val' that we are tracking
2008 // and stop tracking them.
2009 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002010}
2011
Ted Kremenek0106e202008-10-24 20:32:50 +00002012std::pair<GRStateRef,bool>
2013CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2014 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002015 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002016 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002017
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002018 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00002019 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00002020 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002021
Ted Kremenek311f3d42008-10-22 23:56:21 +00002022 if (V.isReturnedOwned() && V.getCount() == 0)
2023 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00002024 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00002025 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00002026 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00002027 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2028 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00002029 }
2030 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002031
Ted Kremenek311f3d42008-10-22 23:56:21 +00002032 // All other cases.
2033
2034 hasLeak = V.isOwned() ||
2035 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002036
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002037 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002038 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002039
Ted Kremenek0106e202008-10-24 20:32:50 +00002040 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2041 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002042}
2043
Ted Kremenek541db372008-04-24 23:57:27 +00002044
Ted Kremenekffefc352008-04-11 22:25:11 +00002045
Ted Kremenek541db372008-04-24 23:57:27 +00002046// Dead symbols.
2047
Ted Kremenek708af042009-02-05 06:50:21 +00002048
Ted Kremenek541db372008-04-24 23:57:27 +00002049
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002050 // Return statements.
2051
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002052void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002053 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002054 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002055 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002056 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002057
2058 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002059 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002060 return;
2061
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002062 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002063 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002064
2065 if (!Sym.isValid())
2066 return;
2067
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002068 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002069 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002070
2071 if (!T)
2072 return;
2073
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002074 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002075 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002076
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002077 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002078 case RefVal::Owned: {
2079 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002080 assert (cnt > 0);
2081 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002082 break;
2083 }
2084
2085 case RefVal::NotOwned: {
2086 unsigned cnt = X.getCount();
2087 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2088 : RefVal::makeReturnedNotOwned();
2089 break;
2090 }
2091
2092 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002093 return;
2094 }
2095
2096 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002097 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002098 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002099}
2100
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002101// Assumptions.
2102
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002103const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2104 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002105 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002106 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002107
2108 // FIXME: We may add to the interface of EvalAssume the list of symbols
2109 // whose assumptions have changed. For now we just iterate through the
2110 // bindings and check if any of the tracked symbols are NULL. This isn't
2111 // too bad since the number of symbols we will track in practice are
2112 // probably small and EvalAssume is only called at branches and a few
2113 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002114 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002115
2116 if (B.isEmpty())
2117 return St;
2118
2119 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002120
2121 GRStateRef state(St, VMgr);
2122 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002123
2124 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002125 // Check if the symbol is null (or equal to any constant).
2126 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002127 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002128 changed = true;
2129 B = RefBFactory.Remove(B, I.getKey());
2130 }
2131 }
2132
Ted Kremenek91781202008-08-17 03:20:02 +00002133 if (changed)
2134 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002135
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002136 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002137}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002138
Ted Kremenekb6578942009-02-24 19:15:11 +00002139GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2140 RefVal V, ArgEffect E,
2141 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002142
2143 // In GC mode [... release] and [... retain] do nothing.
2144 switch (E) {
2145 default: break;
2146 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2147 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002148 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00002149 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2150 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002151 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002152
Ted Kremenek0d721572008-03-11 17:48:22 +00002153 switch (E) {
2154 default:
2155 assert (false && "Unhandled CFRef transition.");
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002156
Ted Kremenekb7826ab2009-02-25 23:11:49 +00002157 case NewAutoreleasePool:
2158 assert(!isGCEnabled());
2159 return state.add<AutoreleaseStack>(sym);
2160
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002161 case MayEscape:
2162 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002163 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002164 break;
2165 }
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002166 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00002167
Ted Kremenekede40b72008-07-09 18:11:16 +00002168 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002169 case DoNothing:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002170 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002171 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002172 hasErr = V.getKind();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002173 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002174 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002175 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002176
Ted Kremenek9b112d22009-01-28 21:44:40 +00002177 case Autorelease:
Ted Kremenekb6578942009-02-24 19:15:11 +00002178 if (isGCEnabled()) return state;
Ted Kremenek9b112d22009-01-28 21:44:40 +00002179 // Fall-through.
Ted Kremenek227c5372008-05-06 02:41:27 +00002180 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00002181 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002182
Ted Kremenek0d721572008-03-11 17:48:22 +00002183 case IncRef:
2184 switch (V.getKind()) {
2185 default:
2186 assert(false);
2187
2188 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002189 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002190 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002191 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002192 case RefVal::Released:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002193 if (isGCEnabled())
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002194 V = (V ^ RefVal::Owned) + 1;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002195 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002196 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002197 hasErr = V.getKind();
2198 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002199 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002200 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002201 break;
2202
Ted Kremenek272aa852008-06-25 21:21:56 +00002203 case SelfOwn:
2204 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002205 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002206 case DecRef:
2207 switch (V.getKind()) {
2208 default:
2209 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002210
Ted Kremenek272aa852008-06-25 21:21:56 +00002211 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002212 assert(V.getCount() > 0);
2213 if (V.getCount() == 1) V = V ^ RefVal::Released;
2214 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002215 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002216
Ted Kremenek272aa852008-06-25 21:21:56 +00002217 case RefVal::NotOwned:
2218 if (V.getCount() > 0)
2219 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002220 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002221 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002222 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002223 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002224 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002225
2226 case RefVal::Released:
Ted Kremenek272aa852008-06-25 21:21:56 +00002227 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002228 hasErr = V.getKind();
Ted Kremenek0d721572008-03-11 17:48:22 +00002229 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002230 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002231 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002232 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002233 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002234}
2235
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002236//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002237// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002238//===----------------------------------------------------------------------===//
2239
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002240namespace {
2241
2242 //===-------------===//
2243 // Bug Descriptions. //
2244 //===-------------===//
2245
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002246 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002247 protected:
2248 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002249
2250 CFRefBug(CFRefCount* tf, const char* name)
2251 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002252 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002253
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002254 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002255 const CFRefCount& getTF() const { return TF; }
2256
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002257 // FIXME: Eventually remove.
2258 virtual const char* getDescription() const = 0;
2259
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002260 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002261 };
2262
2263 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2264 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002265 UseAfterRelease(CFRefCount* tf)
2266 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002267
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002268 const char* getDescription() const {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002269 return "Reference-counted object is used after it is released";
Ted Kremenek708af042009-02-05 06:50:21 +00002270 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002271 };
2272
2273 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2274 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002275 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2276
2277 const char* getDescription() const {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002278 return "Incorrect decrement of the reference count of a "
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002279 "Core Foundation object ("
2280 "the object is not owned at this point by the caller)";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002281 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002282 };
2283
2284 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002285 const bool isReturn;
2286 protected:
2287 Leak(CFRefCount* tf, const char* name, bool isRet)
2288 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002289 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002290
Ted Kremenek44274e62009-02-07 22:38:00 +00002291 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002292
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002293 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002294 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002295
2296 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2297 public:
2298 LeakAtReturn(CFRefCount* tf, const char* name)
2299 : Leak(tf, name, true) {}
2300 };
2301
2302 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2303 public:
2304 LeakWithinFunction(CFRefCount* tf, const char* name)
2305 : Leak(tf, name, false) {}
2306 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002307
2308 //===---------===//
2309 // Bug Reports. //
2310 //===---------===//
2311
2312 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002313 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002314 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002315 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002316 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002317 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2318 ExplodedNode<GRState> *n, SymbolRef sym)
2319 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002320
2321 virtual ~CFRefReport() {}
2322
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002323 CFRefBug& getBugType() {
2324 return (CFRefBug&) RangedBugReport::getBugType();
2325 }
2326 const CFRefBug& getBugType() const {
2327 return (const CFRefBug&) RangedBugReport::getBugType();
2328 }
2329
2330 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2331 const SourceRange*& end) {
2332
Ted Kremenek198cae02008-05-02 20:53:50 +00002333 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002334 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002335 else
2336 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002337 }
2338
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002339 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002340
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002341 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2342 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002343
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002344 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002345
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002346 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2347 const ExplodedNode<GRState>* PrevN,
2348 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002349 BugReporter& BR,
2350 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002351 };
2352
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002353 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002354 SourceLocation AllocSite;
2355 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002356 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002357 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2358 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002359 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002360
2361 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2362 const ExplodedNode<GRState>* N);
2363
Ted Kremenek86617f42009-02-07 22:19:59 +00002364 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002365 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002366} // end anonymous namespace
2367
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002368void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002369 useAfterRelease = new UseAfterRelease(this);
2370 BR.Register(useAfterRelease);
2371
2372 releaseNotOwned = new BadRelease(this);
2373 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002374
2375 // First register "return" leaks.
2376 const char* name = 0;
2377
2378 if (isGCEnabled())
Ted Kremenek50ee2142009-03-11 23:43:16 +00002379 name = "leak of returned object (GC)";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002380 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2381 name = "[naming convention] leak of returned object (hybrid MM, "
2382 "non-GC)";
2383 else {
2384 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenek50ee2142009-03-11 23:43:16 +00002385 name = "leak of returned object";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002386 }
2387
Ted Kremenek708af042009-02-05 06:50:21 +00002388 leakAtReturn = new LeakAtReturn(this, name);
2389 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002390
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002391 // Second, register leaks within a function/method.
2392 if (isGCEnabled())
2393 name = "leak (GC)";
2394 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2395 name = "leak (hybrid MM, non-GC)";
2396 else {
2397 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2398 name = "leak";
2399 }
2400
Ted Kremenek708af042009-02-05 06:50:21 +00002401 leakWithinFunction = new LeakWithinFunction(this, name);
2402 BR.Register(leakWithinFunction);
2403
2404 // Save the reference to the BugReporter.
2405 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002406}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002407
2408static const char* Msgs[] = {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002409 // GC only
2410 "Code is compiled to only use garbage collection",
2411 // No GC.
Ted Kremeneka9203882009-03-05 00:12:45 +00002412 "Code is compiled to use reference counts",
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002413 // Hybrid, with GC.
2414 "Code is compiled to use either garbage collection (GC) or reference counts"
2415 " (non-GC). The bug occurs with GC enabled",
2416 // Hybrid, without GC
2417 "Code is compiled to use either garbage collection (GC) or reference counts"
2418 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002419};
2420
2421std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2422 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2423
2424 switch (TF.getLangOptions().getGCMode()) {
2425 default:
2426 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002427
2428 case LangOptions::GCOnly:
2429 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002430 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2431
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002432 case LangOptions::NonGC:
2433 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002434 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2435
2436 case LangOptions::HybridGC:
2437 if (TF.isGCEnabled())
2438 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2439 else
2440 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2441 }
2442}
2443
Ted Kremenek2126bef2009-02-18 21:57:45 +00002444static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2445 ArgEffect X) {
2446 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2447 I!=E; ++I)
2448 if (*I == X) return true;
2449
2450 return false;
2451}
2452
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002453PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2454 const ExplodedNode<GRState>* PrevN,
2455 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002456 BugReporter& BR,
2457 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002458
Ted Kremenek71745d92009-01-28 05:29:13 +00002459 // Check if the type state has changed.
2460 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2461 GRStateRef PrevSt(PrevN->getState(), StMgr);
2462 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002463
Ted Kremenek71745d92009-01-28 05:29:13 +00002464 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2465 if (!CurrT) return NULL;
2466
2467 const RefVal& CurrV = *CurrT;
2468 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002469
Ted Kremenek2126bef2009-02-18 21:57:45 +00002470 // Create a string buffer to constain all the useful things we want
2471 // to tell the user.
2472 std::string sbuf;
2473 llvm::raw_string_ostream os(sbuf);
2474
Ted Kremenekc26c4692009-02-18 03:48:14 +00002475 // This is the allocation site since the previous node had no bindings
2476 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002477 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002478 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2479
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002480 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2481 // Get the name of the callee (if it is available).
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002482 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002483 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2484 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2485 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002486 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002487 }
2488 else {
2489 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002490 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002491 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002492
Ted Kremenek18878b12009-01-28 06:06:36 +00002493 if (CurrV.getObjKind() == RetEffect::CF) {
2494 os << " returns a Core Foundation object with a ";
2495 }
2496 else {
2497 assert (CurrV.getObjKind() == RetEffect::ObjC);
2498 os << " returns an Objective-C object with a ";
2499 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002500
Ted Kremenekabe30922009-01-28 06:25:48 +00002501 if (CurrV.isOwned()) {
2502 os << "+1 retain count (owning reference).";
2503
2504 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2505 assert(CurrV.getObjKind() == RetEffect::CF);
2506 os << " "
2507 "Core Foundation objects are not automatically garbage collected.";
2508 }
2509 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002510 else {
2511 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002512 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002513 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002514
Ted Kremeneka8503952008-04-18 04:55:01 +00002515 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek23563642009-03-06 23:58:11 +00002516 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002517
2518 if (Expr* Exp = dyn_cast<Expr>(S))
2519 P->addRange(Exp->getSourceRange());
2520
2521 return P;
2522 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002523
Ted Kremenek2126bef2009-02-18 21:57:45 +00002524 // Gather up the effects that were performed on the object at this
2525 // program point
2526 llvm::SmallVector<ArgEffect, 2> AEffects;
2527
Ted Kremenekc26c4692009-02-18 03:48:14 +00002528 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2529 // We only have summaries attached to nodes after evaluating CallExpr and
2530 // ObjCMessageExprs.
2531 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2532
Ted Kremenekc26c4692009-02-18 03:48:14 +00002533 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2534 // Iterate through the parameter expressions and see if the symbol
2535 // was ever passed as an argument.
2536 unsigned i = 0;
2537
2538 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2539 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002540
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002541 // Retrieve the value of the argument. Is it the symbol
2542 // we are interested in?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002543 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002544 continue;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002545
Ted Kremenekc26c4692009-02-18 03:48:14 +00002546 // We have an argument. Get the effect!
2547 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002548 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002549 }
2550 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002551 if (Expr *receiver = ME->getReceiver())
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002552 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002553 // The symbol we are tracking is the receiver.
2554 AEffects.push_back(Summ->getReceiverEffect());
2555 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002556 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002557 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002558
Ted Kremenek2126bef2009-02-18 21:57:45 +00002559 do {
2560 // Get the previous type state.
2561 RefVal PrevV = *PrevT;
2562
2563 // Specially handle CFMakeCollectable and friends.
2564 if (contains(AEffects, MakeCollectable)) {
2565 // Get the name of the function.
2566 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2567 loc::FuncVal FV =
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002568 cast<loc::FuncVal>(CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee()));
Ted Kremenek2126bef2009-02-18 21:57:45 +00002569 const std::string& FName = FV.getDecl()->getNameAsString();
2570
2571 if (TF.isGCEnabled()) {
2572 // Determine if the object's reference count was pushed to zero.
2573 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2574
2575 os << "In GC mode a call to '" << FName
2576 << "' decrements an object's retain count and registers the "
2577 "object with the garbage collector. ";
2578
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002579 if (CurrV.getKind() == RefVal::Released) {
2580 assert(CurrV.getCount() == 0);
2581 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002582 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002583 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002584 else
2585 os << "An object must have a 0 retain count to be garbage collected. "
2586 "After this call its retain count is +" << CurrV.getCount()
2587 << '.';
2588 }
2589 else
2590 os << "When GC is not enabled a call to '" << FName
2591 << "' has no effect on its argument.";
2592
2593 // Nothing more to say.
2594 break;
2595 }
2596
2597 // Determine if the typestate has changed.
2598 if (!(PrevV == CurrV))
2599 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002600 case RefVal::Owned:
2601 case RefVal::NotOwned:
2602
2603 if (PrevV.getCount() == CurrV.getCount())
2604 return 0;
2605
2606 if (PrevV.getCount() > CurrV.getCount())
2607 os << "Reference count decremented.";
2608 else
2609 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002610
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002611 if (unsigned Count = CurrV.getCount())
2612 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002613
2614 if (PrevV.getKind() == RefVal::Released) {
2615 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2616 os << " The object is not eligible for garbage collection until the "
2617 "retain count reaches 0 again.";
2618 }
2619
Ted Kremenekc26c4692009-02-18 03:48:14 +00002620 break;
2621
2622 case RefVal::Released:
2623 os << "Object released.";
2624 break;
2625
2626 case RefVal::ReturnedOwned:
2627 os << "Object returned to caller as an owning reference (single retain "
2628 "count transferred to caller).";
2629 break;
2630
2631 case RefVal::ReturnedNotOwned:
2632 os << "Object returned to caller with a +0 (non-owning) retain count.";
2633 break;
2634
2635 default:
2636 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002637 }
2638
2639 // Emit any remaining diagnostics for the argument effects (if any).
2640 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2641 E=AEffects.end(); I != E; ++I) {
2642
2643 // A bunch of things have alternate behavior under GC.
2644 if (TF.isGCEnabled())
2645 switch (*I) {
2646 default: break;
2647 case Autorelease:
2648 os << "In GC mode an 'autorelease' has no effect.";
2649 continue;
2650 case IncRefMsg:
2651 os << "In GC mode the 'retain' message has no effect.";
2652 continue;
2653 case DecRefMsg:
2654 os << "In GC mode the 'release' message has no effect.";
2655 continue;
2656 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002657 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002658 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002659
2660 if (os.str().empty())
2661 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002662
2663 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2664 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek23563642009-03-06 23:58:11 +00002665 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002666
2667 // Add the range by scanning the children of the statement for any bindings
2668 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002669 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002670 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002671 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002672 P->addRange(Exp->getSourceRange());
2673 break;
2674 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002675
2676 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002677}
2678
Ted Kremenekb15eba42008-10-04 05:50:14 +00002679namespace {
2680class VISIBILITY_HIDDEN FindUniqueBinding :
2681 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002682 SymbolRef Sym;
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002683 const MemRegion* Binding;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002684 bool First;
2685
2686 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002687 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002688
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002689 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2690 SVal val) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002691 SymbolRef SymV = val.getAsSymbol();
2692
2693 if (!SymV.isValid() || SymV != Sym)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002694 return true;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002695
Ted Kremenekb15eba42008-10-04 05:50:14 +00002696 if (Binding) {
2697 First = false;
2698 return false;
2699 }
2700 else
2701 Binding = R;
2702
2703 return true;
2704 }
2705
2706 operator bool() { return First && Binding; }
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002707 const MemRegion* getRegion() { return Binding; }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002708};
2709}
2710
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002711static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00002712GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002713 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00002714
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002715 // Find both first node that referred to the tracked symbol and the
2716 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002717 const ExplodedNode<GRState>* Last = N;
2718 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002719
2720 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002721 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002722 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002723
Ted Kremenek6064a362008-07-07 16:21:19 +00002724 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002725 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002726
Ted Kremenek86617f42009-02-07 22:19:59 +00002727 FindUniqueBinding FB(Sym);
2728 StateMgr.iterBindings(St, FB);
2729 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002730
Ted Kremenekd7e26782008-05-16 18:33:44 +00002731 Last = N;
2732 N = N->pred_empty() ? NULL : *(N->pred_begin());
2733 }
2734
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002735 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002736}
Ted Kremenek4c479322008-05-06 23:07:13 +00002737
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002738PathDiagnosticPiece*
2739CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002740
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002741 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek86953652008-05-22 23:45:19 +00002742 // Tell the BugReporter to report cases when the tracked symbol is
2743 // assigned to different variables, etc.
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002744 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002745 return RangedBugReport::getEndPath(BR, EndN);
2746}
2747
2748PathDiagnosticPiece*
2749CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2750
2751 GRBugReporter& BR = cast<GRBugReporter>(br);
2752 // Tell the BugReporter to report cases when the tracked symbol is
2753 // assigned to different variables, etc.
2754 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2755
2756 // We are reporting a leak. Walk up the graph to get to the first node where
2757 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00002758 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002759 const ExplodedNode<GRState>* AllocNode = 0;
2760 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002761
2762 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00002763 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002764
Ted Kremenekd7e26782008-05-16 18:33:44 +00002765 // Get the allocate site.
2766 assert (AllocNode);
2767 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002768
Ted Kremenekea794e92008-05-05 18:50:19 +00002769 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00002770 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002771
Ted Kremeneke0336742009-02-18 23:28:26 +00002772 // Get the leak site. We want to find the last place where the symbol
2773 // was used in an expression.
2774 const ExplodedNode<GRState>* LeakN = EndN;
2775 Stmt *S = 0;
Ted Kremenekea794e92008-05-05 18:50:19 +00002776
Ted Kremeneke0336742009-02-18 23:28:26 +00002777 while (LeakN) {
Ted Kremenek914fc7c2009-02-24 23:30:57 +00002778 bool atBranch = false;
Ted Kremeneke0336742009-02-18 23:28:26 +00002779 ProgramPoint P = LeakN->getLocation();
Ted Kremeneke0336742009-02-18 23:28:26 +00002780
2781 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2782 S = PS->getStmt();
Ted Kremenek914fc7c2009-02-24 23:30:57 +00002783 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2784 // FIXME: What we really want is to set LeakN to be the node
2785 // for the BlockEntrance for the branch we took and have BugReporter
2786 // do the right thing.
Ted Kremeneke0336742009-02-18 23:28:26 +00002787 S = BE->getSrc()->getTerminator();
Ted Kremeneka1e39992009-02-24 23:34:17 +00002788 atBranch = (S != 0);
Ted Kremenek914fc7c2009-02-24 23:30:57 +00002789 }
Ted Kremeneke0336742009-02-18 23:28:26 +00002790
2791 if (S) {
2792 // Scan 'S' for uses of Sym.
2793 GRStateRef state(LeakN->getState(), BR.getStateManager());
2794 bool foundSymbol = false;
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002795
2796 // First check if 'S' itself binds to the symbol.
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002797 if (Expr *Ex = dyn_cast<Expr>(S))
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002798 if (state.GetSValAsScalarOrLoc(Ex).getAsLocSymbol() == Sym)
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002799 foundSymbol = true;
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002800
2801 if (!foundSymbol)
2802 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2803 I!=E; ++I)
2804 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002805 SVal X = state.GetSValAsScalarOrLoc(Ex);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002806 if (X.getAsLocSymbol() == Sym) {
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002807 foundSymbol = true;
2808 break;
2809 }
Ted Kremeneke0336742009-02-18 23:28:26 +00002810 }
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002811
Ted Kremeneke0336742009-02-18 23:28:26 +00002812 if (foundSymbol)
2813 break;
2814 }
2815
Ted Kremenek914fc7c2009-02-24 23:30:57 +00002816 // Don't traverse any higher than the branch.
2817 if (atBranch)
2818 break;
2819
Ted Kremeneke0336742009-02-18 23:28:26 +00002820 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2821 }
2822
2823 assert(LeakN && S && "No leak site found.");
Ted Kremenekea794e92008-05-05 18:50:19 +00002824
Ted Kremenekea794e92008-05-05 18:50:19 +00002825 // Generate the diagnostic.
Ted Kremenek323207b2009-02-18 22:59:04 +00002826 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenek59f9fe12009-02-07 21:59:45 +00002827 std::string sbuf;
2828 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00002829
Ted Kremenekea794e92008-05-05 18:50:19 +00002830 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002831
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002832 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002833 os << " and stored into '" << FirstBinding->getString() << '\'';
2834
Ted Kremenek311f3d42008-10-22 23:56:21 +00002835 // Get the retain count.
2836 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2837
2838 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00002839 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2840 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2841 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00002842 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2843 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00002844 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00002845 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00002846 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002847 " in the Memory Management Guide for Cocoa (object leaked).";
2848 }
2849 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00002850 os << " is no longer referenced after this point and has a retain count of"
2851 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002852 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002853
Ted Kremenek23563642009-03-06 23:58:11 +00002854 return new PathDiagnosticEventPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002855}
2856
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002857
Ted Kremenekc26c4692009-02-18 03:48:14 +00002858CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2859 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00002860 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002861 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00002862{
2863
Ted Kremenekd7e26782008-05-16 18:33:44 +00002864 // Most bug reports are cached at the location where they occured.
2865 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00002866 // allocated, and only report a single path. To do this, we need to find
2867 // the allocation site of a piece of tracked memory, which we do via a
2868 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2869 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2870 // that all ancestor nodes that represent the allocation site have the
2871 // same SourceLocation.
2872 const ExplodedNode<GRState>* AllocNode = 0;
2873
2874 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00002875 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00002876
Ted Kremenek86617f42009-02-07 22:19:59 +00002877 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00002878 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00002879 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00002880
2881 // Fill in the description of the bug.
2882 Description.clear();
2883 llvm::raw_string_ostream os(Description);
2884 SourceManager& SMgr = Eng.getContext().getSourceManager();
2885 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00002886 os << "Potential leak of object allocated on line " << AllocLine;
2887
2888 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2889 if (AllocBinding)
2890 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00002891}
2892
Ted Kremeneka7338b42008-03-11 06:39:11 +00002893//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00002894// Handle dead symbols and end-of-path.
2895//===----------------------------------------------------------------------===//
2896
2897void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2898 GREndPathNodeBuilder<GRState>& Builder) {
2899
2900 const GRState* St = Builder.getState();
2901 RefBindings B = St->get<RefBindings>();
2902
2903 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2904 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2905
2906 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2907 bool hasLeak = false;
2908
2909 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002910 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2911 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00002912
2913 St = X.first;
2914 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2915 }
2916
2917 if (Leaked.empty())
2918 return;
2919
2920 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2921
2922 if (!N)
2923 return;
2924
2925 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2926 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2927
2928 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2929 : leakWithinFunction);
2930 assert(BT && "BugType not initialized.");
Ted Kremenekc26c4692009-02-18 03:48:14 +00002931 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00002932 BR->EmitReport(report);
2933 }
2934}
2935
2936void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2937 GRExprEngine& Eng,
2938 GRStmtNodeBuilder<GRState>& Builder,
2939 ExplodedNode<GRState>* Pred,
2940 Stmt* S,
2941 const GRState* St,
2942 SymbolReaper& SymReaper) {
2943
Ted Kremenek876d8df2009-02-19 23:47:02 +00002944 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00002945 RefBindings B = St->get<RefBindings>();
2946 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2947
2948 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2949 E = SymReaper.dead_end(); I != E; ++I) {
2950
2951 const RefVal* T = B.lookup(*I);
2952 if (!T) continue;
2953
2954 bool hasLeak = false;
2955
2956 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00002957 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00002958
2959 St = X.first;
2960
2961 if (hasLeak)
2962 Leaked.push_back(std::make_pair(*I,X.second));
2963 }
2964
Ted Kremenek876d8df2009-02-19 23:47:02 +00002965 if (!Leaked.empty()) {
2966 // Create a new intermediate node representing the leak point. We
2967 // use a special program point that represents this checker-specific
2968 // transition. We use the address of RefBIndex as a unique tag for this
2969 // checker. We will create another node (if we don't cache out) that
2970 // removes the retain-count bindings from the state.
2971 // NOTE: We use 'generateNode' so that it does interplay with the
2972 // auto-transition logic.
2973 ExplodedNode<GRState>* N =
2974 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00002975
Ted Kremenek876d8df2009-02-19 23:47:02 +00002976 if (!N)
2977 return;
2978
2979 // Generate the bug reports.
2980 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
2981 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2982
2983 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2984 : leakWithinFunction);
2985 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00002986 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
2987 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00002988 BR->EmitReport(report);
2989 }
Ted Kremenek708af042009-02-05 06:50:21 +00002990
Ted Kremenek876d8df2009-02-19 23:47:02 +00002991 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00002992 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00002993
2994 // Now generate a new node that nukes the old bindings.
2995 GRStateRef state(St, Eng.getStateManager());
2996 RefBindings::Factory& F = state.get_context<RefBindings>();
2997
2998 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2999 E = SymReaper.dead_end(); I!=E; ++I)
3000 B = F.Remove(B, *I);
3001
3002 state = state.set<RefBindings>(B);
3003 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003004}
3005
3006void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3007 GRStmtNodeBuilder<GRState>& Builder,
3008 Expr* NodeExpr, Expr* ErrorExpr,
3009 ExplodedNode<GRState>* Pred,
3010 const GRState* St,
3011 RefVal::Kind hasErr, SymbolRef Sym) {
3012 Builder.BuildSinks = true;
3013 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3014
3015 if (!N) return;
3016
3017 CFRefBug *BT = 0;
3018
3019 if (hasErr == RefVal::ErrorUseAfterRelease)
3020 BT = static_cast<CFRefBug*>(useAfterRelease);
3021 else {
3022 assert(hasErr == RefVal::ErrorReleaseNotOwned);
3023 BT = static_cast<CFRefBug*>(releaseNotOwned);
3024 }
3025
Ted Kremenekc26c4692009-02-18 03:48:14 +00003026 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003027 report->addRange(ErrorExpr->getSourceRange());
3028 BR->EmitReport(report);
3029}
3030
3031//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003032// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003033//===----------------------------------------------------------------------===//
3034
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003035GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3036 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003037 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003038}