blob: 97efd28c06b75c099161955851a913117ddad06b [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 Kremenek6537a642009-03-17 19:42:23 +0000223enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
224 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
225 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000226
227/// ArgEffects summarizes the effects of a function/method call on all of
228/// its arguments.
229typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000230}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000231
Ted Kremeneka7338b42008-03-11 06:39:11 +0000232namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000233template <> struct FoldingSetTrait<ArgEffects> {
234 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
235 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
236 ID.AddInteger(I->first);
237 ID.AddInteger((unsigned) I->second);
238 }
239 }
240};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000241} // end llvm namespace
242
243namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000244
245/// RetEffect is used to summarize a function/method call's behavior with
246/// respect to its return value.
247class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000248public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000249 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000250 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000251
252 enum ObjKind { CF, ObjC, AnyObj };
253
Ted Kremeneka7338b42008-03-11 06:39:11 +0000254private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000255 Kind K;
256 ObjKind O;
257 unsigned index;
258
259 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
260 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000261
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000263 Kind getKind() const { return K; }
264
265 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000266
267 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000268 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000269 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000271
Ted Kremenek272aa852008-06-25 21:21:56 +0000272 static RetEffect MakeAlias(unsigned Idx) {
273 return RetEffect(Alias, Idx);
274 }
275 static RetEffect MakeReceiverAlias() {
276 return RetEffect(ReceiverAlias);
277 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000278 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
279 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000280 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000281 static RetEffect MakeNotOwned(ObjKind o) {
282 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000283 }
284 static RetEffect MakeGCNotOwned() {
285 return RetEffect(GCNotOwnedSymbol, ObjC);
286 }
287
Ted Kremenek272aa852008-06-25 21:21:56 +0000288 static RetEffect MakeNoRet() {
289 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000290 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000291
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000293 ID.AddInteger((unsigned)K);
294 ID.AddInteger((unsigned)O);
295 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000296 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000297};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000298
Ted Kremenek272aa852008-06-25 21:21:56 +0000299
300class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000301 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
302 /// specifies the argument (starting from 0). This can be sparsely
303 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000304 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000305
306 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
307 /// do not have an entry in Args.
308 ArgEffect DefaultArgEffect;
309
Ted Kremenek272aa852008-06-25 21:21:56 +0000310 /// Receiver - If this summary applies to an Objective-C message expression,
311 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000312 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000313
314 /// Ret - The effect on the return value. Used to indicate if the
315 /// function/method call returns a new tracked symbol, returns an
316 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000317 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000318
Ted Kremenekf2717b02008-07-18 17:24:20 +0000319 /// EndPath - Indicates that execution of this method/function should
320 /// terminate the simulation of a path.
321 bool EndPath;
322
Ted Kremeneka7338b42008-03-11 06:39:11 +0000323public:
324
Ted Kremenekbcaff792008-05-06 15:44:25 +0000325 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000326 ArgEffect ReceiverEff, bool endpath = false)
327 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
328 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000329
Ted Kremenek272aa852008-06-25 21:21:56 +0000330 /// getArg - Return the argument effect on the argument specified by
331 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000332 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000333
Ted Kremenekae855d42008-04-24 17:22:33 +0000334 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000335 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000336
337 // If Args is present, it is likely to contain only 1 element.
338 // Just do a linear search. Do it from the back because functions with
339 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000340 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000341 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
342 I!=E; ++I) {
343
344 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000345 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000346
347 if (idx == I->first)
348 return I->second;
349 }
350
Ted Kremenekbcaff792008-05-06 15:44:25 +0000351 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000352 }
353
Ted Kremenek272aa852008-06-25 21:21:56 +0000354 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000355 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000356 return Ret;
357 }
358
Ted Kremenekf2717b02008-07-18 17:24:20 +0000359 /// isEndPath - Returns true if executing the given method/function should
360 /// terminate the path.
361 bool isEndPath() const { return EndPath; }
362
Ted Kremenek272aa852008-06-25 21:21:56 +0000363 /// getReceiverEffect - Returns the effect on the receiver of the call.
364 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000365 ArgEffect getReceiverEffect() const {
366 return Receiver;
367 }
368
Ted Kremenek2719e982008-06-17 02:43:46 +0000369 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370
Ted Kremenek2719e982008-06-17 02:43:46 +0000371 ExprIterator begin_args() const { return Args->begin(); }
372 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373
Ted Kremenek266d8b62008-05-06 02:26:56 +0000374 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000375 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000376 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000377 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000378 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000379 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000380 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000381 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000382 }
383
384 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000385 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000386 }
387};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000388} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390//===----------------------------------------------------------------------===//
391// Data structures for constructing summaries.
392//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000393
Ted Kremenek272aa852008-06-25 21:21:56 +0000394namespace {
395class VISIBILITY_HIDDEN ObjCSummaryKey {
396 IdentifierInfo* II;
397 Selector S;
398public:
399 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
400 : II(ii), S(s) {}
401
402 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
403 : II(d ? d->getIdentifier() : 0), S(s) {}
404
405 ObjCSummaryKey(Selector s)
406 : II(0), S(s) {}
407
408 IdentifierInfo* getIdentifier() const { return II; }
409 Selector getSelector() const { return S; }
410};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000411}
412
413namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000414template <> struct DenseMapInfo<ObjCSummaryKey> {
415 static inline ObjCSummaryKey getEmptyKey() {
416 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
417 DenseMapInfo<Selector>::getEmptyKey());
418 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000419
Ted Kremenek272aa852008-06-25 21:21:56 +0000420 static inline ObjCSummaryKey getTombstoneKey() {
421 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
422 DenseMapInfo<Selector>::getTombstoneKey());
423 }
424
425 static unsigned getHashValue(const ObjCSummaryKey &V) {
426 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
427 & 0x88888888)
428 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
429 & 0x55555555);
430 }
431
432 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
433 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
434 RHS.getIdentifier()) &&
435 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
436 RHS.getSelector());
437 }
438
439 static bool isPod() {
440 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
441 DenseMapInfo<Selector>::isPod();
442 }
443};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000444} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000445
Ted Kremenek84f010c2008-06-23 23:30:29 +0000446namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000447class VISIBILITY_HIDDEN ObjCSummaryCache {
448 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
449 MapTy M;
450public:
451 ObjCSummaryCache() {}
452
453 typedef MapTy::iterator iterator;
454
455 iterator find(ObjCInterfaceDecl* D, Selector S) {
456
457 // Do a lookup with the (D,S) pair. If we find a match return
458 // the iterator.
459 ObjCSummaryKey K(D, S);
460 MapTy::iterator I = M.find(K);
461
462 if (I != M.end() || !D)
463 return I;
464
465 // Walk the super chain. If we find a hit with a parent, we'll end
466 // up returning that summary. We actually allow that key (null,S), as
467 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
468 // generate initial summaries without having to worry about NSObject
469 // being declared.
470 // FIXME: We may change this at some point.
471 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
472 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
473 break;
474
475 if (!C)
476 return I;
477 }
478
479 // Cache the summary with original key to make the next lookup faster
480 // and return the iterator.
481 M[K] = I->second;
482 return I;
483 }
484
Ted Kremenek9449ca92008-08-12 20:41:56 +0000485
Ted Kremenek272aa852008-06-25 21:21:56 +0000486 iterator find(Expr* Receiver, Selector S) {
487 return find(getReceiverDecl(Receiver), S);
488 }
489
490 iterator find(IdentifierInfo* II, Selector S) {
491 // FIXME: Class method lookup. Right now we dont' have a good way
492 // of going between IdentifierInfo* and the class hierarchy.
493 iterator I = M.find(ObjCSummaryKey(II, S));
494 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
495 }
496
497 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
498
499 const PointerType* PT = E->getType()->getAsPointerType();
500 if (!PT) return 0;
501
502 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
503 if (!OI) return 0;
504
505 return OI ? OI->getDecl() : 0;
506 }
507
508 iterator end() { return M.end(); }
509
510 RetainSummary*& operator[](ObjCMessageExpr* ME) {
511
512 Selector S = ME->getSelector();
513
514 if (Expr* Receiver = ME->getReceiver()) {
515 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
516 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
517 }
518
519 return M[ObjCSummaryKey(ME->getClassName(), S)];
520 }
521
522 RetainSummary*& operator[](ObjCSummaryKey K) {
523 return M[K];
524 }
525
526 RetainSummary*& operator[](Selector S) {
527 return M[ ObjCSummaryKey(S) ];
528 }
529};
530} // end anonymous namespace
531
532//===----------------------------------------------------------------------===//
533// Data structures for managing collections of summaries.
534//===----------------------------------------------------------------------===//
535
536namespace {
537class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000538
539 //==-----------------------------------------------------------------==//
540 // Typedefs.
541 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000542
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000543 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
544 ArgEffectsSetTy;
545
546 typedef llvm::FoldingSet<RetainSummary>
547 SummarySetTy;
548
549 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
550 FuncSummariesTy;
551
Ted Kremenek84f010c2008-06-23 23:30:29 +0000552 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000553
554 //==-----------------------------------------------------------------==//
555 // Data.
556 //==-----------------------------------------------------------------==//
557
Ted Kremenek272aa852008-06-25 21:21:56 +0000558 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000559 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000560
Ted Kremenekede40b72008-07-09 18:11:16 +0000561 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
562 /// "CFDictionaryCreate".
563 IdentifierInfo* CFDictionaryCreateII;
564
Ted Kremenek272aa852008-06-25 21:21:56 +0000565 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000566 const bool GCEnabled;
567
Ted Kremenek272aa852008-06-25 21:21:56 +0000568 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000569 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000570
Ted Kremenek272aa852008-06-25 21:21:56 +0000571 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000572 FuncSummariesTy FuncSummaries;
573
Ted Kremenek272aa852008-06-25 21:21:56 +0000574 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
575 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000576 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000577
Ted Kremenek272aa852008-06-25 21:21:56 +0000578 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000579 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000580
Ted Kremenek272aa852008-06-25 21:21:56 +0000581 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000582 ArgEffectsSetTy ArgEffectsSet;
583
Ted Kremenek272aa852008-06-25 21:21:56 +0000584 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
585 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000586 llvm::BumpPtrAllocator BPAlloc;
587
Ted Kremenek272aa852008-06-25 21:21:56 +0000588 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000589 ArgEffects ScratchArgs;
590
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000591 RetainSummary* StopSummary;
592
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000593 //==-----------------------------------------------------------------==//
594 // Methods.
595 //==-----------------------------------------------------------------==//
596
Ted Kremenek272aa852008-06-25 21:21:56 +0000597 /// getArgEffects - Returns a persistent ArgEffects object based on the
598 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000599 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000600
Ted Kremenek562c1302008-05-05 16:51:50 +0000601 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000602
603public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000604 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000605
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000606 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
607 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000608 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000609
Ted Kremenek266d8b62008-05-06 02:26:56 +0000610 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000611 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000612 ArgEffect DefaultEff = MayEscape,
613 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000614
Ted Kremenek266d8b62008-05-06 02:26:56 +0000615 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000616 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000617 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000618 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000619 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000620
Ted Kremenekbcaff792008-05-06 15:44:25 +0000621 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000622 if (StopSummary)
623 return StopSummary;
624
625 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
626 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000627
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000628 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000629 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000630
Ted Kremenek272aa852008-06-25 21:21:56 +0000631 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000632
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000633 void InitializeClassMethodSummaries();
634 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000635
Ted Kremenek35920ed2009-01-07 00:39:56 +0000636 bool isTrackedObjectType(QualType T);
637
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000638private:
639
Ted Kremenekf2717b02008-07-18 17:24:20 +0000640 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
641 RetainSummary* Summ) {
642 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
643 }
644
Ted Kremenek272aa852008-06-25 21:21:56 +0000645 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
646 ObjCClassMethodSummaries[S] = Summ;
647 }
648
649 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
650 ObjCMethodSummaries[S] = Summ;
651 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000652
653 void addClassMethSummary(const char* Cls, const char* nullaryName,
654 RetainSummary *Summ) {
655 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
656 Selector S = GetNullarySelector(nullaryName, Ctx);
657 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
658 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000659
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000660 void addInstMethSummary(const char* Cls, const char* nullaryName,
661 RetainSummary *Summ) {
662 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
663 Selector S = GetNullarySelector(nullaryName, Ctx);
664 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
665 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000666
667 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000668 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000669
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000670 while (const char* s = va_arg(argp, const char*))
671 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000672
673 return Ctx.Selectors.getSelector(II.size(), &II[0]);
674 }
675
676 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
677 RetainSummary* Summ, va_list argp) {
678 Selector S = generateSelector(argp);
679 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000680 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000681
682 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
683 va_list argp;
684 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000685 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000686 va_end(argp);
687 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000688
689 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
690 va_list argp;
691 va_start(argp, Summ);
692 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
693 va_end(argp);
694 }
695
696 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
697 va_list argp;
698 va_start(argp, Summ);
699 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
700 va_end(argp);
701 }
702
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000703 void addPanicSummary(const char* Cls, ...) {
704 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
705 DoNothing, DoNothing, true);
706 va_list argp;
707 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000708 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000709 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000710 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000711
Ted Kremeneka7338b42008-03-11 06:39:11 +0000712public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000713
714 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000715 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000716 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000717 GCEnabled(gcenabled), StopSummary(0) {
718
719 InitializeClassMethodSummaries();
720 InitializeMethodSummaries();
721 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000722
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000723 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000724
Ted Kremenekd13c1872008-06-24 03:56:45 +0000725 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000726 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek578498a2009-04-29 00:42:39 +0000727
728 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
729 ObjCInterfaceDecl *ID,
730 ObjCMethodDecl *MD, QualType RetTy);
731
732 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
733 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
734 ME->getClassInfo().first,
735 ME->getMethodDecl(), ME->getType());
736 }
737
738 RetainSummary* getCommonMethodSummary(ObjCMethodDecl* MD, Selector S,
739 QualType RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +0000740 RetainSummary* getMethodSummaryFromAnnotations(ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000741
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000742 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000743};
744
745} // end anonymous namespace
746
747//===----------------------------------------------------------------------===//
748// Implementation of checker data structures.
749//===----------------------------------------------------------------------===//
750
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000751RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000752
753 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
754 // mitigating the need to do explicit cleanup of the
755 // Argument-Effect summaries.
756
Ted Kremenek42ea0322008-05-05 23:55:01 +0000757 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
758 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000759 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000760}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000761
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000762ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000763
Ted Kremenekae855d42008-04-24 17:22:33 +0000764 if (ScratchArgs.empty())
765 return NULL;
766
767 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000768 llvm::FoldingSetNodeID profile;
769 profile.Add(ScratchArgs);
770 void* InsertPos;
771
Ted Kremenekae855d42008-04-24 17:22:33 +0000772 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000773 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000774 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000775
Ted Kremenekae855d42008-04-24 17:22:33 +0000776 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000777 ScratchArgs.clear();
778 return &E->getValue();
779 }
780
781 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000782 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000783
784 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000785 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000786
787 ScratchArgs.clear();
788 return &E->getValue();
789}
790
Ted Kremenek266d8b62008-05-06 02:26:56 +0000791RetainSummary*
792RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000793 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000794 ArgEffect DefaultEff,
795 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000796
Ted Kremenekae855d42008-04-24 17:22:33 +0000797 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000798 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000799 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
800 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000801
Ted Kremenekae855d42008-04-24 17:22:33 +0000802 // Look up the uniqued summary, or create one if it doesn't exist.
803 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000804 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000805
806 if (Summ)
807 return Summ;
808
Ted Kremenekae855d42008-04-24 17:22:33 +0000809 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000810 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000811 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000812 SummarySet.InsertNode(Summ, InsertPos);
813
814 return Summ;
815}
816
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000817//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000818// Predicates.
819//===----------------------------------------------------------------------===//
820
Ted Kremenek0d813552009-04-23 22:11:07 +0000821bool RetainSummaryManager::isTrackedObjectType(QualType Ty) {
822 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000823 return false;
824
Ted Kremenek0d813552009-04-23 22:11:07 +0000825 // We assume that id<..>, id, and "Class" all represent tracked objects.
826 const PointerType *PT = Ty->getAsPointerType();
827 if (PT == 0)
828 return true;
829
830 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000831
832 // We assume that id<..>, id, and "Class" all represent tracked objects.
833 if (!OT)
834 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000835
836 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000837 // FIXME: We can memoize here if this gets too expensive.
838 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
839 ObjCInterfaceDecl* ID = OT->getDecl();
840
841 for ( ; ID ; ID = ID->getSuperClass())
842 if (ID->getIdentifier() == NSObjectII)
843 return true;
844
845 return false;
846}
847
848//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000849// Summary creation for functions (largely uses of Core Foundation).
850//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000851
Ted Kremenek17144e82009-01-12 21:45:02 +0000852static bool isRetain(FunctionDecl* FD, const char* FName) {
853 const char* loc = strstr(FName, "Retain");
854 return loc && loc[sizeof("Retain")-1] == '\0';
855}
856
857static bool isRelease(FunctionDecl* FD, const char* FName) {
858 const char* loc = strstr(FName, "Release");
859 return loc && loc[sizeof("Release")-1] == '\0';
860}
861
Ted Kremenekd13c1872008-06-24 03:56:45 +0000862RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000863
864 SourceLocation Loc = FD->getLocation();
865
866 if (!Loc.isFileID())
867 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000868
Ted Kremenekae855d42008-04-24 17:22:33 +0000869 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000870 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000871
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000872 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000873 return I->second;
874
875 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000876 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000877
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000878 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000879 // We generate "stop" summaries for implicitly defined functions.
880 if (FD->isImplicit()) {
881 S = getPersistentStopSummary();
882 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000883 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000884
Ted Kremenek064ef322009-02-23 16:51:39 +0000885 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000886 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000887 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000888 const char* FName = FD->getIdentifier()->getName();
889
Ted Kremenek38c6f022009-03-05 22:11:14 +0000890 // Strip away preceding '_'. Doing this here will effect all the checks
891 // down below.
892 while (*FName == '_') ++FName;
893
Ted Kremenek17144e82009-01-12 21:45:02 +0000894 // Inspect the result type.
895 QualType RetTy = FT->getResultType();
896
897 // FIXME: This should all be refactored into a chain of "summary lookup"
898 // filters.
899 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
900 // FIXES: <rdar://problem/6326900>
901 // This should be addressed using a API table. This strcmp is also
902 // a little gross, but there is no need to super optimize here.
903 assert (ScratchArgs.empty());
904 ScratchArgs.push_back(std::make_pair(1, DecRef));
905 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
906 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000907 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000908
909 // Enable this code once the semantics of NSDeallocateObject are resolved
910 // for GC. <rdar://problem/6619988>
911#if 0
912 // Handle: NSDeallocateObject(id anObject);
913 // This method does allow 'nil' (although we don't check it now).
914 if (strcmp(FName, "NSDeallocateObject") == 0) {
915 return RetTy == Ctx.VoidTy
916 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
917 : getPersistentStopSummary();
918 }
919#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000920
921 // Handle: id NSMakeCollectable(CFTypeRef)
922 if (strcmp(FName, "NSMakeCollectable") == 0) {
923 S = (RetTy == Ctx.getObjCIdType())
924 ? getUnarySummary(FT, cfmakecollectable)
925 : getPersistentStopSummary();
926
927 break;
928 }
929
930 if (RetTy->isPointerType()) {
931 // For CoreFoundation ('CF') types.
932 if (isRefType(RetTy, "CF", &Ctx, FName)) {
933 if (isRetain(FD, FName))
934 S = getUnarySummary(FT, cfretain);
935 else if (strstr(FName, "MakeCollectable"))
936 S = getUnarySummary(FT, cfmakecollectable);
937 else
938 S = getCFCreateGetRuleSummary(FD, FName);
939
940 break;
941 }
942
943 // For CoreGraphics ('CG') types.
944 if (isRefType(RetTy, "CG", &Ctx, FName)) {
945 if (isRetain(FD, FName))
946 S = getUnarySummary(FT, cfretain);
947 else
948 S = getCFCreateGetRuleSummary(FD, FName);
949
950 break;
951 }
952
953 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
954 if (isRefType(RetTy, "DADisk") ||
955 isRefType(RetTy, "DADissenter") ||
956 isRefType(RetTy, "DASessionRef")) {
957 S = getCFCreateGetRuleSummary(FD, FName);
958 break;
959 }
960
961 break;
962 }
963
964 // Check for release functions, the only kind of functions that we care
965 // about that don't return a pointer type.
966 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000967 // Test for 'CGCF'.
968 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
969 FName += 4;
970 else
971 FName += 2;
972
973 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000974 S = getUnarySummary(FT, cfrelease);
975 else {
Ted Kremenek7b293682009-01-29 22:45:13 +0000976 assert (ScratchArgs.empty());
977 // Remaining CoreFoundation and CoreGraphics functions.
978 // We use to assume that they all strictly followed the ownership idiom
979 // and that ownership cannot be transferred. While this is technically
980 // correct, many methods allow a tracked object to escape. For example:
981 //
982 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
983 // CFDictionaryAddValue(y, key, x);
984 // CFRelease(x);
985 // ... it is okay to use 'x' since 'y' has a reference to it
986 //
987 // We handle this and similar cases with the follow heuristic. If the
988 // function name contains "InsertValue", "SetValue" or "AddValue" then
989 // we assume that arguments may "escape."
990 //
991 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
992 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000993 CStrInCStrNoCase(FName, "SetValue") ||
994 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000995 ? MayEscape : DoNothing;
996
997 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000998 }
999 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001000 }
1001 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +00001002
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001003 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001004 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001005}
1006
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001007RetainSummary*
1008RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1009 const char* FName) {
1010
Ted Kremenek562c1302008-05-05 16:51:50 +00001011 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1012 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001013
Ted Kremenek562c1302008-05-05 16:51:50 +00001014 if (strstr(FName, "Get"))
1015 return getCFSummaryGetRule(FD);
1016
1017 return 0;
1018}
1019
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001020RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001021RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1022 UnaryFuncKind func) {
1023
Ted Kremenek17144e82009-01-12 21:45:02 +00001024 // Sanity check that this is *really* a unary function. This can
1025 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001026 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001027 if (!FTP || FTP->getNumArgs() != 1)
1028 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001029
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001030 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001031
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001032 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +00001033 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001034 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001035 return getPersistentSummary(RetEffect::MakeAlias(0),
1036 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001037 }
1038
1039 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001040 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001041 return getPersistentSummary(RetEffect::MakeNoRet(),
1042 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001043 }
1044
1045 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +00001046 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1047 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001048 }
1049
1050 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001051 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001052 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001053 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001054}
1055
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001056RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001057 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001058
1059 if (FD->getIdentifier() == CFDictionaryCreateII) {
1060 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1061 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1062 }
1063
Ted Kremenek68621b92009-01-28 05:56:51 +00001064 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001065}
1066
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001067RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001068 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001069 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1070 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001071}
1072
Ted Kremeneka7338b42008-03-11 06:39:11 +00001073//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001074// Summary creation for Selectors.
1075//===----------------------------------------------------------------------===//
1076
Ted Kremenekbcaff792008-05-06 15:44:25 +00001077RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001078RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001079 assert(ScratchArgs.empty());
1080
Ted Kremenek802cfc72009-02-20 00:05:35 +00001081 // 'init' methods only return an alias if the return type is a location type.
1082 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001083 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +00001084 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1085 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001086
Ted Kremenek272aa852008-06-25 21:21:56 +00001087 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001088 return Summ;
1089}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001090
Ted Kremenek923fc392009-04-24 23:32:32 +00001091RetainSummary*
1092RetainSummaryManager::getMethodSummaryFromAnnotations(ObjCMethodDecl *MD) {
1093 if (!MD)
1094 return 0;
1095
1096 assert(ScratchArgs.empty());
1097
1098 // Determine if there is a special return effect for this method.
1099 bool hasRetEffect = false;
1100 RetEffect RE = RetEffect::MakeNoRet();
1101
1102 if (isTrackedObjectType(MD->getResultType())) {
1103 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001104 RE = isGCEnabled() ? RetEffect::MakeGCNotOwned()
1105 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek923fc392009-04-24 23:32:32 +00001106 hasRetEffect = true;
1107 }
1108 else {
1109 // Default to 'not owned'.
1110 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1111 }
1112 }
1113
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001114 // Determine if there are any arguments with a specific ArgEffect.
1115 bool hasArgEffect = false;
1116 unsigned i = 0;
1117 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1118 E = MD->param_end(); I != E; ++I, ++i) {
1119 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
1120 ScratchArgs.push_back(std::make_pair(i, IncRefMsg));
1121 hasArgEffect = true;
1122 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001123 else if ((*I)->getAttr<ObjCOwnershipCFRetainAttr>()) {
1124 ScratchArgs.push_back(std::make_pair(i, IncRef));
1125 hasArgEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001126 }
1127 else if ((*I)->getAttr<ObjCOwnershipReleaseAttr>()) {
1128 ScratchArgs.push_back(std::make_pair(i, DecRefMsg));
1129 hasArgEffect = true;
1130 }
1131 else if ((*I)->getAttr<ObjCOwnershipCFReleaseAttr>()) {
1132 ScratchArgs.push_back(std::make_pair(i, DecRef));
1133 hasArgEffect = true;
1134 }
Ted Kremenekff8648d2009-04-28 22:32:26 +00001135 else if ((*I)->getAttr<ObjCOwnershipMakeCollectableAttr>()) {
1136 ScratchArgs.push_back(std::make_pair(i, MakeCollectable));
1137 hasArgEffect = true;
1138 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001139 }
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001140
1141 if (!hasRetEffect && !hasArgEffect)
Ted Kremenek923fc392009-04-24 23:32:32 +00001142 return 0;
1143
1144 return getPersistentSummary(RE);
1145}
Ted Kremenek272aa852008-06-25 21:21:56 +00001146
Ted Kremenekbcaff792008-05-06 15:44:25 +00001147RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001148RetainSummaryManager::getCommonMethodSummary(ObjCMethodDecl* MD, Selector S,
1149 QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001150
Ted Kremenek578498a2009-04-29 00:42:39 +00001151 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001152 // Scan the method decl for 'void*' arguments. These should be treated
1153 // as 'StopTracking' because they are often used with delegates.
1154 // Delegates are a frequent form of false positives with the retain
1155 // count checker.
1156 unsigned i = 0;
1157 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1158 E = MD->param_end(); I != E; ++I, ++i)
1159 if (ParmVarDecl *PD = *I) {
1160 QualType Ty = Ctx.getCanonicalType(PD->getType());
1161 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
1162 ScratchArgs.push_back(std::make_pair(i, StopTracking));
1163 }
1164 }
1165
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001166 // Any special effect for the receiver?
1167 ArgEffect ReceiverEff = DoNothing;
1168
1169 // If one of the arguments in the selector has the keyword 'delegate' we
1170 // should stop tracking the reference count for the receiver. This is
1171 // because the reference count is quite possibly handled by a delegate
1172 // method.
1173 if (S.isKeywordSelector()) {
1174 const std::string &str = S.getAsString();
1175 assert(!str.empty());
1176 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1177 }
1178
Ted Kremenek174a0772009-04-23 23:08:22 +00001179 // Look for methods that return an owned object.
Ted Kremenek578498a2009-04-29 00:42:39 +00001180 if (!isTrackedObjectType(RetTy)) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001181 if (ScratchArgs.empty() && ReceiverEff == DoNothing)
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001182 return 0;
1183
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001184 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1185 MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001186 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001187
1188 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1189 // by instance methods.
1190
1191 RetEffect E =
Ted Kremenekaca0b452009-04-24 18:19:07 +00001192 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001193 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek174a0772009-04-23 23:08:22 +00001194 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1195 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1196
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001197 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001198}
1199
1200RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001201RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1202 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001203
1204 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001205
Ted Kremenek272aa852008-06-25 21:21:56 +00001206 // Look up a summary in our summary cache.
1207 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001208
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001209 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001210 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001211
Ted Kremenek174a0772009-04-23 23:08:22 +00001212 assert(ScratchArgs.empty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001213
1214 // Annotations take precedence over all other ways to derive
1215 // summaries.
1216 RetainSummary *Summ = getMethodSummaryFromAnnotations(ME->getMethodDecl());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001217
Ted Kremenek923fc392009-04-24 23:32:32 +00001218 if (!Summ) {
1219 // "initXXX": pass-through for receiver.
1220 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1221 == InitRule)
1222 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +00001223
Ted Kremenek578498a2009-04-29 00:42:39 +00001224 Summ = getCommonMethodSummary(ME->getMethodDecl(), S, ME->getType());
Ted Kremenek923fc392009-04-24 23:32:32 +00001225 }
1226
Ted Kremeneke4158502009-04-23 19:11:35 +00001227 ObjCMethodSummaries[ME] = Summ;
1228 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001229}
1230
Ted Kremeneka7722b72008-05-06 21:26:51 +00001231RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001232RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
1233 ObjCInterfaceDecl *ID,
1234 ObjCMethodDecl *MD, QualType RetTy){
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001235
Ted Kremenek578498a2009-04-29 00:42:39 +00001236 assert(ClsName && "Class name must be specified.");
1237 ObjCMethodSummariesTy::iterator I;
Ted Kremenek272aa852008-06-25 21:21:56 +00001238
Ted Kremenek578498a2009-04-29 00:42:39 +00001239 if (ID) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001240 // Lookup the method using the decl for the class @interface.
1241 I = ObjCClassMethodSummaries.find(ID, S);
1242 }
1243 else {
1244 // Fallback to using the class name.
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001245 // Look up a summary in our cache of Selectors -> Summaries.
1246 I = ObjCClassMethodSummaries.find(ClsName, S);
1247 }
Ted Kremeneka7722b72008-05-06 21:26:51 +00001248
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001249 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001250 return I->second;
1251
Ted Kremenek923fc392009-04-24 23:32:32 +00001252 // Annotations take precedence over all other ways to derive
1253 // summaries.
Ted Kremenek578498a2009-04-29 00:42:39 +00001254 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001255
1256 if (!Summ)
Ted Kremenek578498a2009-04-29 00:42:39 +00001257 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001258
Ted Kremenek578498a2009-04-29 00:42:39 +00001259 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001260 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001261}
1262
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001263void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001264
1265 assert (ScratchArgs.empty());
1266
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001267 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001268 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001269
Ted Kremenek0e344d42008-05-06 00:30:21 +00001270 RetainSummary* Summ = getPersistentSummary(E);
1271
Ted Kremenek272aa852008-06-25 21:21:56 +00001272 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1273 // NSObject and its derivatives.
1274 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1275 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1276 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001277
1278 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001279 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001280 GetNullarySelector("currentHandler", Ctx),
1281 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001282
1283 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001284 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1285 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1286 GetUnarySelector("addObject", Ctx),
1287 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001288 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001289
1290 // Create the summaries for [NSObject performSelector...]. We treat
1291 // these as 'stop tracking' for the arguments because they are often
1292 // used for delegates that can release the object. When we have better
1293 // inter-procedural analysis we can potentially do something better. This
1294 // workaround is to remove false positives.
1295 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1296 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1297 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1298 "afterDelay", NULL);
1299 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1300 "afterDelay", "inModes", NULL);
1301 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1302 "withObject", "waitUntilDone", NULL);
1303 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1304 "withObject", "waitUntilDone", "modes", NULL);
1305 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1306 "withObject", "waitUntilDone", NULL);
1307 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1308 "withObject", "waitUntilDone", "modes", NULL);
1309 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1310 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001311}
1312
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001313void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001314
1315 assert (ScratchArgs.empty());
1316
Ted Kremeneka7722b72008-05-06 21:26:51 +00001317 // Create the "init" selector. It just acts as a pass-through for the
1318 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001319 RetainSummary* InitSumm =
1320 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001321 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001322
1323 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001324 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001325 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001326
Ted Kremeneke44927e2008-07-01 17:21:27 +00001327 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001328
1329 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001330 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1331
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001332 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001333 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001334
Ted Kremenek266d8b62008-05-06 02:26:56 +00001335 // Create the "retain" selector.
1336 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001337 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001338 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001339
1340 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001341 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001342 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001343
1344 // Create the "drain" selector.
1345 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001346 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001347
1348 // Create the -dealloc summary.
1349 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1350 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001351
1352 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001353 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001354 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001355
Ted Kremenekaac82832009-02-23 17:45:03 +00001356 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001357 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001358 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001359 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001360
Ted Kremenek45642a42008-08-12 18:48:50 +00001361 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001362 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1363 // self-own themselves. However, they only do this once they are displayed.
1364 // Thus, we need to track an NSWindow's display status.
1365 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001366 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001367 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1368
1369 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1370
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001371
1372#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001373 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001374 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001375
1376 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1377 "styleMask", "backing", "defer", NULL);
1378
1379 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1380 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001381#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001382
1383 // For NSPanel (which subclasses NSWindow), allocated objects are not
1384 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001385 // FIXME: For now we don't track NSPanels. object for the same reason
1386 // as for NSWindow objects.
1387 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1388
Ted Kremenek45642a42008-08-12 18:48:50 +00001389 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1390 "styleMask", "backing", "defer", NULL);
1391
1392 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1393 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001394
Ted Kremenekf2717b02008-07-18 17:24:20 +00001395 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001396 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1397 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001398
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001399 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1400 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001401}
1402
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001403//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001404// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001405//===----------------------------------------------------------------------===//
1406
Ted Kremeneka7338b42008-03-11 06:39:11 +00001407namespace {
1408
Ted Kremenek7d421f32008-04-09 23:49:11 +00001409class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001410public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001411 enum Kind {
1412 Owned = 0, // Owning reference.
1413 NotOwned, // Reference is not owned by still valid (not freed).
1414 Released, // Object has been released.
1415 ReturnedOwned, // Returned object passes ownership to caller.
1416 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001417 ERROR_START,
1418 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1419 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001420 ErrorUseAfterRelease, // Object used after released.
1421 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001422 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001423 ErrorLeak, // A memory leak due to excessive reference counts.
1424 ErrorLeakReturned // A memory leak due to the returning method not having
1425 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001426 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001427
1428private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001429 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001430 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001431 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001432 QualType T;
1433
Ted Kremenek68621b92009-01-28 05:56:51 +00001434 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1435 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001436
Ted Kremenek68621b92009-01-28 05:56:51 +00001437 RefVal(Kind k, unsigned cnt = 0)
1438 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1439
1440public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001441 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001442
1443 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001444
Ted Kremenek6537a642009-03-17 19:42:23 +00001445 unsigned getCount() const { return Cnt; }
1446 void clearCounts() { Cnt = 0; }
1447
Ted Kremenek272aa852008-06-25 21:21:56 +00001448 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001449
1450 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001451
Ted Kremenek6537a642009-03-17 19:42:23 +00001452 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001453
Ted Kremenek6537a642009-03-17 19:42:23 +00001454 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001455
Ted Kremenekffefc352008-04-11 22:25:11 +00001456 bool isOwned() const {
1457 return getKind() == Owned;
1458 }
1459
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001460 bool isNotOwned() const {
1461 return getKind() == NotOwned;
1462 }
1463
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001464 bool isReturnedOwned() const {
1465 return getKind() == ReturnedOwned;
1466 }
1467
1468 bool isReturnedNotOwned() const {
1469 return getKind() == ReturnedNotOwned;
1470 }
1471
1472 bool isNonLeakError() const {
1473 Kind k = getKind();
1474 return isError(k) && !isLeak(k);
1475 }
1476
Ted Kremenek68621b92009-01-28 05:56:51 +00001477 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1478 unsigned Count = 1) {
1479 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001480 }
1481
Ted Kremenek68621b92009-01-28 05:56:51 +00001482 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1483 unsigned Count = 0) {
1484 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001485 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001486
1487 static RefVal makeReturnedOwned(unsigned Count) {
1488 return RefVal(ReturnedOwned, Count);
1489 }
1490
1491 static RefVal makeReturnedNotOwned() {
1492 return RefVal(ReturnedNotOwned);
1493 }
1494
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001495 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001496
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001497 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001498 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001499 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001500
Ted Kremenek272aa852008-06-25 21:21:56 +00001501 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001502 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001503 }
1504
1505 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001506 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001507 }
1508
1509 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001510 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001511 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001512
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001513 void Profile(llvm::FoldingSetNodeID& ID) const {
1514 ID.AddInteger((unsigned) kind);
1515 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001516 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001517 }
1518
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001519 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001520};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001521
1522void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001523 if (!T.isNull())
1524 Out << "Tracked Type:" << T.getAsString() << '\n';
1525
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001526 switch (getKind()) {
1527 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001528 case Owned: {
1529 Out << "Owned";
1530 unsigned cnt = getCount();
1531 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001532 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001533 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001534
Ted Kremenekc4f81022008-04-10 23:09:18 +00001535 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001536 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001537 unsigned cnt = getCount();
1538 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001539 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001540 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001541
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001542 case ReturnedOwned: {
1543 Out << "ReturnedOwned";
1544 unsigned cnt = getCount();
1545 if (cnt) Out << " (+ " << cnt << ")";
1546 break;
1547 }
1548
1549 case ReturnedNotOwned: {
1550 Out << "ReturnedNotOwned";
1551 unsigned cnt = getCount();
1552 if (cnt) Out << " (+ " << cnt << ")";
1553 break;
1554 }
1555
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001556 case Released:
1557 Out << "Released";
1558 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001559
1560 case ErrorDeallocGC:
1561 Out << "-dealloc (GC)";
1562 break;
1563
1564 case ErrorDeallocNotOwned:
1565 Out << "-dealloc (not-owned)";
1566 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001567
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001568 case ErrorLeak:
1569 Out << "Leaked";
1570 break;
1571
Ted Kremenek311f3d42008-10-22 23:56:21 +00001572 case ErrorLeakReturned:
1573 Out << "Leaked (Bad naming)";
1574 break;
1575
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001576 case ErrorUseAfterRelease:
1577 Out << "Use-After-Release [ERROR]";
1578 break;
1579
1580 case ErrorReleaseNotOwned:
1581 Out << "Release of Not-Owned [ERROR]";
1582 break;
1583 }
1584}
Ted Kremenek0d721572008-03-11 17:48:22 +00001585
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001586} // end anonymous namespace
1587
1588//===----------------------------------------------------------------------===//
1589// RefBindings - State used to track object reference counts.
1590//===----------------------------------------------------------------------===//
1591
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001592typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001593static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001594static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001595
1596namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001597 template<>
1598 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1599 static inline void* GDMIndex() { return &RefBIndex; }
1600 };
1601}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001602
1603//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001604// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001605//===----------------------------------------------------------------------===//
1606
Ted Kremenekb6578942009-02-24 19:15:11 +00001607typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1608typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1609typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001610
Ted Kremenekb6578942009-02-24 19:15:11 +00001611static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001612static int AutoRBIndex = 0;
1613
Ted Kremenekb6578942009-02-24 19:15:11 +00001614namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001615namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001616
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001617namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001618template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001619 : public GRStatePartialTrait<ARStack> {
1620 static inline void* GDMIndex() { return &AutoRBIndex; }
1621};
1622
1623template<> struct GRStateTrait<AutoreleasePoolContents>
1624 : public GRStatePartialTrait<ARPoolContents> {
1625 static inline void* GDMIndex() { return &AutoRCIndex; }
1626};
1627} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001628
Ted Kremenek681fb352009-03-20 17:34:15 +00001629static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1630 ARStack stack = state->get<AutoreleaseStack>();
1631 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1632}
1633
1634static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1635 SymbolRef sym) {
1636
1637 SymbolRef pool = GetCurrentAutoreleasePool(state);
1638 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1639 ARCounts newCnts(0);
1640
1641 if (cnts) {
1642 const unsigned *cnt = (*cnts).lookup(sym);
1643 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1644 }
1645 else
1646 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1647
1648 return state.set<AutoreleasePoolContents>(pool, newCnts);
1649}
1650
Ted Kremenek7aef4842008-04-16 20:40:59 +00001651//===----------------------------------------------------------------------===//
1652// Transfer functions.
1653//===----------------------------------------------------------------------===//
1654
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001655namespace {
1656
Ted Kremenek7d421f32008-04-09 23:49:11 +00001657class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001658public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001659 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001660 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001661 virtual void Print(std::ostream& Out, const GRState* state,
1662 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001663 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001664
1665private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001666 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1667 SummaryLogTy;
1668
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001669 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001670 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001671 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001672 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001673
Ted Kremenek708af042009-02-05 06:50:21 +00001674 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001675 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001676 BugType *leakWithinFunction, *leakAtReturn;
1677 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001678
Ted Kremenekb6578942009-02-24 19:15:11 +00001679 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1680 RefVal::Kind& hasErr);
1681
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001682 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1683 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001684 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001685 ExplodedNode<GRState>* Pred,
1686 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001687 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001688
Ted Kremenek0106e202008-10-24 20:32:50 +00001689 std::pair<GRStateRef, bool>
1690 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001691 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001692
Ted Kremenekb6578942009-02-24 19:15:11 +00001693public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001694 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001695 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001696 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1697 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001698 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001699
Ted Kremenek708af042009-02-05 06:50:21 +00001700 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001701
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001702 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001703
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001704 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1705 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001706 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001707
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001708 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001709 const LangOptions& getLangOptions() const { return LOpts; }
1710
Ted Kremenekc26c4692009-02-18 03:48:14 +00001711 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1712 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1713 return I == SummaryLog.end() ? 0 : I->second;
1714 }
1715
Ted Kremeneka7338b42008-03-11 06:39:11 +00001716 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001717
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001718 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001719 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001720 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001721 Expr* Ex,
1722 Expr* Receiver,
1723 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001724 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001725 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001726
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001727 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001728 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001729 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001730 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001731 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001732
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001733
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001734 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001735 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001736 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001737 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001738 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001739
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001740 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001741 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001742 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001743 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001744 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001745
Ted Kremeneka42be302009-02-14 01:43:44 +00001746 // Stores.
1747 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1748
Ted Kremenekffefc352008-04-11 22:25:11 +00001749 // End-of-path.
1750
1751 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001752 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001753
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001754 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001755 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001756 GRStmtNodeBuilder<GRState>& Builder,
1757 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001758 Stmt* S, const GRState* state,
1759 SymbolReaper& SymReaper);
1760
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001761 // Return statements.
1762
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001763 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001764 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001765 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001766 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001767 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001768
1769 // Assumptions.
1770
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001771 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001772 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001773 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001774};
1775
1776} // end anonymous namespace
1777
Ted Kremenek681fb352009-03-20 17:34:15 +00001778static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1779 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001780 if (Sym)
1781 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001782 else
1783 Out << "<pool>";
1784 Out << ":{";
1785
1786 // Get the contents of the pool.
1787 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1788 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1789 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1790
1791 Out << '}';
1792}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001793
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001794void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1795 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001796
1797
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001798
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001799 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001800
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001801 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001802 Out << sep << nl;
1803
1804 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1805 Out << (*I).first << " : ";
1806 (*I).second.print(Out);
1807 Out << nl;
1808 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001809
1810 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001811 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001812 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001813
Ted Kremenek681fb352009-03-20 17:34:15 +00001814 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1815 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1816 PrintPool(Out, *I, state);
1817
1818 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001819}
1820
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001821static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001822 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001823}
1824
Ted Kremenek266d8b62008-05-06 02:26:56 +00001825static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1826 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001827}
1828
Ted Kremenek227c5372008-05-06 02:41:27 +00001829static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1830 return Summ ? Summ->getReceiverEffect() : DoNothing;
1831}
1832
Ted Kremenekf2717b02008-07-18 17:24:20 +00001833static inline bool IsEndPath(RetainSummary* Summ) {
1834 return Summ ? Summ->isEndPath() : false;
1835}
1836
Ted Kremenek1feab292008-04-16 04:28:53 +00001837
Ted Kremenek272aa852008-06-25 21:21:56 +00001838/// GetReturnType - Used to get the return type of a message expression or
1839/// function call with the intention of affixing that type to a tracked symbol.
1840/// While the the return type can be queried directly from RetEx, when
1841/// invoking class methods we augment to the return type to be that of
1842/// a pointer to the class (as opposed it just being id).
1843static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1844
1845 QualType RetTy = RetE->getType();
1846
1847 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001848 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001849 if (!PT)
1850 return RetTy;
1851
1852 // If RetEx is not a message expression just return its type.
1853 // If RetEx is a message expression, return its types if it is something
1854 /// more specific than id.
1855
1856 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1857
Steve Naroff17c03822009-02-12 17:52:19 +00001858 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001859 return RetTy;
1860
1861 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1862
1863 // At this point we know the return type of the message expression is id.
1864 // If we have an ObjCInterceDecl, we know this is a call to a class method
1865 // whose type we can resolve. In such cases, promote the return type to
1866 // Class*.
1867 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1868}
1869
1870
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001871void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001872 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001873 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001874 Expr* Ex,
1875 Expr* Receiver,
1876 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00001877 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001878 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001879
Ted Kremeneka7338b42008-03-11 06:39:11 +00001880 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001881 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001882 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001883
1884 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001885 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001886 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001887 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001888 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001889
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001890 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001891 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001892 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001893
Ted Kremenek74556a12009-03-26 03:35:11 +00001894 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00001895 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1896 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1897 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001898 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001899 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001900 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001901 }
1902 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00001903 }
Ted Kremenekede40b72008-07-09 18:11:16 +00001904
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001905 if (isa<Loc>(V)) {
1906 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001907 if (GetArgE(Summ, idx) == DoNothingByRef)
1908 continue;
1909
1910 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001911
1912 // FIXME: Either this logic should also be replicated in GRSimpleVals
1913 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001914
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001915 // FIXME: We can have collisions on the conjured symbol if the
1916 // expression *I also creates conjured symbols. We probably want
1917 // to identify conjured symbols by an expression pair: the enclosing
1918 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001919 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001920
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001921 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001922
Ted Kremenekb1855e62009-04-28 18:48:13 +00001923 // Blast through TypedViewRegions to get the original region type.
1924 while (R) {
1925 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
1926 if (!ATR) break;
1927 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1928 }
1929
Ted Kremenek53b24182009-03-04 22:56:43 +00001930 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001931 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001932 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001933
Ted Kremenek53b24182009-03-04 22:56:43 +00001934 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00001935 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001936
Ted Kremenek53b24182009-03-04 22:56:43 +00001937 if (R->isBoundable(Ctx)) {
1938 // Set the value of the variable to be a conjured symbol.
1939 unsigned Count = Builder.getCurrentBlockCount();
1940 QualType T = R->getRValueType(Ctx);
1941
Zhongxing Xu079dc352009-04-09 06:03:54 +00001942 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001943 ValueManager &ValMgr = Eng.getValueManager();
1944 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00001945 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00001946 }
1947 else if (const RecordType *RT = T->getAsStructureType()) {
1948 // Handle structs in a not so awesome way. Here we just
1949 // eagerly bind new symbols to the fields. In reality we
1950 // should have the store manager handle this. The idea is just
1951 // to prototype some basic functionality here. All of this logic
1952 // should one day soon just go away.
1953 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1954
1955 // No record definition. There is nothing we can do.
1956 if (!RD)
1957 continue;
1958
1959 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1960
1961 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001962 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
1963 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00001964
1965 // For now just handle scalar fields.
1966 FieldDecl *FD = *FI;
1967 QualType FT = FD->getType();
1968
1969 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001970 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00001971 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001972 ValueManager &ValMgr = Eng.getValueManager();
1973 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00001974 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00001975 }
1976 }
1977 }
1978 else {
1979 // Just blast away other values.
1980 state = state.BindLoc(*MR, UnknownVal());
1981 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00001982 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001983 }
1984 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001985 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001986 }
1987 else {
1988 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001989 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001990 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001991 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001992 else if (isa<nonloc::LocAsInteger>(V))
1993 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001994 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001995
Ted Kremenek272aa852008-06-25 21:21:56 +00001996 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001997 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001998 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00001999 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002000 if (const RefVal* T = state.get<RefBindings>(Sym)) {
2001 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
2002 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002003 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002004 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002005 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002006 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002007 }
2008 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002009
Ted Kremenek272aa852008-06-25 21:21:56 +00002010 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002011 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002012 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002013 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002014 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002015 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002016
Ted Kremenekf2717b02008-07-18 17:24:20 +00002017 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00002018 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002019
2020 switch (RE.getKind()) {
2021 default:
2022 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002023
Ted Kremenek8f90e712008-10-17 22:23:12 +00002024 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002025
Ted Kremenek455dd862008-04-11 20:23:24 +00002026 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002027 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2028 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002029
Ted Kremenek8f90e712008-10-17 22:23:12 +00002030 // FIXME: We eventually should handle structs and other compound types
2031 // that are returned by value.
2032
2033 QualType T = Ex->getType();
2034
Ted Kremenek79413a52008-11-13 06:10:40 +00002035 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002036 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002037 ValueManager &ValMgr = Eng.getValueManager();
2038 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002039 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002040 }
2041
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002042 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002043 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002044
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002045 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002046 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002047 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002048 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002049 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002050 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002051 break;
2052 }
2053
Ted Kremenek227c5372008-05-06 02:41:27 +00002054 case RetEffect::ReceiverAlias: {
2055 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002056 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002057 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002058 break;
2059 }
2060
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002061 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002062 case RetEffect::OwnedSymbol: {
2063 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002064 ValueManager &ValMgr = Eng.getValueManager();
2065 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2066 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2067 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2068 RetT));
2069 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002070
2071 // FIXME: Add a flag to the checker where allocations are assumed to
2072 // *not fail.
2073#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002074 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2075 bool isFeasible;
2076 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2077 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2078 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002079#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002080
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002081 break;
2082 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002083
2084 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002085 case RetEffect::NotOwnedSymbol: {
2086 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002087 ValueManager &ValMgr = Eng.getValueManager();
2088 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2089 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2090 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2091 RetT));
2092 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002093 break;
2094 }
2095 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002096
Ted Kremenek0dd65012009-02-18 02:00:25 +00002097 // Generate a sink node if we are at the end of a path.
2098 GRExprEngine::NodeTy *NewNode =
2099 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2100 : Builder.MakeNode(Dst, Ex, Pred, state);
2101
2102 // Annotate the edge with summary we used.
2103 // FIXME: This assumes that we always use the same summary when generating
2104 // this node.
2105 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002106}
2107
2108
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002109void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002110 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002111 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002112 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002113 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002114 const FunctionDecl* FD = L.getAsFunctionDecl();
2115 RetainSummary* Summ = !FD ? 0
2116 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002117
2118 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2119 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002120}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002121
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002122void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002123 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002124 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002125 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002126 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002127 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002128
Ted Kremenek272aa852008-06-25 21:21:56 +00002129 if (Expr* Receiver = ME->getReceiver()) {
2130 // We need the type-information of the tracked receiver object
2131 // Retrieve it from the state.
2132 ObjCInterfaceDecl* ID = 0;
2133
2134 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2135 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002136 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002137 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002138
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002139 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002140 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002141 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002142 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002143
2144 if (const PointerType* PT = Ty->getAsPointerType()) {
2145 QualType PointeeTy = PT->getPointeeType();
2146
2147 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2148 ID = IT->getDecl();
2149 }
2150 }
2151 }
2152
2153 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002154
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002155 // Special-case: are we sending a mesage to "self"?
2156 // This is a hack. When we have full-IP this should be removed.
2157 if (!Summ) {
2158 ObjCMethodDecl* MD =
2159 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2160
2161 if (MD) {
2162 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002163 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002164 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002165 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2166 // Create a summmary where all of the arguments "StopTracking".
2167 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2168 DoNothing,
2169 StopTracking);
2170 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002171 }
2172 }
2173 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002174 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002175 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002176 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002177
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002178
Ted Kremenek926abf22008-05-06 04:20:12 +00002179 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2180 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002181}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002182
2183namespace {
2184class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2185 GRStateRef state;
2186public:
2187 StopTrackingCallback(GRStateRef st) : state(st) {}
2188 GRStateRef getState() { return state; }
2189
2190 bool VisitSymbol(SymbolRef sym) {
2191 state = state.remove<RefBindings>(sym);
2192 return true;
2193 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002194
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002195 const GRState* getState() const { return state.getState(); }
2196};
2197} // end anonymous namespace
2198
2199
Ted Kremeneka42be302009-02-14 01:43:44 +00002200void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002201 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002202 bool escapes = false;
2203
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002204 // A value escapes in three possible cases (this may change):
2205 //
2206 // (1) we are binding to something that is not a memory region.
2207 // (2) we are binding to a memregion that does not have stack storage
2208 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002209 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002210 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002211
Ted Kremeneka42be302009-02-14 01:43:44 +00002212 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002213 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002214 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002215 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2216 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002217
2218 if (!escapes) {
2219 // To test (3), generate a new state with the binding removed. If it is
2220 // the same state, then it escapes (since the store cannot represent
2221 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002222 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002223 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002224 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002225
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002226 // If our store can represent the binding and we aren't storing to something
2227 // that doesn't have local storage then just return and have the simulation
2228 // state continue as is.
2229 if (!escapes)
2230 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002231
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002232 // Otherwise, find all symbols referenced by 'val' that we are tracking
2233 // and stop tracking them.
2234 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002235}
2236
Ted Kremenek0106e202008-10-24 20:32:50 +00002237std::pair<GRStateRef,bool>
2238CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2239 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002240 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002241 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002242
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002243 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00002244 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00002245 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002246
Ted Kremenek311f3d42008-10-22 23:56:21 +00002247 if (V.isReturnedOwned() && V.getCount() == 0)
2248 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00002249 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00002250 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00002251 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00002252 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2253 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00002254 }
2255 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002256
Ted Kremenek311f3d42008-10-22 23:56:21 +00002257 // All other cases.
2258
2259 hasLeak = V.isOwned() ||
2260 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002261
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002262 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002263 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002264
Ted Kremenek0106e202008-10-24 20:32:50 +00002265 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2266 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002267}
2268
Ted Kremenek541db372008-04-24 23:57:27 +00002269
Ted Kremenekffefc352008-04-11 22:25:11 +00002270
Ted Kremenek541db372008-04-24 23:57:27 +00002271// Dead symbols.
2272
Ted Kremenek708af042009-02-05 06:50:21 +00002273
Ted Kremenek541db372008-04-24 23:57:27 +00002274
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002275 // Return statements.
2276
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002277void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002278 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002279 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002280 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002281 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002282
2283 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002284 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002285 return;
2286
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002287 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002288 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002289
Ted Kremenek74556a12009-03-26 03:35:11 +00002290 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002291 return;
2292
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002293 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002294 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002295
2296 if (!T)
2297 return;
2298
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002299 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002300 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002301
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002302 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002303 case RefVal::Owned: {
2304 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002305 assert (cnt > 0);
2306 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002307 break;
2308 }
2309
2310 case RefVal::NotOwned: {
2311 unsigned cnt = X.getCount();
2312 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2313 : RefVal::makeReturnedNotOwned();
2314 break;
2315 }
2316
2317 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002318 return;
2319 }
2320
2321 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002322 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002323 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002324}
2325
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002326// Assumptions.
2327
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002328const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2329 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002330 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002331 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002332
2333 // FIXME: We may add to the interface of EvalAssume the list of symbols
2334 // whose assumptions have changed. For now we just iterate through the
2335 // bindings and check if any of the tracked symbols are NULL. This isn't
2336 // too bad since the number of symbols we will track in practice are
2337 // probably small and EvalAssume is only called at branches and a few
2338 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002339 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002340
2341 if (B.isEmpty())
2342 return St;
2343
2344 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002345
2346 GRStateRef state(St, VMgr);
2347 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002348
2349 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002350 // Check if the symbol is null (or equal to any constant).
2351 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002352 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002353 changed = true;
2354 B = RefBFactory.Remove(B, I.getKey());
2355 }
2356 }
2357
Ted Kremenek91781202008-08-17 03:20:02 +00002358 if (changed)
2359 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002360
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002361 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002362}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002363
Ted Kremenekb6578942009-02-24 19:15:11 +00002364GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2365 RefVal V, ArgEffect E,
2366 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002367
2368 // In GC mode [... release] and [... retain] do nothing.
2369 switch (E) {
2370 default: break;
2371 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2372 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002373 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00002374 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2375 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002376 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002377
Ted Kremenek6537a642009-03-17 19:42:23 +00002378 // Handle all use-after-releases.
2379 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
2380 V = V ^ RefVal::ErrorUseAfterRelease;
2381 hasErr = V.getKind();
2382 return state.set<RefBindings>(sym, V);
2383 }
2384
Ted Kremenek0d721572008-03-11 17:48:22 +00002385 switch (E) {
2386 default:
2387 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00002388
2389 case Dealloc:
2390 // Any use of -dealloc in GC is *bad*.
2391 if (isGCEnabled()) {
2392 V = V ^ RefVal::ErrorDeallocGC;
2393 hasErr = V.getKind();
2394 break;
2395 }
2396
2397 switch (V.getKind()) {
2398 default:
2399 assert(false && "Invalid case.");
2400 case RefVal::Owned:
2401 // The object immediately transitions to the released state.
2402 V = V ^ RefVal::Released;
2403 V.clearCounts();
2404 return state.set<RefBindings>(sym, V);
2405 case RefVal::NotOwned:
2406 V = V ^ RefVal::ErrorDeallocNotOwned;
2407 hasErr = V.getKind();
2408 break;
2409 }
2410 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002411
Ted Kremenekb7826ab2009-02-25 23:11:49 +00002412 case NewAutoreleasePool:
2413 assert(!isGCEnabled());
2414 return state.add<AutoreleaseStack>(sym);
2415
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002416 case MayEscape:
2417 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002418 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002419 break;
2420 }
Ted Kremenek6537a642009-03-17 19:42:23 +00002421
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002422 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00002423
Ted Kremenekede40b72008-07-09 18:11:16 +00002424 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002425 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00002426 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002427
Ted Kremenek9b112d22009-01-28 21:44:40 +00002428 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00002429 if (isGCEnabled())
2430 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00002431
2432 // Update the autorelease counts.
2433 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00002434
2435 // Fall-through.
2436
Ted Kremenek227c5372008-05-06 02:41:27 +00002437 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00002438 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002439
Ted Kremenek0d721572008-03-11 17:48:22 +00002440 case IncRef:
2441 switch (V.getKind()) {
2442 default:
2443 assert(false);
2444
2445 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002446 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002447 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002448 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002449 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002450 // Non-GC cases are handled above.
2451 assert(isGCEnabled());
2452 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002453 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002454 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002455 break;
2456
Ted Kremenek272aa852008-06-25 21:21:56 +00002457 case SelfOwn:
2458 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002459 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002460 case DecRef:
2461 switch (V.getKind()) {
2462 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00002463 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00002464 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002465
Ted Kremenek272aa852008-06-25 21:21:56 +00002466 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002467 assert(V.getCount() > 0);
2468 if (V.getCount() == 1) V = V ^ RefVal::Released;
2469 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002470 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002471
Ted Kremenek272aa852008-06-25 21:21:56 +00002472 case RefVal::NotOwned:
2473 if (V.getCount() > 0)
2474 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002475 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002476 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002477 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002478 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002479 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00002480
Ted Kremenek0d721572008-03-11 17:48:22 +00002481 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002482 // Non-GC cases are handled above.
2483 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00002484 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002485 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00002486 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002487 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002488 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002489 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002490 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002491}
2492
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002493//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002494// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002495//===----------------------------------------------------------------------===//
2496
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002497namespace {
2498
2499 //===-------------===//
2500 // Bug Descriptions. //
2501 //===-------------===//
2502
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002503 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002504 protected:
2505 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002506
2507 CFRefBug(CFRefCount* tf, const char* name)
2508 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002509 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002510
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002511 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002512 const CFRefCount& getTF() const { return TF; }
2513
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002514 // FIXME: Eventually remove.
2515 virtual const char* getDescription() const = 0;
2516
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002517 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002518 };
2519
2520 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2521 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002522 UseAfterRelease(CFRefCount* tf)
Ted Kremenek5b1ab102009-04-03 21:10:31 +00002523 : CFRefBug(tf, "Use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002524
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002525 const char* getDescription() const {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002526 return "Reference-counted object is used after it is released";
Ted Kremenek708af042009-02-05 06:50:21 +00002527 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002528 };
2529
2530 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2531 public:
Ted Kremenekcce60492009-04-24 17:51:19 +00002532 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002533
2534 const char* getDescription() const {
Ted Kremeneke4158502009-04-23 19:11:35 +00002535 return "Incorrect decrement of the reference count of an "
2536 "object is not owned at this point by the caller";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002537 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002538 };
2539
Ted Kremenek6537a642009-03-17 19:42:23 +00002540 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2541 public:
2542 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
2543 "-dealloc called while using GC") {}
2544
2545 const char *getDescription() const {
2546 return "-dealloc called while using GC";
2547 }
2548 };
2549
2550 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2551 public:
2552 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
2553 "-dealloc sent to non-exclusively owned object") {}
2554
2555 const char *getDescription() const {
2556 return "-dealloc sent to object that may be referenced elsewhere";
2557 }
2558 };
2559
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002560 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002561 const bool isReturn;
2562 protected:
2563 Leak(CFRefCount* tf, const char* name, bool isRet)
2564 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002565 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002566
Ted Kremenek44274e62009-02-07 22:38:00 +00002567 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002568
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002569 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002570 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002571
2572 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2573 public:
2574 LeakAtReturn(CFRefCount* tf, const char* name)
2575 : Leak(tf, name, true) {}
2576 };
2577
2578 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2579 public:
2580 LeakWithinFunction(CFRefCount* tf, const char* name)
2581 : Leak(tf, name, false) {}
2582 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002583
2584 //===---------===//
2585 // Bug Reports. //
2586 //===---------===//
2587
2588 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002589 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002590 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002591 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002592 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002593 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2594 ExplodedNode<GRState> *n, SymbolRef sym)
2595 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002596
2597 virtual ~CFRefReport() {}
2598
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002599 CFRefBug& getBugType() {
2600 return (CFRefBug&) RangedBugReport::getBugType();
2601 }
2602 const CFRefBug& getBugType() const {
2603 return (const CFRefBug&) RangedBugReport::getBugType();
2604 }
2605
2606 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2607 const SourceRange*& end) {
2608
Ted Kremenek198cae02008-05-02 20:53:50 +00002609 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002610 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002611 else
2612 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002613 }
2614
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002615 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002616
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002617 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2618 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002619
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002620 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002621
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002622 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2623 const ExplodedNode<GRState>* PrevN,
2624 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002625 BugReporter& BR,
2626 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002627 };
2628
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002629 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002630 SourceLocation AllocSite;
2631 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002632 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002633 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2634 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002635 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002636
2637 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2638 const ExplodedNode<GRState>* N);
2639
Ted Kremenek86617f42009-02-07 22:19:59 +00002640 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002641 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002642} // end anonymous namespace
2643
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002644void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002645 useAfterRelease = new UseAfterRelease(this);
2646 BR.Register(useAfterRelease);
2647
2648 releaseNotOwned = new BadRelease(this);
2649 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002650
Ted Kremenek6537a642009-03-17 19:42:23 +00002651 deallocGC = new DeallocGC(this);
2652 BR.Register(deallocGC);
2653
2654 deallocNotOwned = new DeallocNotOwned(this);
2655 BR.Register(deallocNotOwned);
2656
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002657 // First register "return" leaks.
2658 const char* name = 0;
2659
2660 if (isGCEnabled())
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002661 name = "Leak of returned object when using garbage collection";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002662 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002663 name = "Leak of returned object when not using garbage collection (GC) in "
2664 "dual GC/non-GC code";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002665 else {
2666 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002667 name = "Leak of returned object";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002668 }
2669
Ted Kremenek708af042009-02-05 06:50:21 +00002670 leakAtReturn = new LeakAtReturn(this, name);
2671 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002672
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002673 // Second, register leaks within a function/method.
2674 if (isGCEnabled())
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002675 name = "Leak of object when using garbage collection";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002676 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002677 name = "Leak of object when not using garbage collection (GC) in "
2678 "dual GC/non-GC code";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002679 else {
2680 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002681 name = "Leak";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002682 }
2683
Ted Kremenek708af042009-02-05 06:50:21 +00002684 leakWithinFunction = new LeakWithinFunction(this, name);
2685 BR.Register(leakWithinFunction);
2686
2687 // Save the reference to the BugReporter.
2688 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002689}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002690
2691static const char* Msgs[] = {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002692 // GC only
2693 "Code is compiled to only use garbage collection",
2694 // No GC.
Ted Kremeneka9203882009-03-05 00:12:45 +00002695 "Code is compiled to use reference counts",
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002696 // Hybrid, with GC.
2697 "Code is compiled to use either garbage collection (GC) or reference counts"
2698 " (non-GC). The bug occurs with GC enabled",
2699 // Hybrid, without GC
2700 "Code is compiled to use either garbage collection (GC) or reference counts"
2701 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002702};
2703
2704std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2705 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2706
2707 switch (TF.getLangOptions().getGCMode()) {
2708 default:
2709 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002710
2711 case LangOptions::GCOnly:
2712 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002713 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2714
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002715 case LangOptions::NonGC:
2716 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002717 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2718
2719 case LangOptions::HybridGC:
2720 if (TF.isGCEnabled())
2721 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2722 else
2723 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2724 }
2725}
2726
Ted Kremenek2126bef2009-02-18 21:57:45 +00002727static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2728 ArgEffect X) {
2729 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2730 I!=E; ++I)
2731 if (*I == X) return true;
2732
2733 return false;
2734}
2735
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002736PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2737 const ExplodedNode<GRState>* PrevN,
2738 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002739 BugReporter& BR,
2740 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002741
Ted Kremenek71745d92009-01-28 05:29:13 +00002742 // Check if the type state has changed.
2743 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2744 GRStateRef PrevSt(PrevN->getState(), StMgr);
2745 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002746
Ted Kremenek71745d92009-01-28 05:29:13 +00002747 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2748 if (!CurrT) return NULL;
2749
2750 const RefVal& CurrV = *CurrT;
2751 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002752
Ted Kremenek2126bef2009-02-18 21:57:45 +00002753 // Create a string buffer to constain all the useful things we want
2754 // to tell the user.
2755 std::string sbuf;
2756 llvm::raw_string_ostream os(sbuf);
2757
Ted Kremenekc26c4692009-02-18 03:48:14 +00002758 // This is the allocation site since the previous node had no bindings
2759 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002760 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002761 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2762
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002763 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2764 // Get the name of the callee (if it is available).
Zhongxing Xucac107a2009-04-20 05:24:46 +00002765 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2766 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2767 os << "Call to function '" << FD->getNameAsString() <<'\'';
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002768 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002769 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002770 }
2771 else {
2772 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002773 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002774 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002775
Ted Kremenek18878b12009-01-28 06:06:36 +00002776 if (CurrV.getObjKind() == RetEffect::CF) {
2777 os << " returns a Core Foundation object with a ";
2778 }
2779 else {
2780 assert (CurrV.getObjKind() == RetEffect::ObjC);
2781 os << " returns an Objective-C object with a ";
2782 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002783
Ted Kremenekabe30922009-01-28 06:25:48 +00002784 if (CurrV.isOwned()) {
2785 os << "+1 retain count (owning reference).";
2786
2787 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2788 assert(CurrV.getObjKind() == RetEffect::CF);
2789 os << " "
2790 "Core Foundation objects are not automatically garbage collected.";
2791 }
2792 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002793 else {
2794 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002795 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002796 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002797
Ted Kremenek2fba6152009-04-01 06:13:56 +00002798 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2799 return new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002800 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002801
Ted Kremenek2126bef2009-02-18 21:57:45 +00002802 // Gather up the effects that were performed on the object at this
2803 // program point
2804 llvm::SmallVector<ArgEffect, 2> AEffects;
2805
Ted Kremenekc26c4692009-02-18 03:48:14 +00002806 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2807 // We only have summaries attached to nodes after evaluating CallExpr and
2808 // ObjCMessageExprs.
2809 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2810
Ted Kremenekc26c4692009-02-18 03:48:14 +00002811 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2812 // Iterate through the parameter expressions and see if the symbol
2813 // was ever passed as an argument.
2814 unsigned i = 0;
2815
2816 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2817 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002818
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002819 // Retrieve the value of the argument. Is it the symbol
2820 // we are interested in?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002821 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002822 continue;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002823
Ted Kremenekc26c4692009-02-18 03:48:14 +00002824 // We have an argument. Get the effect!
2825 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002826 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002827 }
2828 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002829 if (Expr *receiver = ME->getReceiver())
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002830 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002831 // The symbol we are tracking is the receiver.
2832 AEffects.push_back(Summ->getReceiverEffect());
2833 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002834 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002835 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002836
Ted Kremenek2126bef2009-02-18 21:57:45 +00002837 do {
2838 // Get the previous type state.
2839 RefVal PrevV = *PrevT;
Ted Kremenek6537a642009-03-17 19:42:23 +00002840
2841 // Specially handle -dealloc.
2842 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2843 // Determine if the object's reference count was pushed to zero.
2844 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2845 // We may not have transitioned to 'release' if we hit an error.
2846 // This case is handled elsewhere.
2847 if (CurrV.getKind() == RefVal::Released) {
2848 assert(CurrV.getCount() == 0);
2849 os << "Object released by directly sending the '-dealloc' message";
2850 break;
2851 }
2852 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002853
2854 // Specially handle CFMakeCollectable and friends.
2855 if (contains(AEffects, MakeCollectable)) {
2856 // Get the name of the function.
2857 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Zhongxing Xucac107a2009-04-20 05:24:46 +00002858 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2859 const FunctionDecl* FD = X.getAsFunctionDecl();
2860 const std::string& FName = FD->getNameAsString();
Ted Kremenek2126bef2009-02-18 21:57:45 +00002861
2862 if (TF.isGCEnabled()) {
2863 // Determine if the object's reference count was pushed to zero.
2864 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2865
2866 os << "In GC mode a call to '" << FName
2867 << "' decrements an object's retain count and registers the "
2868 "object with the garbage collector. ";
2869
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002870 if (CurrV.getKind() == RefVal::Released) {
2871 assert(CurrV.getCount() == 0);
2872 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002873 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002874 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002875 else
2876 os << "An object must have a 0 retain count to be garbage collected. "
2877 "After this call its retain count is +" << CurrV.getCount()
2878 << '.';
2879 }
2880 else
2881 os << "When GC is not enabled a call to '" << FName
2882 << "' has no effect on its argument.";
2883
2884 // Nothing more to say.
2885 break;
2886 }
2887
2888 // Determine if the typestate has changed.
2889 if (!(PrevV == CurrV))
2890 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002891 case RefVal::Owned:
2892 case RefVal::NotOwned:
2893
2894 if (PrevV.getCount() == CurrV.getCount())
2895 return 0;
2896
2897 if (PrevV.getCount() > CurrV.getCount())
2898 os << "Reference count decremented.";
2899 else
2900 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002901
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002902 if (unsigned Count = CurrV.getCount())
2903 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002904
2905 if (PrevV.getKind() == RefVal::Released) {
2906 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2907 os << " The object is not eligible for garbage collection until the "
2908 "retain count reaches 0 again.";
2909 }
2910
Ted Kremenekc26c4692009-02-18 03:48:14 +00002911 break;
2912
2913 case RefVal::Released:
2914 os << "Object released.";
2915 break;
2916
2917 case RefVal::ReturnedOwned:
2918 os << "Object returned to caller as an owning reference (single retain "
2919 "count transferred to caller).";
2920 break;
2921
2922 case RefVal::ReturnedNotOwned:
2923 os << "Object returned to caller with a +0 (non-owning) retain count.";
2924 break;
2925
2926 default:
2927 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002928 }
2929
2930 // Emit any remaining diagnostics for the argument effects (if any).
2931 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2932 E=AEffects.end(); I != E; ++I) {
2933
2934 // A bunch of things have alternate behavior under GC.
2935 if (TF.isGCEnabled())
2936 switch (*I) {
2937 default: break;
2938 case Autorelease:
2939 os << "In GC mode an 'autorelease' has no effect.";
2940 continue;
2941 case IncRefMsg:
2942 os << "In GC mode the 'retain' message has no effect.";
2943 continue;
2944 case DecRefMsg:
2945 os << "In GC mode the 'release' message has no effect.";
2946 continue;
2947 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002948 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002949 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002950
2951 if (os.str().empty())
2952 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002953
2954 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek2fba6152009-04-01 06:13:56 +00002955 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
Ted Kremenek23563642009-03-06 23:58:11 +00002956 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002957
2958 // Add the range by scanning the children of the statement for any bindings
2959 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002960 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002961 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002962 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002963 P->addRange(Exp->getSourceRange());
2964 break;
2965 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002966
2967 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002968}
2969
Ted Kremenekb15eba42008-10-04 05:50:14 +00002970namespace {
2971class VISIBILITY_HIDDEN FindUniqueBinding :
2972 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002973 SymbolRef Sym;
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002974 const MemRegion* Binding;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002975 bool First;
2976
2977 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002978 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002979
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002980 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2981 SVal val) {
Ted Kremenek74556a12009-03-26 03:35:11 +00002982
2983 SymbolRef SymV = val.getAsSymbol();
2984 if (!SymV || SymV != Sym)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002985 return true;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002986
Ted Kremenekb15eba42008-10-04 05:50:14 +00002987 if (Binding) {
2988 First = false;
2989 return false;
2990 }
2991 else
2992 Binding = R;
2993
2994 return true;
2995 }
2996
2997 operator bool() { return First && Binding; }
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002998 const MemRegion* getRegion() { return Binding; }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002999};
3000}
3001
Ted Kremenek3f6c6802009-01-24 00:55:43 +00003002static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00003003GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00003004 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00003005
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00003006 // Find both first node that referred to the tracked symbol and the
3007 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00003008 const ExplodedNode<GRState>* Last = N;
3009 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00003010
3011 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003012 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003013 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00003014
Ted Kremenek6064a362008-07-07 16:21:19 +00003015 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00003016 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00003017
Ted Kremenek86617f42009-02-07 22:19:59 +00003018 FindUniqueBinding FB(Sym);
3019 StateMgr.iterBindings(St, FB);
3020 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00003021
Ted Kremenekd7e26782008-05-16 18:33:44 +00003022 Last = N;
3023 N = N->pred_empty() ? NULL : *(N->pred_begin());
3024 }
3025
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00003026 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00003027}
Ted Kremenek4c479322008-05-06 23:07:13 +00003028
Ted Kremenek3f6c6802009-01-24 00:55:43 +00003029PathDiagnosticPiece*
3030CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00003031 // Tell the BugReporter to report cases when the tracked symbol is
3032 // assigned to different variables, etc.
Ted Kremenek6537a642009-03-17 19:42:23 +00003033 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00003034 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00003035 return RangedBugReport::getEndPath(BR, EndN);
3036}
3037
3038PathDiagnosticPiece*
3039CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
3040
3041 GRBugReporter& BR = cast<GRBugReporter>(br);
3042 // Tell the BugReporter to report cases when the tracked symbol is
3043 // assigned to different variables, etc.
3044 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
3045
3046 // We are reporting a leak. Walk up the graph to get to the first node where
3047 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00003048 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00003049 const ExplodedNode<GRState>* AllocNode = 0;
3050 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00003051
3052 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00003053 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003054
Ted Kremenekd7e26782008-05-16 18:33:44 +00003055 // Get the allocate site.
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003056 assert(AllocNode);
Ted Kremenekd7e26782008-05-16 18:33:44 +00003057 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003058
Ted Kremenekea794e92008-05-05 18:50:19 +00003059 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00003060 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003061
Ted Kremenek505dc672009-04-07 04:54:20 +00003062 // Compute an actual location for the leak. Sometimes a leak doesn't
3063 // occur at an actual statement (e.g., transition between blocks; end
3064 // of function) so we need to walk the graph and compute a real location.
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003065 const ExplodedNode<GRState>* LeakN = EndN;
3066 PathDiagnosticLocation L;
3067
3068 while (LeakN) {
3069 ProgramPoint P = LeakN->getLocation();
3070
3071 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
3072 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
3073 break;
3074 }
3075 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
3076 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
3077 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
3078 break;
3079 }
3080 }
3081
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003082 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
3083 }
Sebastian Redlbc9ef252009-04-26 20:35:05 +00003084
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003085 if (!L.isValid()) {
Sebastian Redlbc9ef252009-04-26 20:35:05 +00003086 L = PathDiagnosticLocation(
3087 BR.getStateManager().getCodeDecl().getBodyRBrace(BR.getContext()),
3088 SMgr);
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003089 }
3090
Ted Kremenek59f9fe12009-02-07 21:59:45 +00003091 std::string sbuf;
3092 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00003093
Ted Kremenekea794e92008-05-05 18:50:19 +00003094 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00003095
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00003096 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00003097 os << " and stored into '" << FirstBinding->getString() << '\'';
3098
Ted Kremenek311f3d42008-10-22 23:56:21 +00003099 // Get the retain count.
3100 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
3101
3102 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00003103 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
3104 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
3105 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00003106 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
3107 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00003108 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00003109 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00003110 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00003111 " in the Memory Management Guide for Cocoa (object leaked).";
3112 }
3113 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00003114 os << " is no longer referenced after this point and has a retain count of"
3115 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00003116 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003117
Ted Kremenek23563642009-03-06 23:58:11 +00003118 return new PathDiagnosticEventPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003119}
3120
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00003121
Ted Kremenekc26c4692009-02-18 03:48:14 +00003122CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
3123 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00003124 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00003125 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00003126{
3127
Ted Kremenekd7e26782008-05-16 18:33:44 +00003128 // Most bug reports are cached at the location where they occured.
3129 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00003130 // allocated, and only report a single path. To do this, we need to find
3131 // the allocation site of a piece of tracked memory, which we do via a
3132 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
3133 // Note that this is *not* the trimmed graph; we are guaranteed, however,
3134 // that all ancestor nodes that represent the allocation site have the
3135 // same SourceLocation.
3136 const ExplodedNode<GRState>* AllocNode = 0;
3137
3138 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00003139 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00003140
Ted Kremenek86617f42009-02-07 22:19:59 +00003141 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00003142 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00003143 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00003144
3145 // Fill in the description of the bug.
3146 Description.clear();
3147 llvm::raw_string_ostream os(Description);
3148 SourceManager& SMgr = Eng.getContext().getSourceManager();
3149 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00003150 os << "Potential leak of object allocated on line " << AllocLine;
3151
3152 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
3153 if (AllocBinding)
Ted Kremenek5ee01662009-04-02 03:42:38 +00003154 os << " and stored into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00003155}
3156
Ted Kremeneka7338b42008-03-11 06:39:11 +00003157//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003158// Handle dead symbols and end-of-path.
3159//===----------------------------------------------------------------------===//
3160
3161void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3162 GREndPathNodeBuilder<GRState>& Builder) {
3163
3164 const GRState* St = Builder.getState();
3165 RefBindings B = St->get<RefBindings>();
3166
3167 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3168 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3169
3170 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3171 bool hasLeak = false;
3172
3173 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003174 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3175 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003176
3177 St = X.first;
3178 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3179 }
3180
3181 if (Leaked.empty())
3182 return;
3183
3184 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3185
3186 if (!N)
3187 return;
3188
3189 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3190 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3191
3192 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3193 : leakWithinFunction);
3194 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003195 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003196 BR->EmitReport(report);
3197 }
3198}
3199
3200void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3201 GRExprEngine& Eng,
3202 GRStmtNodeBuilder<GRState>& Builder,
3203 ExplodedNode<GRState>* Pred,
3204 Stmt* S,
3205 const GRState* St,
3206 SymbolReaper& SymReaper) {
3207
Ted Kremenek876d8df2009-02-19 23:47:02 +00003208 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003209 RefBindings B = St->get<RefBindings>();
3210 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3211
3212 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3213 E = SymReaper.dead_end(); I != E; ++I) {
3214
3215 const RefVal* T = B.lookup(*I);
3216 if (!T) continue;
3217
3218 bool hasLeak = false;
3219
3220 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003221 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003222
3223 St = X.first;
3224
3225 if (hasLeak)
3226 Leaked.push_back(std::make_pair(*I,X.second));
3227 }
3228
Ted Kremenek876d8df2009-02-19 23:47:02 +00003229 if (!Leaked.empty()) {
3230 // Create a new intermediate node representing the leak point. We
3231 // use a special program point that represents this checker-specific
3232 // transition. We use the address of RefBIndex as a unique tag for this
3233 // checker. We will create another node (if we don't cache out) that
3234 // removes the retain-count bindings from the state.
3235 // NOTE: We use 'generateNode' so that it does interplay with the
3236 // auto-transition logic.
3237 ExplodedNode<GRState>* N =
3238 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003239
Ted Kremenek876d8df2009-02-19 23:47:02 +00003240 if (!N)
3241 return;
3242
3243 // Generate the bug reports.
3244 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3245 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3246
3247 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3248 : leakWithinFunction);
3249 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003250 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3251 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003252 BR->EmitReport(report);
3253 }
Ted Kremenek708af042009-02-05 06:50:21 +00003254
Ted Kremenek876d8df2009-02-19 23:47:02 +00003255 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003256 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003257
3258 // Now generate a new node that nukes the old bindings.
3259 GRStateRef state(St, Eng.getStateManager());
3260 RefBindings::Factory& F = state.get_context<RefBindings>();
3261
3262 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3263 E = SymReaper.dead_end(); I!=E; ++I)
3264 B = F.Remove(B, *I);
3265
3266 state = state.set<RefBindings>(B);
3267 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003268}
3269
3270void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3271 GRStmtNodeBuilder<GRState>& Builder,
3272 Expr* NodeExpr, Expr* ErrorExpr,
3273 ExplodedNode<GRState>* Pred,
3274 const GRState* St,
3275 RefVal::Kind hasErr, SymbolRef Sym) {
3276 Builder.BuildSinks = true;
3277 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3278
3279 if (!N) return;
3280
3281 CFRefBug *BT = 0;
3282
Ted Kremenek6537a642009-03-17 19:42:23 +00003283 switch (hasErr) {
3284 default:
3285 assert(false && "Unhandled error.");
3286 return;
3287 case RefVal::ErrorUseAfterRelease:
3288 BT = static_cast<CFRefBug*>(useAfterRelease);
3289 break;
3290 case RefVal::ErrorReleaseNotOwned:
3291 BT = static_cast<CFRefBug*>(releaseNotOwned);
3292 break;
3293 case RefVal::ErrorDeallocGC:
3294 BT = static_cast<CFRefBug*>(deallocGC);
3295 break;
3296 case RefVal::ErrorDeallocNotOwned:
3297 BT = static_cast<CFRefBug*>(deallocNotOwned);
3298 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003299 }
3300
Ted Kremenekc26c4692009-02-18 03:48:14 +00003301 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003302 report->addRange(ErrorExpr->getSourceRange());
3303 BR->EmitReport(report);
3304}
3305
3306//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003307// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003308//===----------------------------------------------------------------------===//
3309
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003310GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3311 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003312 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003313}