blob: 2d154759b252bb1bc1f98fb9a861c48c64fe2865 [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"
Ted Kremenekc3bc6c82009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
Ted Kremenek314b1952009-04-29 23:03:22 +0000152static const ObjCMethodDecl*
153ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
154 ObjCInterfaceDecl *ID =
155 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
156
157 return MD->isInstanceMethod()
158 ? ID->lookupInstanceMethod(Context, MD->getSelector())
159 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000160}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000161
Ted Kremenek7d421f32008-04-09 23:49:11 +0000162//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000163// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000164//===----------------------------------------------------------------------===//
165
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000166static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(0, &II);
169}
170
Ted Kremenek0e344d42008-05-06 00:30:21 +0000171static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
172 IdentifierInfo* II = &Ctx.Idents.get(name);
173 return Ctx.Selectors.getSelector(1, &II);
174}
175
Ted Kremenek272aa852008-06-25 21:21:56 +0000176//===----------------------------------------------------------------------===//
177// Type querying functions.
178//===----------------------------------------------------------------------===//
179
Ted Kremenek17144e82009-01-12 21:45:02 +0000180static bool hasPrefix(const char* s, const char* prefix) {
181 if (!prefix)
182 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000183
Ted Kremenek17144e82009-01-12 21:45:02 +0000184 char c = *s;
185 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000186
Ted Kremenek17144e82009-01-12 21:45:02 +0000187 while (c != '\0' && cP != '\0') {
188 if (c != cP) break;
189 c = *(++s);
190 cP = *(++prefix);
191 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000192
Ted Kremenek17144e82009-01-12 21:45:02 +0000193 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000194}
195
Ted Kremenek17144e82009-01-12 21:45:02 +0000196static bool hasSuffix(const char* s, const char* suffix) {
197 const char* loc = strstr(s, suffix);
198 return loc && strcmp(suffix, loc) == 0;
199}
200
201static bool isRefType(QualType RetTy, const char* prefix,
202 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
205 const char* TDName = TD->getDecl()->getIdentifier()->getName();
206 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
207 }
208
209 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Is the type void*?
213 const PointerType* PT = RetTy->getAsPointerType();
214 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000215 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000216
217 // Does the name start with the prefix?
218 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000219}
220
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000221//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000222// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000223//===----------------------------------------------------------------------===//
224
Ted Kremenek272aa852008-06-25 21:21:56 +0000225/// ArgEffect is used to summarize a function/method call's effect on a
226/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000227enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
228 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
229 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000230
Ted Kremeneka7338b42008-03-11 06:39:11 +0000231namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000232template <> struct FoldingSetTrait<ArgEffect> {
233static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
234 ID.AddInteger((unsigned) X);
235}
Ted Kremenek272aa852008-06-25 21:21:56 +0000236};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000237} // end llvm namespace
238
Ted Kremeneka56ae162009-05-03 05:20:50 +0000239/// ArgEffects summarizes the effects of a function/method call on all of
240/// its arguments.
241typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
242
Ted Kremeneka7338b42008-03-11 06:39:11 +0000243namespace {
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 Kremenek314b1952009-04-29 23:03:22 +0000272 bool isOwned() const {
273 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
274 }
275
Ted Kremenek272aa852008-06-25 21:21:56 +0000276 static RetEffect MakeAlias(unsigned Idx) {
277 return RetEffect(Alias, Idx);
278 }
279 static RetEffect MakeReceiverAlias() {
280 return RetEffect(ReceiverAlias);
281 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000282 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
283 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000284 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000285 static RetEffect MakeNotOwned(ObjKind o) {
286 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000287 }
288 static RetEffect MakeGCNotOwned() {
289 return RetEffect(GCNotOwnedSymbol, ObjC);
290 }
291
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 static RetEffect MakeNoRet() {
293 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000294 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000295
Ted Kremenek272aa852008-06-25 21:21:56 +0000296 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000297 ID.AddInteger((unsigned)K);
298 ID.AddInteger((unsigned)O);
299 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000300 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000301};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000302
Ted Kremenek272aa852008-06-25 21:21:56 +0000303
Ted Kremenek2f226732009-05-04 05:31:22 +0000304class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000305 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
306 /// specifies the argument (starting from 0). This can be sparsely
307 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000308 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000309
310 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
311 /// do not have an entry in Args.
312 ArgEffect DefaultArgEffect;
313
Ted Kremenek272aa852008-06-25 21:21:56 +0000314 /// Receiver - If this summary applies to an Objective-C message expression,
315 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000316 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000317
318 /// Ret - The effect on the return value. Used to indicate if the
319 /// function/method call returns a new tracked symbol, returns an
320 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000321 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000322
Ted Kremenekf2717b02008-07-18 17:24:20 +0000323 /// EndPath - Indicates that execution of this method/function should
324 /// terminate the simulation of a path.
325 bool EndPath;
326
Ted Kremeneka7338b42008-03-11 06:39:11 +0000327public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000328 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000329 ArgEffect ReceiverEff, bool endpath = false)
330 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
331 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000332
Ted Kremenek272aa852008-06-25 21:21:56 +0000333 /// getArg - Return the argument effect on the argument specified by
334 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000335 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000336 if (const ArgEffect *AE = Args.lookup(idx))
337 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000338
Ted Kremenekbcaff792008-05-06 15:44:25 +0000339 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000340 }
341
Ted Kremenek2f226732009-05-04 05:31:22 +0000342 /// setDefaultArgEffect - Set the default argument effect.
343 void setDefaultArgEffect(ArgEffect E) {
344 DefaultArgEffect = E;
345 }
346
347 /// setArg - Set the argument effect on the argument specified by idx.
348 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
349 Args = AF.Add(Args, idx, E);
350 }
351
Ted Kremenek272aa852008-06-25 21:21:56 +0000352 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000354
Ted Kremenek2f226732009-05-04 05:31:22 +0000355 /// setRetEffect - Set the effect of the return value of the call.
356 void setRetEffect(RetEffect E) { Ret = E; }
357
Ted Kremenekf2717b02008-07-18 17:24:20 +0000358 /// isEndPath - Returns true if executing the given method/function should
359 /// terminate the path.
360 bool isEndPath() const { return EndPath; }
361
Ted Kremenek272aa852008-06-25 21:21:56 +0000362 /// getReceiverEffect - Returns the effect on the receiver of the call.
363 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000364 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000365
Ted Kremenek2f226732009-05-04 05:31:22 +0000366 /// setReceiverEffect - Set the effect on the receiver of the call.
367 void setReceiverEffect(ArgEffect E) { Receiver = E; }
368
Ted Kremeneka56ae162009-05-03 05:20:50 +0000369 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370
Ted Kremeneka56ae162009-05-03 05:20:50 +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 Kremeneka56ae162009-05-03 05:20:50 +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 Kremeneka56ae162009-05-03 05:20:50 +0000377 ID.Add(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
Ted Kremenek314b1952009-04-29 23:03:22 +0000402 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000403 : 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
Ted Kremenek314b1952009-04-29 23:03:22 +0000455 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
456 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000457 // Lookup the method using the decl for the class @interface. If we
458 // have no decl, lookup using the class name.
459 return D ? find(D, S) : find(ClsName, S);
460 }
461
Ted Kremenek314b1952009-04-29 23:03:22 +0000462 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000463 // Do a lookup with the (D,S) pair. If we find a match return
464 // the iterator.
465 ObjCSummaryKey K(D, S);
466 MapTy::iterator I = M.find(K);
467
468 if (I != M.end() || !D)
469 return I;
470
471 // Walk the super chain. If we find a hit with a parent, we'll end
472 // up returning that summary. We actually allow that key (null,S), as
473 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
474 // generate initial summaries without having to worry about NSObject
475 // being declared.
476 // FIXME: We may change this at some point.
477 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
478 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
479 break;
480
481 if (!C)
482 return I;
483 }
484
485 // Cache the summary with original key to make the next lookup faster
486 // and return the iterator.
487 M[K] = I->second;
488 return I;
489 }
490
Ted Kremenek9449ca92008-08-12 20:41:56 +0000491
Ted Kremenek272aa852008-06-25 21:21:56 +0000492 iterator find(Expr* Receiver, Selector S) {
493 return find(getReceiverDecl(Receiver), S);
494 }
495
496 iterator find(IdentifierInfo* II, Selector S) {
497 // FIXME: Class method lookup. Right now we dont' have a good way
498 // of going between IdentifierInfo* and the class hierarchy.
499 iterator I = M.find(ObjCSummaryKey(II, S));
500 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
501 }
502
503 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
504
505 const PointerType* PT = E->getType()->getAsPointerType();
506 if (!PT) return 0;
507
508 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
509 if (!OI) return 0;
510
511 return OI ? OI->getDecl() : 0;
512 }
513
514 iterator end() { return M.end(); }
515
516 RetainSummary*& operator[](ObjCMessageExpr* ME) {
517
518 Selector S = ME->getSelector();
519
520 if (Expr* Receiver = ME->getReceiver()) {
521 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
522 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
523 }
524
525 return M[ObjCSummaryKey(ME->getClassName(), S)];
526 }
527
528 RetainSummary*& operator[](ObjCSummaryKey K) {
529 return M[K];
530 }
531
532 RetainSummary*& operator[](Selector S) {
533 return M[ ObjCSummaryKey(S) ];
534 }
535};
536} // end anonymous namespace
537
538//===----------------------------------------------------------------------===//
539// Data structures for managing collections of summaries.
540//===----------------------------------------------------------------------===//
541
542namespace {
543class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000544
545 //==-----------------------------------------------------------------==//
546 // Typedefs.
547 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000548
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000549 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;
Ted Kremenekee649082009-05-04 04:30:18 +0000567
Ted Kremenek272aa852008-06-25 21:21:56 +0000568 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000569 FuncSummariesTy FuncSummaries;
570
Ted Kremenek272aa852008-06-25 21:21:56 +0000571 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
572 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000573 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000574
Ted Kremenek272aa852008-06-25 21:21:56 +0000575 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000576 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000577
Ted Kremenek272aa852008-06-25 21:21:56 +0000578 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
579 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000580 llvm::BumpPtrAllocator BPAlloc;
581
Ted Kremeneka56ae162009-05-03 05:20:50 +0000582 /// AF - A factory for ArgEffects objects.
583 ArgEffects::Factory AF;
584
Ted Kremenek272aa852008-06-25 21:21:56 +0000585 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000586 ArgEffects ScratchArgs;
587
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000588 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
589 /// objects.
590 RetEffect ObjCAllocRetE;
591
Ted Kremenek286e9852009-05-04 04:57:00 +0000592 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000593 RetainSummary* StopSummary;
594
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000595 //==-----------------------------------------------------------------==//
596 // Methods.
597 //==-----------------------------------------------------------------==//
598
Ted Kremenek272aa852008-06-25 21:21:56 +0000599 /// getArgEffects - Returns a persistent ArgEffects object based on the
600 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000601 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000602
Ted Kremenek562c1302008-05-05 16:51:50 +0000603 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000604
605public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000606 RetainSummary *getDefaultSummary() {
607 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
608 return new (Summ) RetainSummary(DefaultSummary);
609 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000610
Ted Kremenek064ef322009-02-23 16:51:39 +0000611 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000612
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000613 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
614 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000615 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000616
Ted Kremeneka56ae162009-05-03 05:20:50 +0000617 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000618 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000619 ArgEffect DefaultEff = MayEscape,
620 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000621
Ted Kremenek266d8b62008-05-06 02:26:56 +0000622 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000623 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000624 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000625 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000626 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000627
Ted Kremeneka821b792009-04-29 05:04:30 +0000628 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000629 if (StopSummary)
630 return StopSummary;
631
632 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
633 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000634
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000635 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000636 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000637
Ted Kremeneka821b792009-04-29 05:04:30 +0000638 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000639
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000640 void InitializeClassMethodSummaries();
641 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000642
Ted Kremenek9b42e062009-05-03 04:42:10 +0000643 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000644 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000645
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000646private:
647
Ted Kremenekf2717b02008-07-18 17:24:20 +0000648 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
649 RetainSummary* Summ) {
650 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
651 }
652
Ted Kremenek272aa852008-06-25 21:21:56 +0000653 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
654 ObjCClassMethodSummaries[S] = Summ;
655 }
656
657 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
658 ObjCMethodSummaries[S] = Summ;
659 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000660
661 void addClassMethSummary(const char* Cls, const char* nullaryName,
662 RetainSummary *Summ) {
663 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
664 Selector S = GetNullarySelector(nullaryName, Ctx);
665 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
666 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000667
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000668 void addInstMethSummary(const char* Cls, const char* nullaryName,
669 RetainSummary *Summ) {
670 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
671 Selector S = GetNullarySelector(nullaryName, Ctx);
672 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
673 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000674
675 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000676 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000677
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000678 while (const char* s = va_arg(argp, const char*))
679 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000680
681 return Ctx.Selectors.getSelector(II.size(), &II[0]);
682 }
683
684 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
685 RetainSummary* Summ, va_list argp) {
686 Selector S = generateSelector(argp);
687 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000688 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000689
690 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
691 va_list argp;
692 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000693 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000694 va_end(argp);
695 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000696
697 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
698 va_list argp;
699 va_start(argp, Summ);
700 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
701 va_end(argp);
702 }
703
704 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
705 va_list argp;
706 va_start(argp, Summ);
707 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
708 va_end(argp);
709 }
710
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000711 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000712 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
713 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000714 DoNothing, DoNothing, true);
715 va_list argp;
716 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000717 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000718 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000719 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000720
Ted Kremeneka7338b42008-03-11 06:39:11 +0000721public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000722
723 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000724 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000725 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000726 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000727 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
728 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000729 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
730 RetEffect::MakeNoRet() /* return effect */,
731 DoNothing /* receiver effect */,
732 MayEscape /* default argument effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000733 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000734
735 InitializeClassMethodSummaries();
736 InitializeMethodSummaries();
737 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000738
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000739 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000740
Ted Kremenekd13c1872008-06-24 03:56:45 +0000741 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000742
Ted Kremenek314b1952009-04-29 23:03:22 +0000743 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
744 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000745 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000746 ID, ME->getMethodDecl(), ME->getType());
747 }
748
Ted Kremenek04e00302009-04-29 17:09:14 +0000749 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000750 const ObjCInterfaceDecl* ID,
751 const ObjCMethodDecl *MD,
752 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000753
754 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000755 const ObjCInterfaceDecl *ID,
756 const ObjCMethodDecl *MD,
757 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000758
759 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
760 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
761 ME->getClassInfo().first,
762 ME->getMethodDecl(), ME->getType());
763 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000764
765 /// getMethodSummary - This version of getMethodSummary is used to query
766 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000767 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
768 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000769 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000770 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000771 IdentifierInfo *ClsName = ID->getIdentifier();
772 QualType ResultTy = MD->getResultType();
773
Ted Kremenek81eb4642009-04-30 05:47:23 +0000774 // Resolve the method decl last.
775 if (const ObjCMethodDecl *InterfaceMD =
776 ResolveToInterfaceMethodDecl(MD, Ctx))
777 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000778
Ted Kremenek91b89a42009-04-29 17:17:48 +0000779 if (MD->isInstanceMethod())
780 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
781 else
782 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
783 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000784
Ted Kremenek314b1952009-04-29 23:03:22 +0000785 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
786 Selector S, QualType RetTy);
787
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000788 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000789
790 RetainSummary *copySummary(RetainSummary *OldSumm) {
791 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
792 new (Summ) RetainSummary(*OldSumm);
793 return Summ;
794 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000795};
796
797} // end anonymous namespace
798
799//===----------------------------------------------------------------------===//
800// Implementation of checker data structures.
801//===----------------------------------------------------------------------===//
802
Ted Kremeneka56ae162009-05-03 05:20:50 +0000803RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000804
Ted Kremeneka56ae162009-05-03 05:20:50 +0000805ArgEffects RetainSummaryManager::getArgEffects() {
806 ArgEffects AE = ScratchArgs;
807 ScratchArgs = AF.GetEmptyMap();
808 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000809}
810
Ted Kremenek266d8b62008-05-06 02:26:56 +0000811RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000812RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000813 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000814 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000815 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000816 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000817 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000818 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000819 return Summ;
820}
821
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000822//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000823// Predicates.
824//===----------------------------------------------------------------------===//
825
Ted Kremenek9b42e062009-05-03 04:42:10 +0000826bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000827 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000828 return false;
829
Ted Kremenek0d813552009-04-23 22:11:07 +0000830 // We assume that id<..>, id, and "Class" all represent tracked objects.
831 const PointerType *PT = Ty->getAsPointerType();
832 if (PT == 0)
833 return true;
834
835 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000836
837 // We assume that id<..>, id, and "Class" all represent tracked objects.
838 if (!OT)
839 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000840
841 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000842 // FIXME: We can memoize here if this gets too expensive.
843 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
844 ObjCInterfaceDecl* ID = OT->getDecl();
845
846 for ( ; ID ; ID = ID->getSuperClass())
847 if (ID->getIdentifier() == NSObjectII)
848 return true;
849
850 return false;
851}
852
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000853bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
854 return isRefType(T, "CF") || // Core Foundation.
855 isRefType(T, "CG") || // Core Graphics.
856 isRefType(T, "DADisk") || // Disk Arbitration API.
857 isRefType(T, "DADissenter") ||
858 isRefType(T, "DASessionRef");
859}
860
Ted Kremenek35920ed2009-01-07 00:39:56 +0000861//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000862// Summary creation for functions (largely uses of Core Foundation).
863//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000864
Ted Kremenek17144e82009-01-12 21:45:02 +0000865static bool isRetain(FunctionDecl* FD, const char* FName) {
866 const char* loc = strstr(FName, "Retain");
867 return loc && loc[sizeof("Retain")-1] == '\0';
868}
869
870static bool isRelease(FunctionDecl* FD, const char* FName) {
871 const char* loc = strstr(FName, "Release");
872 return loc && loc[sizeof("Release")-1] == '\0';
873}
874
Ted Kremenekd13c1872008-06-24 03:56:45 +0000875RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000876 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000877 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000878 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000879 return I->second;
880
Ted Kremenek64cddf12009-05-04 15:34:07 +0000881 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000882 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000883
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000884 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000885 // We generate "stop" summaries for implicitly defined functions.
886 if (FD->isImplicit()) {
887 S = getPersistentStopSummary();
888 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000889 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000890
Ted Kremenek064ef322009-02-23 16:51:39 +0000891 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000892 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000893 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000894 const char* FName = FD->getIdentifier()->getName();
895
Ted Kremenek38c6f022009-03-05 22:11:14 +0000896 // Strip away preceding '_'. Doing this here will effect all the checks
897 // down below.
898 while (*FName == '_') ++FName;
899
Ted Kremenek17144e82009-01-12 21:45:02 +0000900 // Inspect the result type.
901 QualType RetTy = FT->getResultType();
902
903 // FIXME: This should all be refactored into a chain of "summary lookup"
904 // filters.
905 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
906 // FIXES: <rdar://problem/6326900>
907 // This should be addressed using a API table. This strcmp is also
908 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000909 assert (ScratchArgs.isEmpty());
910 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000911 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
912 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000913 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000914
915 // Enable this code once the semantics of NSDeallocateObject are resolved
916 // for GC. <rdar://problem/6619988>
917#if 0
918 // Handle: NSDeallocateObject(id anObject);
919 // This method does allow 'nil' (although we don't check it now).
920 if (strcmp(FName, "NSDeallocateObject") == 0) {
921 return RetTy == Ctx.VoidTy
922 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
923 : getPersistentStopSummary();
924 }
925#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000926
927 // Handle: id NSMakeCollectable(CFTypeRef)
928 if (strcmp(FName, "NSMakeCollectable") == 0) {
929 S = (RetTy == Ctx.getObjCIdType())
930 ? getUnarySummary(FT, cfmakecollectable)
931 : getPersistentStopSummary();
932
933 break;
934 }
935
936 if (RetTy->isPointerType()) {
937 // For CoreFoundation ('CF') types.
938 if (isRefType(RetTy, "CF", &Ctx, FName)) {
939 if (isRetain(FD, FName))
940 S = getUnarySummary(FT, cfretain);
941 else if (strstr(FName, "MakeCollectable"))
942 S = getUnarySummary(FT, cfmakecollectable);
943 else
944 S = getCFCreateGetRuleSummary(FD, FName);
945
946 break;
947 }
948
949 // For CoreGraphics ('CG') types.
950 if (isRefType(RetTy, "CG", &Ctx, FName)) {
951 if (isRetain(FD, FName))
952 S = getUnarySummary(FT, cfretain);
953 else
954 S = getCFCreateGetRuleSummary(FD, FName);
955
956 break;
957 }
958
959 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
960 if (isRefType(RetTy, "DADisk") ||
961 isRefType(RetTy, "DADissenter") ||
962 isRefType(RetTy, "DASessionRef")) {
963 S = getCFCreateGetRuleSummary(FD, FName);
964 break;
965 }
966
967 break;
968 }
969
970 // Check for release functions, the only kind of functions that we care
971 // about that don't return a pointer type.
972 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000973 // Test for 'CGCF'.
974 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
975 FName += 4;
976 else
977 FName += 2;
978
979 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000980 S = getUnarySummary(FT, cfrelease);
981 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000982 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +0000983 // Remaining CoreFoundation and CoreGraphics functions.
984 // We use to assume that they all strictly followed the ownership idiom
985 // and that ownership cannot be transferred. While this is technically
986 // correct, many methods allow a tracked object to escape. For example:
987 //
988 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
989 // CFDictionaryAddValue(y, key, x);
990 // CFRelease(x);
991 // ... it is okay to use 'x' since 'y' has a reference to it
992 //
993 // We handle this and similar cases with the follow heuristic. If the
994 // function name contains "InsertValue", "SetValue" or "AddValue" then
995 // we assume that arguments may "escape."
996 //
997 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
998 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000999 CStrInCStrNoCase(FName, "SetValue") ||
1000 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001001 ? MayEscape : DoNothing;
1002
1003 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001004 }
1005 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001006 }
1007 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001008
1009 if (!S)
1010 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001011
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001012 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001013 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001014}
1015
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001016RetainSummary*
1017RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1018 const char* FName) {
1019
Ted Kremenek562c1302008-05-05 16:51:50 +00001020 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1021 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001022
Ted Kremenek562c1302008-05-05 16:51:50 +00001023 if (strstr(FName, "Get"))
1024 return getCFSummaryGetRule(FD);
1025
Ted Kremenek286e9852009-05-04 04:57:00 +00001026 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001027}
1028
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001029RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001030RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1031 UnaryFuncKind func) {
1032
Ted Kremenek17144e82009-01-12 21:45:02 +00001033 // Sanity check that this is *really* a unary function. This can
1034 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001035 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001036 if (!FTP || FTP->getNumArgs() != 1)
1037 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001038
Ted Kremeneka56ae162009-05-03 05:20:50 +00001039 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001040
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001041 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001042 case cfretain: {
1043 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001044 return getPersistentSummary(RetEffect::MakeAlias(0),
1045 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001046 }
1047
1048 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001049 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001050 return getPersistentSummary(RetEffect::MakeNoRet(),
1051 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001052 }
1053
1054 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001055 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001056 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001057 }
1058
1059 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001060 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001061 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001062 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001063}
1064
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001065RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001066 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001067
1068 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001069 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1070 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001071 }
1072
Ted Kremenek68621b92009-01-28 05:56:51 +00001073 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001074}
1075
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001076RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001077 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001078 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1079 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001080}
1081
Ted Kremeneka7338b42008-03-11 06:39:11 +00001082//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001083// Summary creation for Selectors.
1084//===----------------------------------------------------------------------===//
1085
Ted Kremenekbcaff792008-05-06 15:44:25 +00001086RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001087RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001088 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001089
Ted Kremenek802cfc72009-02-20 00:05:35 +00001090 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001091 return getPersistentSummary(Loc::IsLocType(RetTy)
1092 ? RetEffect::MakeReceiverAlias()
Ted Kremenek03d242e2009-05-05 18:44:20 +00001093 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001094}
Ted Kremenek03d242e2009-05-05 18:44:20 +00001095
Ted Kremenekbcaff792008-05-06 15:44:25 +00001096RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001097RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1098 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001099
Ted Kremenek578498a2009-04-29 00:42:39 +00001100 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001101 // Scan the method decl for 'void*' arguments. These should be treated
1102 // as 'StopTracking' because they are often used with delegates.
1103 // Delegates are a frequent form of false positives with the retain
1104 // count checker.
1105 unsigned i = 0;
1106 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1107 E = MD->param_end(); I != E; ++I, ++i)
1108 if (ParmVarDecl *PD = *I) {
1109 QualType Ty = Ctx.getCanonicalType(PD->getType());
1110 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001111 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001112 }
1113 }
1114
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001115 // Any special effect for the receiver?
1116 ArgEffect ReceiverEff = DoNothing;
1117
1118 // If one of the arguments in the selector has the keyword 'delegate' we
1119 // should stop tracking the reference count for the receiver. This is
1120 // because the reference count is quite possibly handled by a delegate
1121 // method.
1122 if (S.isKeywordSelector()) {
1123 const std::string &str = S.getAsString();
1124 assert(!str.empty());
1125 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1126 }
1127
Ted Kremenek174a0772009-04-23 23:08:22 +00001128 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001129 if (isTrackedObjCObjectType(RetTy)) {
1130 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1131 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001132 RetEffect E =
1133 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001134 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001135
1136 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001137 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001138
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001139 // Look for methods that return an owned core foundation object.
1140 if (isTrackedCFObjectType(RetTy)) {
1141 RetEffect E =
1142 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1143 ? RetEffect::MakeOwned(RetEffect::CF, true)
1144 : RetEffect::MakeNotOwned(RetEffect::CF);
1145
1146 return getPersistentSummary(E, ReceiverEff, MayEscape);
1147 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001148
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001149 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001150 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001151
Ted Kremenek2f226732009-05-04 05:31:22 +00001152 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001153}
1154
1155RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001156RetainSummaryManager::getInstanceMethodSummary(Selector S,
1157 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001158 const ObjCInterfaceDecl* ID,
1159 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001160 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001161
Ted Kremeneka821b792009-04-29 05:04:30 +00001162 // Look up a summary in our summary cache.
1163 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001164
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001165 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001166 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001167
Ted Kremeneka56ae162009-05-03 05:20:50 +00001168 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001169 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001170
Ted Kremenek2f226732009-05-04 05:31:22 +00001171 // "initXXX": pass-through for receiver.
1172 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1173 == InitRule)
1174 Summ = getInitMethodSummary(RetTy);
1175 else
1176 Summ = getCommonMethodSummary(MD, S, RetTy);
1177
Ted Kremenek2f226732009-05-04 05:31:22 +00001178 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001179 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001180 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001181}
1182
Ted Kremeneka7722b72008-05-06 21:26:51 +00001183RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001184RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001185 const ObjCInterfaceDecl *ID,
1186 const ObjCMethodDecl *MD,
1187 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001188
Ted Kremenek578498a2009-04-29 00:42:39 +00001189 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001190 ObjCMethodSummariesTy::iterator I =
1191 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001192
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001193 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001194 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001195
1196 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
1197
Ted Kremenek2f226732009-05-04 05:31:22 +00001198 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001199 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001200 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001201}
1202
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001203void RetainSummaryManager::InitializeClassMethodSummaries() {
1204 assert(ScratchArgs.isEmpty());
1205 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001206
Ted Kremenek272aa852008-06-25 21:21:56 +00001207 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1208 // NSObject and its derivatives.
1209 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1210 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1211 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001212
1213 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001214 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001215 GetNullarySelector("currentHandler", Ctx),
1216 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001217
1218 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001219 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001220 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1221 GetUnarySelector("addObject", Ctx),
1222 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001223 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001224
1225 // Create the summaries for [NSObject performSelector...]. We treat
1226 // these as 'stop tracking' for the arguments because they are often
1227 // used for delegates that can release the object. When we have better
1228 // inter-procedural analysis we can potentially do something better. This
1229 // workaround is to remove false positives.
1230 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1231 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1232 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1233 "afterDelay", NULL);
1234 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1235 "afterDelay", "inModes", NULL);
1236 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1237 "withObject", "waitUntilDone", NULL);
1238 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1239 "withObject", "waitUntilDone", "modes", NULL);
1240 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1241 "withObject", "waitUntilDone", NULL);
1242 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1243 "withObject", "waitUntilDone", "modes", NULL);
1244 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1245 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001246}
1247
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001248void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001249
Ted Kremeneka56ae162009-05-03 05:20:50 +00001250 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001251
Ted Kremeneka7722b72008-05-06 21:26:51 +00001252 // Create the "init" selector. It just acts as a pass-through for the
1253 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001254 RetainSummary* InitSumm =
1255 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001256 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001257
1258 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001259 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001260
1261 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001262 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1263
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001264 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001265 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001266
Ted Kremenek266d8b62008-05-06 02:26:56 +00001267 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001268 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001269 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001270 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001271
1272 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001273 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001274 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001275
1276 // Create the "drain" selector.
1277 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001278 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001279
1280 // Create the -dealloc summary.
1281 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1282 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001283
1284 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001285 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001286 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001287
Ted Kremenekaac82832009-02-23 17:45:03 +00001288 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001289 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001290 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001291 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001292
Ted Kremenek45642a42008-08-12 18:48:50 +00001293 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001294 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1295 // self-own themselves. However, they only do this once they are displayed.
1296 // Thus, we need to track an NSWindow's display status.
1297 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001298 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001299 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1300
1301 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1302
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001303
1304#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001305 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001306 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001307
1308 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1309 "styleMask", "backing", "defer", NULL);
1310
1311 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1312 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001313#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001314
1315 // For NSPanel (which subclasses NSWindow), allocated objects are not
1316 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001317 // FIXME: For now we don't track NSPanels. object for the same reason
1318 // as for NSWindow objects.
1319 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1320
Ted Kremenek45642a42008-08-12 18:48:50 +00001321 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1322 "styleMask", "backing", "defer", NULL);
1323
1324 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1325 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001326
Ted Kremenekf2717b02008-07-18 17:24:20 +00001327 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001328 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1329 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001330
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001331 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1332 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001333}
1334
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001335//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001336// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001337//===----------------------------------------------------------------------===//
1338
Ted Kremeneka7338b42008-03-11 06:39:11 +00001339namespace {
1340
Ted Kremenek7d421f32008-04-09 23:49:11 +00001341class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001342public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001343 enum Kind {
1344 Owned = 0, // Owning reference.
1345 NotOwned, // Reference is not owned by still valid (not freed).
1346 Released, // Object has been released.
1347 ReturnedOwned, // Returned object passes ownership to caller.
1348 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001349 ERROR_START,
1350 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1351 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001352 ErrorUseAfterRelease, // Object used after released.
1353 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001354 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001355 ErrorLeak, // A memory leak due to excessive reference counts.
1356 ErrorLeakReturned // A memory leak due to the returning method not having
1357 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001358 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001359
1360private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001361 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001362 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001363 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001364 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001365 QualType T;
1366
Ted Kremenek4d99d342009-05-08 20:01:42 +00001367 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1368 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001369
Ted Kremenek68621b92009-01-28 05:56:51 +00001370 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001371 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001372
1373public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001374 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001375
1376 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001377
Ted Kremenek4d99d342009-05-08 20:01:42 +00001378 unsigned getCount() const { return Cnt; }
1379 unsigned getAutoreleaseCount() const { return ACnt; }
1380 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1381 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001382
Ted Kremenek272aa852008-06-25 21:21:56 +00001383 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001384
1385 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001386
Ted Kremenek6537a642009-03-17 19:42:23 +00001387 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001388
Ted Kremenek6537a642009-03-17 19:42:23 +00001389 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001390
Ted Kremenekffefc352008-04-11 22:25:11 +00001391 bool isOwned() const {
1392 return getKind() == Owned;
1393 }
1394
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001395 bool isNotOwned() const {
1396 return getKind() == NotOwned;
1397 }
1398
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001399 bool isReturnedOwned() const {
1400 return getKind() == ReturnedOwned;
1401 }
1402
1403 bool isReturnedNotOwned() const {
1404 return getKind() == ReturnedNotOwned;
1405 }
1406
1407 bool isNonLeakError() const {
1408 Kind k = getKind();
1409 return isError(k) && !isLeak(k);
1410 }
1411
Ted Kremenek68621b92009-01-28 05:56:51 +00001412 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1413 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001414 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001415 }
1416
Ted Kremenek68621b92009-01-28 05:56:51 +00001417 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1418 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001419 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001420 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001421
1422 static RefVal makeReturnedOwned(unsigned Count) {
1423 return RefVal(ReturnedOwned, Count);
1424 }
1425
1426 static RefVal makeReturnedNotOwned() {
1427 return RefVal(ReturnedNotOwned);
1428 }
1429
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001430 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001431
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001432 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001433 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001434 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001435
Ted Kremenek272aa852008-06-25 21:21:56 +00001436 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001437 return RefVal(getKind(), getObjKind(), getCount() - i,
1438 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001439 }
1440
1441 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001442 return RefVal(getKind(), getObjKind(), getCount() + i,
1443 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001444 }
1445
1446 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001447 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1448 getType());
1449 }
1450
1451 RefVal autorelease() const {
1452 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1453 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001454 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001455
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001456 void Profile(llvm::FoldingSetNodeID& ID) const {
1457 ID.AddInteger((unsigned) kind);
1458 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001459 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001460 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001461 }
1462
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001463 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001464};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001465
1466void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001467 if (!T.isNull())
1468 Out << "Tracked Type:" << T.getAsString() << '\n';
1469
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001470 switch (getKind()) {
1471 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001472 case Owned: {
1473 Out << "Owned";
1474 unsigned cnt = getCount();
1475 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001476 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001477 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001478
Ted Kremenekc4f81022008-04-10 23:09:18 +00001479 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001480 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001481 unsigned cnt = getCount();
1482 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001483 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001484 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001485
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001486 case ReturnedOwned: {
1487 Out << "ReturnedOwned";
1488 unsigned cnt = getCount();
1489 if (cnt) Out << " (+ " << cnt << ")";
1490 break;
1491 }
1492
1493 case ReturnedNotOwned: {
1494 Out << "ReturnedNotOwned";
1495 unsigned cnt = getCount();
1496 if (cnt) Out << " (+ " << cnt << ")";
1497 break;
1498 }
1499
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001500 case Released:
1501 Out << "Released";
1502 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001503
1504 case ErrorDeallocGC:
1505 Out << "-dealloc (GC)";
1506 break;
1507
1508 case ErrorDeallocNotOwned:
1509 Out << "-dealloc (not-owned)";
1510 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001511
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001512 case ErrorLeak:
1513 Out << "Leaked";
1514 break;
1515
Ted Kremenek311f3d42008-10-22 23:56:21 +00001516 case ErrorLeakReturned:
1517 Out << "Leaked (Bad naming)";
1518 break;
1519
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001520 case ErrorUseAfterRelease:
1521 Out << "Use-After-Release [ERROR]";
1522 break;
1523
1524 case ErrorReleaseNotOwned:
1525 Out << "Release of Not-Owned [ERROR]";
1526 break;
1527 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001528
1529 if (ACnt) {
1530 Out << " [ARC +" << ACnt << ']';
1531 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001532}
Ted Kremenek0d721572008-03-11 17:48:22 +00001533
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001534} // end anonymous namespace
1535
1536//===----------------------------------------------------------------------===//
1537// RefBindings - State used to track object reference counts.
1538//===----------------------------------------------------------------------===//
1539
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001540typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001541static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001542static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001543
1544namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001545 template<>
1546 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1547 static inline void* GDMIndex() { return &RefBIndex; }
1548 };
1549}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001550
1551//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001552// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001553//===----------------------------------------------------------------------===//
1554
Ted Kremenekb6578942009-02-24 19:15:11 +00001555typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1556typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1557typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001558
Ted Kremenekb6578942009-02-24 19:15:11 +00001559static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001560static int AutoRBIndex = 0;
1561
Ted Kremenekb6578942009-02-24 19:15:11 +00001562namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001563namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001564
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001565namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001566template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001567 : public GRStatePartialTrait<ARStack> {
1568 static inline void* GDMIndex() { return &AutoRBIndex; }
1569};
1570
1571template<> struct GRStateTrait<AutoreleasePoolContents>
1572 : public GRStatePartialTrait<ARPoolContents> {
1573 static inline void* GDMIndex() { return &AutoRCIndex; }
1574};
1575} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001576
Ted Kremenek681fb352009-03-20 17:34:15 +00001577static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1578 ARStack stack = state->get<AutoreleaseStack>();
1579 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1580}
1581
1582static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1583 SymbolRef sym) {
1584
1585 SymbolRef pool = GetCurrentAutoreleasePool(state);
1586 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1587 ARCounts newCnts(0);
1588
1589 if (cnts) {
1590 const unsigned *cnt = (*cnts).lookup(sym);
1591 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1592 }
1593 else
1594 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1595
1596 return state.set<AutoreleasePoolContents>(pool, newCnts);
1597}
1598
Ted Kremenek7aef4842008-04-16 20:40:59 +00001599//===----------------------------------------------------------------------===//
1600// Transfer functions.
1601//===----------------------------------------------------------------------===//
1602
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001603namespace {
1604
Ted Kremenek7d421f32008-04-09 23:49:11 +00001605class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001606public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001607 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001608 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001609 virtual void Print(std::ostream& Out, const GRState* state,
1610 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001611 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001612
1613private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001614 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1615 SummaryLogTy;
1616
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001617 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001618 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001619 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001620 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001621
Ted Kremenek708af042009-02-05 06:50:21 +00001622 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001623 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001624 BugType *leakWithinFunction, *leakAtReturn;
1625 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001626
Ted Kremenekb6578942009-02-24 19:15:11 +00001627 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1628 RefVal::Kind& hasErr);
1629
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001630 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1631 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001632 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001633 ExplodedNode<GRState>* Pred,
1634 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001635 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001636
Ted Kremenek0106e202008-10-24 20:32:50 +00001637 std::pair<GRStateRef, bool>
1638 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001639 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001640
Ted Kremenekb6578942009-02-24 19:15:11 +00001641public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001642 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001643 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001644 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1645 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001646 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001647
Ted Kremenek708af042009-02-05 06:50:21 +00001648 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001649
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001650 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001651
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001652 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1653 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001654 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001655
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001656 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001657 const LangOptions& getLangOptions() const { return LOpts; }
1658
Ted Kremenekc26c4692009-02-18 03:48:14 +00001659 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1660 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1661 return I == SummaryLog.end() ? 0 : I->second;
1662 }
1663
Ted Kremeneka7338b42008-03-11 06:39:11 +00001664 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001665
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001666 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001667 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001668 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001669 Expr* Ex,
1670 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001671 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001672 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001673 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001674
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001675 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001676 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001677 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001678 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001679 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001680
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001681
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001682 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001683 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001684 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001685 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001686 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001687
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001688 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001689 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001690 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001691 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001692 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001693
Ted Kremeneka42be302009-02-14 01:43:44 +00001694 // Stores.
1695 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1696
Ted Kremenekffefc352008-04-11 22:25:11 +00001697 // End-of-path.
1698
1699 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001700 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001701
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001702 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001703 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001704 GRStmtNodeBuilder<GRState>& Builder,
1705 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001706 Stmt* S, const GRState* state,
1707 SymbolReaper& SymReaper);
1708
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001709 // Return statements.
1710
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001711 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001712 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001713 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001714 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001715 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001716
1717 // Assumptions.
1718
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001719 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001720 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001721 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001722};
1723
1724} // end anonymous namespace
1725
Ted Kremenek681fb352009-03-20 17:34:15 +00001726static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1727 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001728 if (Sym)
1729 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001730 else
1731 Out << "<pool>";
1732 Out << ":{";
1733
1734 // Get the contents of the pool.
1735 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1736 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1737 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1738
1739 Out << '}';
1740}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001741
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001742void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1743 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001744
1745
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001746
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001747 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001748
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001749 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001750 Out << sep << nl;
1751
1752 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1753 Out << (*I).first << " : ";
1754 (*I).second.print(Out);
1755 Out << nl;
1756 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001757
1758 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001759 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001760 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001761
Ted Kremenek681fb352009-03-20 17:34:15 +00001762 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1763 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1764 PrintPool(Out, *I, state);
1765
1766 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001767}
1768
Ted Kremenek47a72422009-04-29 18:50:19 +00001769//===----------------------------------------------------------------------===//
1770// Error reporting.
1771//===----------------------------------------------------------------------===//
1772
1773namespace {
1774
1775 //===-------------===//
1776 // Bug Descriptions. //
1777 //===-------------===//
1778
1779 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1780 protected:
1781 CFRefCount& TF;
1782
1783 CFRefBug(CFRefCount* tf, const char* name)
1784 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1785 public:
1786
1787 CFRefCount& getTF() { return TF; }
1788 const CFRefCount& getTF() const { return TF; }
1789
1790 // FIXME: Eventually remove.
1791 virtual const char* getDescription() const = 0;
1792
1793 virtual bool isLeak() const { return false; }
1794 };
1795
1796 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1797 public:
1798 UseAfterRelease(CFRefCount* tf)
1799 : CFRefBug(tf, "Use-after-release") {}
1800
1801 const char* getDescription() const {
1802 return "Reference-counted object is used after it is released";
1803 }
1804 };
1805
1806 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1807 public:
1808 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1809
1810 const char* getDescription() const {
1811 return "Incorrect decrement of the reference count of an "
1812 "object is not owned at this point by the caller";
1813 }
1814 };
1815
1816 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1817 public:
1818 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1819 "-dealloc called while using GC") {}
1820
1821 const char *getDescription() const {
1822 return "-dealloc called while using GC";
1823 }
1824 };
1825
1826 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1827 public:
1828 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1829 "-dealloc sent to non-exclusively owned object") {}
1830
1831 const char *getDescription() const {
1832 return "-dealloc sent to object that may be referenced elsewhere";
1833 }
1834 };
1835
1836 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1837 const bool isReturn;
1838 protected:
1839 Leak(CFRefCount* tf, const char* name, bool isRet)
1840 : CFRefBug(tf, name), isReturn(isRet) {}
1841 public:
1842
1843 const char* getDescription() const { return ""; }
1844
1845 bool isLeak() const { return true; }
1846 };
1847
1848 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1849 public:
1850 LeakAtReturn(CFRefCount* tf, const char* name)
1851 : Leak(tf, name, true) {}
1852 };
1853
1854 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1855 public:
1856 LeakWithinFunction(CFRefCount* tf, const char* name)
1857 : Leak(tf, name, false) {}
1858 };
1859
1860 //===---------===//
1861 // Bug Reports. //
1862 //===---------===//
1863
1864 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1865 protected:
1866 SymbolRef Sym;
1867 const CFRefCount &TF;
1868 public:
1869 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1870 ExplodedNode<GRState> *n, SymbolRef sym)
1871 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1872
1873 virtual ~CFRefReport() {}
1874
1875 CFRefBug& getBugType() {
1876 return (CFRefBug&) RangedBugReport::getBugType();
1877 }
1878 const CFRefBug& getBugType() const {
1879 return (const CFRefBug&) RangedBugReport::getBugType();
1880 }
1881
1882 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1883 const SourceRange*& end) {
1884
1885 if (!getBugType().isLeak())
1886 RangedBugReport::getRanges(BR, beg, end);
1887 else
1888 beg = end = 0;
1889 }
1890
1891 SymbolRef getSymbol() const { return Sym; }
1892
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001893 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001894 const ExplodedNode<GRState>* N);
1895
1896 std::pair<const char**,const char**> getExtraDescriptiveText();
1897
1898 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1899 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001900 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00001901 };
1902
1903 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1904 SourceLocation AllocSite;
1905 const MemRegion* AllocBinding;
1906 public:
1907 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1908 ExplodedNode<GRState> *n, SymbolRef sym,
1909 GRExprEngine& Eng);
1910
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001911 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001912 const ExplodedNode<GRState>* N);
1913
1914 SourceLocation getLocation() const { return AllocSite; }
1915 };
1916} // end anonymous namespace
1917
1918void CFRefCount::RegisterChecks(BugReporter& BR) {
1919 useAfterRelease = new UseAfterRelease(this);
1920 BR.Register(useAfterRelease);
1921
1922 releaseNotOwned = new BadRelease(this);
1923 BR.Register(releaseNotOwned);
1924
1925 deallocGC = new DeallocGC(this);
1926 BR.Register(deallocGC);
1927
1928 deallocNotOwned = new DeallocNotOwned(this);
1929 BR.Register(deallocNotOwned);
1930
1931 // First register "return" leaks.
1932 const char* name = 0;
1933
1934 if (isGCEnabled())
1935 name = "Leak of returned object when using garbage collection";
1936 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1937 name = "Leak of returned object when not using garbage collection (GC) in "
1938 "dual GC/non-GC code";
1939 else {
1940 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1941 name = "Leak of returned object";
1942 }
1943
1944 leakAtReturn = new LeakAtReturn(this, name);
1945 BR.Register(leakAtReturn);
1946
1947 // Second, register leaks within a function/method.
1948 if (isGCEnabled())
1949 name = "Leak of object when using garbage collection";
1950 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1951 name = "Leak of object when not using garbage collection (GC) in "
1952 "dual GC/non-GC code";
1953 else {
1954 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1955 name = "Leak";
1956 }
1957
1958 leakWithinFunction = new LeakWithinFunction(this, name);
1959 BR.Register(leakWithinFunction);
1960
1961 // Save the reference to the BugReporter.
1962 this->BR = &BR;
1963}
1964
1965static const char* Msgs[] = {
1966 // GC only
1967 "Code is compiled to only use garbage collection",
1968 // No GC.
1969 "Code is compiled to use reference counts",
1970 // Hybrid, with GC.
1971 "Code is compiled to use either garbage collection (GC) or reference counts"
1972 " (non-GC). The bug occurs with GC enabled",
1973 // Hybrid, without GC
1974 "Code is compiled to use either garbage collection (GC) or reference counts"
1975 " (non-GC). The bug occurs in non-GC mode"
1976};
1977
1978std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
1979 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
1980
1981 switch (TF.getLangOptions().getGCMode()) {
1982 default:
1983 assert(false);
1984
1985 case LangOptions::GCOnly:
1986 assert (TF.isGCEnabled());
1987 return std::make_pair(&Msgs[0], &Msgs[0]+1);
1988
1989 case LangOptions::NonGC:
1990 assert (!TF.isGCEnabled());
1991 return std::make_pair(&Msgs[1], &Msgs[1]+1);
1992
1993 case LangOptions::HybridGC:
1994 if (TF.isGCEnabled())
1995 return std::make_pair(&Msgs[2], &Msgs[2]+1);
1996 else
1997 return std::make_pair(&Msgs[3], &Msgs[3]+1);
1998 }
1999}
2000
2001static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2002 ArgEffect X) {
2003 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2004 I!=E; ++I)
2005 if (*I == X) return true;
2006
2007 return false;
2008}
2009
2010PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2011 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002012 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002013
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002014 // Check if the type state has changed.
2015 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002016 GRStateRef PrevSt(PrevN->getState(), StMgr);
2017 GRStateRef CurrSt(N->getState(), StMgr);
2018
2019 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2020 if (!CurrT) return NULL;
2021
2022 const RefVal& CurrV = *CurrT;
2023 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2024
2025 // Create a string buffer to constain all the useful things we want
2026 // to tell the user.
2027 std::string sbuf;
2028 llvm::raw_string_ostream os(sbuf);
2029
2030 // This is the allocation site since the previous node had no bindings
2031 // for this symbol.
2032 if (!PrevT) {
2033 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2034
2035 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2036 // Get the name of the callee (if it is available).
2037 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2038 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2039 os << "Call to function '" << FD->getNameAsString() <<'\'';
2040 else
2041 os << "function call";
2042 }
2043 else {
2044 assert (isa<ObjCMessageExpr>(S));
2045 os << "Method";
2046 }
2047
2048 if (CurrV.getObjKind() == RetEffect::CF) {
2049 os << " returns a Core Foundation object with a ";
2050 }
2051 else {
2052 assert (CurrV.getObjKind() == RetEffect::ObjC);
2053 os << " returns an Objective-C object with a ";
2054 }
2055
2056 if (CurrV.isOwned()) {
2057 os << "+1 retain count (owning reference).";
2058
2059 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2060 assert(CurrV.getObjKind() == RetEffect::CF);
2061 os << " "
2062 "Core Foundation objects are not automatically garbage collected.";
2063 }
2064 }
2065 else {
2066 assert (CurrV.isNotOwned());
2067 os << "+0 retain count (non-owning reference).";
2068 }
2069
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002070 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002071 return new PathDiagnosticEventPiece(Pos, os.str());
2072 }
2073
2074 // Gather up the effects that were performed on the object at this
2075 // program point
2076 llvm::SmallVector<ArgEffect, 2> AEffects;
2077
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002078 if (const RetainSummary *Summ =
2079 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002080 // We only have summaries attached to nodes after evaluating CallExpr and
2081 // ObjCMessageExprs.
2082 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2083
2084 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2085 // Iterate through the parameter expressions and see if the symbol
2086 // was ever passed as an argument.
2087 unsigned i = 0;
2088
2089 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2090 AI!=AE; ++AI, ++i) {
2091
2092 // Retrieve the value of the argument. Is it the symbol
2093 // we are interested in?
2094 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2095 continue;
2096
2097 // We have an argument. Get the effect!
2098 AEffects.push_back(Summ->getArg(i));
2099 }
2100 }
2101 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2102 if (Expr *receiver = ME->getReceiver())
2103 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2104 // The symbol we are tracking is the receiver.
2105 AEffects.push_back(Summ->getReceiverEffect());
2106 }
2107 }
2108 }
2109
2110 do {
2111 // Get the previous type state.
2112 RefVal PrevV = *PrevT;
2113
2114 // Specially handle -dealloc.
2115 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2116 // Determine if the object's reference count was pushed to zero.
2117 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2118 // We may not have transitioned to 'release' if we hit an error.
2119 // This case is handled elsewhere.
2120 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002121 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002122 os << "Object released by directly sending the '-dealloc' message";
2123 break;
2124 }
2125 }
2126
2127 // Specially handle CFMakeCollectable and friends.
2128 if (contains(AEffects, MakeCollectable)) {
2129 // Get the name of the function.
2130 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2131 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2132 const FunctionDecl* FD = X.getAsFunctionDecl();
2133 const std::string& FName = FD->getNameAsString();
2134
2135 if (TF.isGCEnabled()) {
2136 // Determine if the object's reference count was pushed to zero.
2137 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2138
2139 os << "In GC mode a call to '" << FName
2140 << "' decrements an object's retain count and registers the "
2141 "object with the garbage collector. ";
2142
2143 if (CurrV.getKind() == RefVal::Released) {
2144 assert(CurrV.getCount() == 0);
2145 os << "Since it now has a 0 retain count the object can be "
2146 "automatically collected by the garbage collector.";
2147 }
2148 else
2149 os << "An object must have a 0 retain count to be garbage collected. "
2150 "After this call its retain count is +" << CurrV.getCount()
2151 << '.';
2152 }
2153 else
2154 os << "When GC is not enabled a call to '" << FName
2155 << "' has no effect on its argument.";
2156
2157 // Nothing more to say.
2158 break;
2159 }
2160
2161 // Determine if the typestate has changed.
2162 if (!(PrevV == CurrV))
2163 switch (CurrV.getKind()) {
2164 case RefVal::Owned:
2165 case RefVal::NotOwned:
2166
Ted Kremenek4d99d342009-05-08 20:01:42 +00002167 if (PrevV.getCount() == CurrV.getCount()) {
2168 // Did an autorelease message get sent?
2169 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2170 return 0;
2171
2172 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2173 os << "Object added to autorelease pool.";
2174 break;
2175 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002176
2177 if (PrevV.getCount() > CurrV.getCount())
2178 os << "Reference count decremented.";
2179 else
2180 os << "Reference count incremented.";
2181
2182 if (unsigned Count = CurrV.getCount())
2183 os << " The object now has a +" << Count << " retain count.";
2184
2185 if (PrevV.getKind() == RefVal::Released) {
2186 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2187 os << " The object is not eligible for garbage collection until the "
2188 "retain count reaches 0 again.";
2189 }
2190
2191 break;
2192
2193 case RefVal::Released:
2194 os << "Object released.";
2195 break;
2196
2197 case RefVal::ReturnedOwned:
2198 os << "Object returned to caller as an owning reference (single retain "
2199 "count transferred to caller).";
2200 break;
2201
2202 case RefVal::ReturnedNotOwned:
2203 os << "Object returned to caller with a +0 (non-owning) retain count.";
2204 break;
2205
2206 default:
2207 return NULL;
2208 }
2209
2210 // Emit any remaining diagnostics for the argument effects (if any).
2211 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2212 E=AEffects.end(); I != E; ++I) {
2213
2214 // A bunch of things have alternate behavior under GC.
2215 if (TF.isGCEnabled())
2216 switch (*I) {
2217 default: break;
2218 case Autorelease:
2219 os << "In GC mode an 'autorelease' has no effect.";
2220 continue;
2221 case IncRefMsg:
2222 os << "In GC mode the 'retain' message has no effect.";
2223 continue;
2224 case DecRefMsg:
2225 os << "In GC mode the 'release' message has no effect.";
2226 continue;
2227 }
2228 }
2229 } while(0);
2230
2231 if (os.str().empty())
2232 return 0; // We have nothing to say!
2233
2234 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002235 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002236 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2237
2238 // Add the range by scanning the children of the statement for any bindings
2239 // to Sym.
2240 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2241 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2242 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2243 P->addRange(Exp->getSourceRange());
2244 break;
2245 }
2246
2247 return P;
2248}
2249
2250namespace {
2251 class VISIBILITY_HIDDEN FindUniqueBinding :
2252 public StoreManager::BindingsHandler {
2253 SymbolRef Sym;
2254 const MemRegion* Binding;
2255 bool First;
2256
2257 public:
2258 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2259
2260 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2261 SVal val) {
2262
2263 SymbolRef SymV = val.getAsSymbol();
2264 if (!SymV || SymV != Sym)
2265 return true;
2266
2267 if (Binding) {
2268 First = false;
2269 return false;
2270 }
2271 else
2272 Binding = R;
2273
2274 return true;
2275 }
2276
2277 operator bool() { return First && Binding; }
2278 const MemRegion* getRegion() { return Binding; }
2279 };
2280}
2281
2282static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2283GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2284 SymbolRef Sym) {
2285
2286 // Find both first node that referred to the tracked symbol and the
2287 // memory location that value was store to.
2288 const ExplodedNode<GRState>* Last = N;
2289 const MemRegion* FirstBinding = 0;
2290
2291 while (N) {
2292 const GRState* St = N->getState();
2293 RefBindings B = St->get<RefBindings>();
2294
2295 if (!B.lookup(Sym))
2296 break;
2297
2298 FindUniqueBinding FB(Sym);
2299 StateMgr.iterBindings(St, FB);
2300 if (FB) FirstBinding = FB.getRegion();
2301
2302 Last = N;
2303 N = N->pred_empty() ? NULL : *(N->pred_begin());
2304 }
2305
2306 return std::make_pair(Last, FirstBinding);
2307}
2308
2309PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002310CFRefReport::getEndPath(BugReporterContext& BRC,
2311 const ExplodedNode<GRState>* EndN) {
2312 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002313 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002314 BRC.addNotableSymbol(Sym);
2315 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002316}
2317
2318PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002319CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2320 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002321
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002322 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002323 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002324 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002325
2326 // We are reporting a leak. Walk up the graph to get to the first node where
2327 // the symbol appeared, and also get the first VarDecl that tracked object
2328 // is stored to.
2329 const ExplodedNode<GRState>* AllocNode = 0;
2330 const MemRegion* FirstBinding = 0;
2331
2332 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002333 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002334
2335 // Get the allocate site.
2336 assert(AllocNode);
2337 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2338
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002339 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002340 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2341
2342 // Compute an actual location for the leak. Sometimes a leak doesn't
2343 // occur at an actual statement (e.g., transition between blocks; end
2344 // of function) so we need to walk the graph and compute a real location.
2345 const ExplodedNode<GRState>* LeakN = EndN;
2346 PathDiagnosticLocation L;
2347
2348 while (LeakN) {
2349 ProgramPoint P = LeakN->getLocation();
2350
2351 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2352 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2353 break;
2354 }
2355 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2356 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2357 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2358 break;
2359 }
2360 }
2361
2362 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2363 }
2364
2365 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002366 const Decl &D = BRC.getCodeDecl();
2367 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002368 }
2369
2370 std::string sbuf;
2371 llvm::raw_string_ostream os(sbuf);
2372
2373 os << "Object allocated on line " << AllocLine;
2374
2375 if (FirstBinding)
2376 os << " and stored into '" << FirstBinding->getString() << '\'';
2377
2378 // Get the retain count.
2379 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2380
2381 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2382 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2383 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2384 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002385 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002386 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002387 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002388 << "') does not contain 'copy' or otherwise starts with"
2389 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002390 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002391 }
2392 else
2393 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002394 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002395
2396 return new PathDiagnosticEventPiece(L, os.str());
2397}
2398
2399
2400CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2401 ExplodedNode<GRState> *n,
2402 SymbolRef sym, GRExprEngine& Eng)
2403: CFRefReport(D, tf, n, sym)
2404{
2405
2406 // Most bug reports are cached at the location where they occured.
2407 // With leaks, we want to unique them by the location where they were
2408 // allocated, and only report a single path. To do this, we need to find
2409 // the allocation site of a piece of tracked memory, which we do via a
2410 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2411 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2412 // that all ancestor nodes that represent the allocation site have the
2413 // same SourceLocation.
2414 const ExplodedNode<GRState>* AllocNode = 0;
2415
2416 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2417 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2418
2419 // Get the SourceLocation for the allocation site.
2420 ProgramPoint P = AllocNode->getLocation();
2421 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2422
2423 // Fill in the description of the bug.
2424 Description.clear();
2425 llvm::raw_string_ostream os(Description);
2426 SourceManager& SMgr = Eng.getContext().getSourceManager();
2427 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002428 os << "Potential leak ";
2429 if (tf.isGCEnabled()) {
2430 os << "(when using garbage collection) ";
2431 }
2432 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002433
2434 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2435 if (AllocBinding)
2436 os << " and stored into '" << AllocBinding->getString() << '\'';
2437}
2438
2439//===----------------------------------------------------------------------===//
2440// Main checker logic.
2441//===----------------------------------------------------------------------===//
2442
Ted Kremenek272aa852008-06-25 21:21:56 +00002443/// GetReturnType - Used to get the return type of a message expression or
2444/// function call with the intention of affixing that type to a tracked symbol.
2445/// While the the return type can be queried directly from RetEx, when
2446/// invoking class methods we augment to the return type to be that of
2447/// a pointer to the class (as opposed it just being id).
2448static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2449
2450 QualType RetTy = RetE->getType();
2451
2452 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002453 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002454 if (!PT)
2455 return RetTy;
2456
2457 // If RetEx is not a message expression just return its type.
2458 // If RetEx is a message expression, return its types if it is something
2459 /// more specific than id.
2460
2461 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2462
Steve Naroff17c03822009-02-12 17:52:19 +00002463 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002464 return RetTy;
2465
2466 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2467
2468 // At this point we know the return type of the message expression is id.
2469 // If we have an ObjCInterceDecl, we know this is a call to a class method
2470 // whose type we can resolve. In such cases, promote the return type to
2471 // Class*.
2472 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2473}
2474
2475
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002476void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002477 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002478 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002479 Expr* Ex,
2480 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002481 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002482 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002483 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002484
Ted Kremeneka7338b42008-03-11 06:39:11 +00002485 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002486 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002487 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002488
2489 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002490 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002491 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002492 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002493 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002494
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002495 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002496 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002497 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002498
Ted Kremenek74556a12009-03-26 03:35:11 +00002499 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002500 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002501 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002502 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002503 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002504 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002505 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002506 }
2507 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002508 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002509
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002510 if (isa<Loc>(V)) {
2511 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002512 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002513 continue;
2514
2515 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002516
2517 // FIXME: Either this logic should also be replicated in GRSimpleVals
2518 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002519
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002520 // FIXME: We can have collisions on the conjured symbol if the
2521 // expression *I also creates conjured symbols. We probably want
2522 // to identify conjured symbols by an expression pair: the enclosing
2523 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002524 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002525
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002526 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002527
Ted Kremenek73ec7732009-05-06 18:19:24 +00002528 if (R) {
2529 // Are we dealing with an ElementRegion? If the element type is
2530 // a basic integer type (e.g., char, int) and the underying region
2531 // is also typed then strip off the ElementRegion.
2532 // FIXME: We really need to think about this for the general case
2533 // as sometimes we are reasoning about arrays and other times
2534 // about (char*), etc., is just a form of passing raw bytes.
2535 // e.g., void *p = alloca(); foo((char*)p);
2536 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2537 // Checking for 'integral type' is probably too promiscuous, but
2538 // we'll leave it in for now until we have a systematic way of
2539 // handling all of these cases. Eventually we need to come up
2540 // with an interface to StoreManager so that this logic can be
2541 // approriately delegated to the respective StoreManagers while
2542 // still allowing us to do checker-specific logic (e.g.,
2543 // invalidating reference counts), probably via callbacks.
2544 if (ER->getElementType()->isIntegralType())
2545 if (const TypedRegion *superReg =
2546 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2547 R = superReg;
2548 // FIXME: What about layers of ElementRegions?
2549 }
2550
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002551 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002552 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002553
Ted Kremenek53b24182009-03-04 22:56:43 +00002554 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002555 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002556
Ted Kremenek53b24182009-03-04 22:56:43 +00002557 if (R->isBoundable(Ctx)) {
2558 // Set the value of the variable to be a conjured symbol.
2559 unsigned Count = Builder.getCurrentBlockCount();
2560 QualType T = R->getRValueType(Ctx);
2561
Zhongxing Xu079dc352009-04-09 06:03:54 +00002562 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002563 ValueManager &ValMgr = Eng.getValueManager();
2564 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002565 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002566 }
2567 else if (const RecordType *RT = T->getAsStructureType()) {
2568 // Handle structs in a not so awesome way. Here we just
2569 // eagerly bind new symbols to the fields. In reality we
2570 // should have the store manager handle this. The idea is just
2571 // to prototype some basic functionality here. All of this logic
2572 // should one day soon just go away.
2573 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2574
2575 // No record definition. There is nothing we can do.
2576 if (!RD)
2577 continue;
2578
2579 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2580
2581 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002582 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2583 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002584
2585 // For now just handle scalar fields.
2586 FieldDecl *FD = *FI;
2587 QualType FT = FD->getType();
2588
2589 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002590 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002591 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002592 ValueManager &ValMgr = Eng.getValueManager();
2593 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002594 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002595 }
2596 }
2597 }
2598 else {
2599 // Just blast away other values.
2600 state = state.BindLoc(*MR, UnknownVal());
2601 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002602 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002603 }
2604 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002605 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002606 }
2607 else {
2608 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002609 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002610 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002611 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002612 else if (isa<nonloc::LocAsInteger>(V))
2613 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002614 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002615
Ted Kremenek272aa852008-06-25 21:21:56 +00002616 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002617 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002618 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002619 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002620 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002621 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002622 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002623 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002624 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002625 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002626 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002627 }
2628 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002629
Ted Kremenek272aa852008-06-25 21:21:56 +00002630 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002631 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002632 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002633 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002634 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002635 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002636
Ted Kremenekf2717b02008-07-18 17:24:20 +00002637 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002638 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002639
2640 switch (RE.getKind()) {
2641 default:
2642 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002643
Ted Kremenek8f90e712008-10-17 22:23:12 +00002644 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002645
Ted Kremenek455dd862008-04-11 20:23:24 +00002646 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002647 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2648 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002649
Ted Kremenek8f90e712008-10-17 22:23:12 +00002650 // FIXME: We eventually should handle structs and other compound types
2651 // that are returned by value.
2652
2653 QualType T = Ex->getType();
2654
Ted Kremenek79413a52008-11-13 06:10:40 +00002655 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002656 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002657 ValueManager &ValMgr = Eng.getValueManager();
2658 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002659 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002660 }
2661
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002662 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002663 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002664
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002665 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002666 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002667 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002668 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002669 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002670 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002671 break;
2672 }
2673
Ted Kremenek227c5372008-05-06 02:41:27 +00002674 case RetEffect::ReceiverAlias: {
2675 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002676 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002677 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002678 break;
2679 }
2680
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002681 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002682 case RetEffect::OwnedSymbol: {
2683 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002684 ValueManager &ValMgr = Eng.getValueManager();
2685 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2686 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2687 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2688 RetT));
2689 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002690
2691 // FIXME: Add a flag to the checker where allocations are assumed to
2692 // *not fail.
2693#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002694 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2695 bool isFeasible;
2696 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2697 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2698 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002699#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002700
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002701 break;
2702 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002703
2704 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002705 case RetEffect::NotOwnedSymbol: {
2706 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002707 ValueManager &ValMgr = Eng.getValueManager();
2708 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2709 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2710 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2711 RetT));
2712 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002713 break;
2714 }
2715 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002716
Ted Kremenek0dd65012009-02-18 02:00:25 +00002717 // Generate a sink node if we are at the end of a path.
2718 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002719 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2720 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002721
2722 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002723 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002724}
2725
2726
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002727void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002728 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002729 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002730 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002731 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002732 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002733 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002734 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002735
Ted Kremenek286e9852009-05-04 04:57:00 +00002736 assert(Summ);
2737 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002738 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002739}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002740
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002741void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002742 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002743 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002744 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002745 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002746 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002747
Ted Kremenek272aa852008-06-25 21:21:56 +00002748 if (Expr* Receiver = ME->getReceiver()) {
2749 // We need the type-information of the tracked receiver object
2750 // Retrieve it from the state.
2751 ObjCInterfaceDecl* ID = 0;
2752
2753 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2754 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002755 // FIXME: Is this really working as expected? There are cases where
2756 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002757 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002758 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002759
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002760 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002761 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002762 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002763 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002764
2765 if (const PointerType* PT = Ty->getAsPointerType()) {
2766 QualType PointeeTy = PT->getPointeeType();
2767
2768 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2769 ID = IT->getDecl();
2770 }
2771 }
2772 }
2773
Ted Kremenek04e00302009-04-29 17:09:14 +00002774 // FIXME: The receiver could be a reference to a class, meaning that
2775 // we should use the class method.
2776 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002777
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002778 // Special-case: are we sending a mesage to "self"?
2779 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002780 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2781 if (Expr* Receiver = ME->getReceiver()) {
2782 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2783 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2784 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2785 // Update the summary to make the default argument effect
2786 // 'StopTracking'.
2787 Summ = Summaries.copySummary(Summ);
2788 Summ->setDefaultArgEffect(StopTracking);
2789 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002790 }
2791 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002792 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002793 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002794 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002795
Ted Kremenek286e9852009-05-04 04:57:00 +00002796 if (!Summ)
2797 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002798
Ted Kremenek286e9852009-05-04 04:57:00 +00002799 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002800 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002801}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002802
2803namespace {
2804class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2805 GRStateRef state;
2806public:
2807 StopTrackingCallback(GRStateRef st) : state(st) {}
2808 GRStateRef getState() { return state; }
2809
2810 bool VisitSymbol(SymbolRef sym) {
2811 state = state.remove<RefBindings>(sym);
2812 return true;
2813 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002814
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002815 const GRState* getState() const { return state.getState(); }
2816};
2817} // end anonymous namespace
2818
2819
Ted Kremeneka42be302009-02-14 01:43:44 +00002820void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002821 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002822 bool escapes = false;
2823
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002824 // A value escapes in three possible cases (this may change):
2825 //
2826 // (1) we are binding to something that is not a memory region.
2827 // (2) we are binding to a memregion that does not have stack storage
2828 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002829 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002830 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002831
Ted Kremeneka42be302009-02-14 01:43:44 +00002832 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002833 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002834 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002835 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2836 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002837
2838 if (!escapes) {
2839 // To test (3), generate a new state with the binding removed. If it is
2840 // the same state, then it escapes (since the store cannot represent
2841 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002842 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002843 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002844 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002845
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002846 // If our store can represent the binding and we aren't storing to something
2847 // that doesn't have local storage then just return and have the simulation
2848 // state continue as is.
2849 if (!escapes)
2850 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002851
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002852 // Otherwise, find all symbols referenced by 'val' that we are tracking
2853 // and stop tracking them.
2854 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002855}
2856
Ted Kremenek0106e202008-10-24 20:32:50 +00002857std::pair<GRStateRef,bool>
2858CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2859 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002860 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002861 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002862
Ted Kremenek47a72422009-04-29 18:50:19 +00002863 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002864 hasLeak = V.isOwned() ||
2865 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002866
Ted Kremenek47a72422009-04-29 18:50:19 +00002867 GRStateRef state(St, VMgr);
2868
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002869 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002870 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002871
Ted Kremenek0106e202008-10-24 20:32:50 +00002872 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2873 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002874}
2875
Ted Kremenek541db372008-04-24 23:57:27 +00002876
Ted Kremenekffefc352008-04-11 22:25:11 +00002877
Ted Kremenek541db372008-04-24 23:57:27 +00002878// Dead symbols.
2879
Ted Kremenek708af042009-02-05 06:50:21 +00002880
Ted Kremenek541db372008-04-24 23:57:27 +00002881
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002882 // Return statements.
2883
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002884void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002885 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002886 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002887 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002888 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002889
2890 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002891 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002892 return;
2893
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002894 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002895 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002896
Ted Kremenek74556a12009-03-26 03:35:11 +00002897 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002898 return;
2899
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002900 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002901 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002902
2903 if (!T)
2904 return;
2905
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002906 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002907 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002908
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002909 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002910 case RefVal::Owned: {
2911 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002912 assert (cnt > 0);
2913 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002914 break;
2915 }
2916
2917 case RefVal::NotOwned: {
2918 unsigned cnt = X.getCount();
2919 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2920 : RefVal::makeReturnedNotOwned();
2921 break;
2922 }
2923
2924 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002925 return;
2926 }
2927
2928 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002929 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002930 Pred = Builder.MakeNode(Dst, S, Pred, state);
2931
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002932 // Did we cache out?
2933 if (!Pred)
2934 return;
2935
Ted Kremenek47a72422009-04-29 18:50:19 +00002936 // Any leaks or other errors?
2937 if (X.isReturnedOwned() && X.getCount() == 0) {
2938 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2939
Ted Kremenek314b1952009-04-29 23:03:22 +00002940 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002941 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2942 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002943 static int ReturnOwnLeakTag = 0;
2944 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002945 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002946 if (ExplodedNode<GRState> *N =
2947 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2948 CFRefLeakReport *report =
2949 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2950 N, Sym, Eng);
2951 BR->EmitReport(report);
2952 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002953 }
2954 }
2955 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002956}
2957
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002958// Assumptions.
2959
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002960const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2961 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002962 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002963 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002964
2965 // FIXME: We may add to the interface of EvalAssume the list of symbols
2966 // whose assumptions have changed. For now we just iterate through the
2967 // bindings and check if any of the tracked symbols are NULL. This isn't
2968 // too bad since the number of symbols we will track in practice are
2969 // probably small and EvalAssume is only called at branches and a few
2970 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002971 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002972
2973 if (B.isEmpty())
2974 return St;
2975
2976 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002977
2978 GRStateRef state(St, VMgr);
2979 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002980
2981 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002982 // Check if the symbol is null (or equal to any constant).
2983 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002984 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002985 changed = true;
2986 B = RefBFactory.Remove(B, I.getKey());
2987 }
2988 }
2989
Ted Kremenek91781202008-08-17 03:20:02 +00002990 if (changed)
2991 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002992
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002993 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002994}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002995
Ted Kremenekb6578942009-02-24 19:15:11 +00002996GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2997 RefVal V, ArgEffect E,
2998 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002999
3000 // In GC mode [... release] and [... retain] do nothing.
3001 switch (E) {
3002 default: break;
3003 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3004 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003005 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003006 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3007 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003008 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003009
Ted Kremenek6537a642009-03-17 19:42:23 +00003010 // Handle all use-after-releases.
3011 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3012 V = V ^ RefVal::ErrorUseAfterRelease;
3013 hasErr = V.getKind();
3014 return state.set<RefBindings>(sym, V);
3015 }
3016
Ted Kremenek0d721572008-03-11 17:48:22 +00003017 switch (E) {
3018 default:
3019 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003020
3021 case Dealloc:
3022 // Any use of -dealloc in GC is *bad*.
3023 if (isGCEnabled()) {
3024 V = V ^ RefVal::ErrorDeallocGC;
3025 hasErr = V.getKind();
3026 break;
3027 }
3028
3029 switch (V.getKind()) {
3030 default:
3031 assert(false && "Invalid case.");
3032 case RefVal::Owned:
3033 // The object immediately transitions to the released state.
3034 V = V ^ RefVal::Released;
3035 V.clearCounts();
3036 return state.set<RefBindings>(sym, V);
3037 case RefVal::NotOwned:
3038 V = V ^ RefVal::ErrorDeallocNotOwned;
3039 hasErr = V.getKind();
3040 break;
3041 }
3042 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003043
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003044 case NewAutoreleasePool:
3045 assert(!isGCEnabled());
3046 return state.add<AutoreleaseStack>(sym);
3047
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003048 case MayEscape:
3049 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003050 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003051 break;
3052 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003053
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003054 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003055
Ted Kremenekede40b72008-07-09 18:11:16 +00003056 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003057 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003058 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003059
Ted Kremenek9b112d22009-01-28 21:44:40 +00003060 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003061 if (isGCEnabled())
3062 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003063
3064 // Update the autorelease counts.
3065 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003066 V = V.autorelease();
Ted Kremenek6537a642009-03-17 19:42:23 +00003067
Ted Kremenek227c5372008-05-06 02:41:27 +00003068 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003069 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003070
Ted Kremenek0d721572008-03-11 17:48:22 +00003071 case IncRef:
3072 switch (V.getKind()) {
3073 default:
3074 assert(false);
3075
3076 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003077 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003078 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003079 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003080 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003081 // Non-GC cases are handled above.
3082 assert(isGCEnabled());
3083 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003084 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003085 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003086 break;
3087
Ted Kremenek272aa852008-06-25 21:21:56 +00003088 case SelfOwn:
3089 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003090 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003091 case DecRef:
3092 switch (V.getKind()) {
3093 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003094 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003095 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003096
Ted Kremenek272aa852008-06-25 21:21:56 +00003097 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003098 assert(V.getCount() > 0);
3099 if (V.getCount() == 1) V = V ^ RefVal::Released;
3100 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003101 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003102
Ted Kremenek272aa852008-06-25 21:21:56 +00003103 case RefVal::NotOwned:
3104 if (V.getCount() > 0)
3105 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003106 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003107 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003108 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003109 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003110 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003111
Ted Kremenek0d721572008-03-11 17:48:22 +00003112 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003113 // Non-GC cases are handled above.
3114 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003115 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003116 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003117 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003118 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003119 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003120 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003121 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003122}
3123
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003124//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003125// Handle dead symbols and end-of-path.
3126//===----------------------------------------------------------------------===//
3127
3128void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3129 GREndPathNodeBuilder<GRState>& Builder) {
3130
3131 const GRState* St = Builder.getState();
3132 RefBindings B = St->get<RefBindings>();
3133
3134 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3135 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3136
3137 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3138 bool hasLeak = false;
3139
3140 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003141 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3142 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003143
3144 St = X.first;
3145 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3146 }
3147
3148 if (Leaked.empty())
3149 return;
3150
3151 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3152
3153 if (!N)
3154 return;
3155
3156 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3157 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3158
3159 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3160 : leakWithinFunction);
3161 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003162 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003163 BR->EmitReport(report);
3164 }
3165}
3166
3167void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3168 GRExprEngine& Eng,
3169 GRStmtNodeBuilder<GRState>& Builder,
3170 ExplodedNode<GRState>* Pred,
3171 Stmt* S,
3172 const GRState* St,
3173 SymbolReaper& SymReaper) {
3174
Ted Kremenek876d8df2009-02-19 23:47:02 +00003175 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003176 RefBindings B = St->get<RefBindings>();
3177 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3178
3179 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3180 E = SymReaper.dead_end(); I != E; ++I) {
3181
3182 const RefVal* T = B.lookup(*I);
3183 if (!T) continue;
3184
3185 bool hasLeak = false;
3186
3187 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003188 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003189
3190 St = X.first;
3191
3192 if (hasLeak)
3193 Leaked.push_back(std::make_pair(*I,X.second));
3194 }
3195
Ted Kremenek876d8df2009-02-19 23:47:02 +00003196 if (!Leaked.empty()) {
3197 // Create a new intermediate node representing the leak point. We
3198 // use a special program point that represents this checker-specific
3199 // transition. We use the address of RefBIndex as a unique tag for this
3200 // checker. We will create another node (if we don't cache out) that
3201 // removes the retain-count bindings from the state.
3202 // NOTE: We use 'generateNode' so that it does interplay with the
3203 // auto-transition logic.
3204 ExplodedNode<GRState>* N =
3205 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003206
Ted Kremenek876d8df2009-02-19 23:47:02 +00003207 if (!N)
3208 return;
3209
3210 // Generate the bug reports.
3211 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3212 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3213
3214 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3215 : leakWithinFunction);
3216 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003217 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3218 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003219 BR->EmitReport(report);
3220 }
Ted Kremenek708af042009-02-05 06:50:21 +00003221
Ted Kremenek876d8df2009-02-19 23:47:02 +00003222 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003223 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003224
3225 // Now generate a new node that nukes the old bindings.
3226 GRStateRef state(St, Eng.getStateManager());
3227 RefBindings::Factory& F = state.get_context<RefBindings>();
3228
3229 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3230 E = SymReaper.dead_end(); I!=E; ++I)
3231 B = F.Remove(B, *I);
3232
3233 state = state.set<RefBindings>(B);
3234 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003235}
3236
3237void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3238 GRStmtNodeBuilder<GRState>& Builder,
3239 Expr* NodeExpr, Expr* ErrorExpr,
3240 ExplodedNode<GRState>* Pred,
3241 const GRState* St,
3242 RefVal::Kind hasErr, SymbolRef Sym) {
3243 Builder.BuildSinks = true;
3244 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3245
3246 if (!N) return;
3247
3248 CFRefBug *BT = 0;
3249
Ted Kremenek6537a642009-03-17 19:42:23 +00003250 switch (hasErr) {
3251 default:
3252 assert(false && "Unhandled error.");
3253 return;
3254 case RefVal::ErrorUseAfterRelease:
3255 BT = static_cast<CFRefBug*>(useAfterRelease);
3256 break;
3257 case RefVal::ErrorReleaseNotOwned:
3258 BT = static_cast<CFRefBug*>(releaseNotOwned);
3259 break;
3260 case RefVal::ErrorDeallocGC:
3261 BT = static_cast<CFRefBug*>(deallocGC);
3262 break;
3263 case RefVal::ErrorDeallocNotOwned:
3264 BT = static_cast<CFRefBug*>(deallocNotOwned);
3265 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003266 }
3267
Ted Kremenekc26c4692009-02-18 03:48:14 +00003268 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003269 report->addRange(ErrorExpr->getSourceRange());
3270 BR->EmitReport(report);
3271}
3272
3273//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003274// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003275//===----------------------------------------------------------------------===//
3276
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003277GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3278 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003279 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003280}