blob: 7cf69e13a28e3de19a52fb1acfca4aa1cc6cc4ac [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 Kremenek286e9852009-05-04 04:57:00 +0000588 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000589 RetainSummary* StopSummary;
590
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000591 //==-----------------------------------------------------------------==//
592 // Methods.
593 //==-----------------------------------------------------------------==//
594
Ted Kremenek272aa852008-06-25 21:21:56 +0000595 /// getArgEffects - Returns a persistent ArgEffects object based on the
596 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000597 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000598
Ted Kremenek562c1302008-05-05 16:51:50 +0000599 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000600
601public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000602 RetainSummary *getDefaultSummary() {
603 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
604 return new (Summ) RetainSummary(DefaultSummary);
605 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000606
Ted Kremenek064ef322009-02-23 16:51:39 +0000607 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000608
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000609 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
610 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000611 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000612
Ted Kremeneka56ae162009-05-03 05:20:50 +0000613 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000614 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000615 ArgEffect DefaultEff = MayEscape,
616 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000617
Ted Kremenek266d8b62008-05-06 02:26:56 +0000618 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000619 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000620 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000621 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000622 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000623
Ted Kremeneka821b792009-04-29 05:04:30 +0000624 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000625 if (StopSummary)
626 return StopSummary;
627
628 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
629 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000630
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000631 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000632 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000633
Ted Kremeneka821b792009-04-29 05:04:30 +0000634 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000635
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000636 void InitializeClassMethodSummaries();
637 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000638
Ted Kremenek9b42e062009-05-03 04:42:10 +0000639 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000640 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000641
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000642private:
643
Ted Kremenekf2717b02008-07-18 17:24:20 +0000644 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
645 RetainSummary* Summ) {
646 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
647 }
648
Ted Kremenek272aa852008-06-25 21:21:56 +0000649 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
650 ObjCClassMethodSummaries[S] = Summ;
651 }
652
653 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
654 ObjCMethodSummaries[S] = Summ;
655 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000656
657 void addClassMethSummary(const char* Cls, const char* nullaryName,
658 RetainSummary *Summ) {
659 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
660 Selector S = GetNullarySelector(nullaryName, Ctx);
661 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
662 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000663
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000664 void addInstMethSummary(const char* Cls, const char* nullaryName,
665 RetainSummary *Summ) {
666 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
667 Selector S = GetNullarySelector(nullaryName, Ctx);
668 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
669 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000670
671 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000672 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000673
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000674 while (const char* s = va_arg(argp, const char*))
675 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000676
677 return Ctx.Selectors.getSelector(II.size(), &II[0]);
678 }
679
680 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
681 RetainSummary* Summ, va_list argp) {
682 Selector S = generateSelector(argp);
683 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000684 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000685
686 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
687 va_list argp;
688 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000689 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000690 va_end(argp);
691 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000692
693 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
694 va_list argp;
695 va_start(argp, Summ);
696 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
697 va_end(argp);
698 }
699
700 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
701 va_list argp;
702 va_start(argp, Summ);
703 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
704 va_end(argp);
705 }
706
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000707 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000708 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
709 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000710 DoNothing, DoNothing, true);
711 va_list argp;
712 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000713 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000714 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000715 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000716
Ted Kremeneka7338b42008-03-11 06:39:11 +0000717public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000718
719 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000720 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000721 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000722 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek286e9852009-05-04 04:57:00 +0000723 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
724 RetEffect::MakeNoRet() /* return effect */,
725 DoNothing /* receiver effect */,
726 MayEscape /* default argument effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000727 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000728
729 InitializeClassMethodSummaries();
730 InitializeMethodSummaries();
731 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000732
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000733 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000734
Ted Kremenekd13c1872008-06-24 03:56:45 +0000735 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000736
Ted Kremenek314b1952009-04-29 23:03:22 +0000737 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
738 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000739 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000740 ID, ME->getMethodDecl(), ME->getType());
741 }
742
Ted Kremenek04e00302009-04-29 17:09:14 +0000743 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000744 const ObjCInterfaceDecl* ID,
745 const ObjCMethodDecl *MD,
746 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000747
748 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000749 const ObjCInterfaceDecl *ID,
750 const ObjCMethodDecl *MD,
751 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000752
753 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
754 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
755 ME->getClassInfo().first,
756 ME->getMethodDecl(), ME->getType());
757 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000758
759 /// getMethodSummary - This version of getMethodSummary is used to query
760 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000761 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
762 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000763 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000764 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000765 IdentifierInfo *ClsName = ID->getIdentifier();
766 QualType ResultTy = MD->getResultType();
767
Ted Kremenek81eb4642009-04-30 05:47:23 +0000768 // Resolve the method decl last.
769 if (const ObjCMethodDecl *InterfaceMD =
770 ResolveToInterfaceMethodDecl(MD, Ctx))
771 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000772
Ted Kremenek91b89a42009-04-29 17:17:48 +0000773 if (MD->isInstanceMethod())
774 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
775 else
776 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
777 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000778
Ted Kremenek314b1952009-04-29 23:03:22 +0000779 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
780 Selector S, QualType RetTy);
781
Ted Kremenek03d242e2009-05-05 18:44:20 +0000782 void updateSummaryArgEffFromAnnotations(RetainSummary &Summ, const Decl *D,
783 unsigned argIdx = 0);
Ted Kremenekb88734c2009-05-04 15:40:58 +0000784
Ted Kremenek2f226732009-05-04 05:31:22 +0000785 void updateSummaryFromAnnotations(RetainSummary &Summ,
786 const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000787
Ted Kremenekf5b44c62009-05-04 16:43:50 +0000788 void updateSummaryFromAnnotations(RetainSummary &Summ,
789 const FunctionDecl *FD);
790
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000791 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000792
793 RetainSummary *copySummary(RetainSummary *OldSumm) {
794 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
795 new (Summ) RetainSummary(*OldSumm);
796 return Summ;
797 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000798};
799
800} // end anonymous namespace
801
802//===----------------------------------------------------------------------===//
803// Implementation of checker data structures.
804//===----------------------------------------------------------------------===//
805
Ted Kremeneka56ae162009-05-03 05:20:50 +0000806RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000807
Ted Kremeneka56ae162009-05-03 05:20:50 +0000808ArgEffects RetainSummaryManager::getArgEffects() {
809 ArgEffects AE = ScratchArgs;
810 ScratchArgs = AF.GetEmptyMap();
811 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000812}
813
Ted Kremenek266d8b62008-05-06 02:26:56 +0000814RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000815RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000816 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000817 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000818 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000819 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000820 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000821 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000822 return Summ;
823}
824
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000825//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000826// Predicates.
827//===----------------------------------------------------------------------===//
828
Ted Kremenek9b42e062009-05-03 04:42:10 +0000829bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000830 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000831 return false;
832
Ted Kremenek0d813552009-04-23 22:11:07 +0000833 // We assume that id<..>, id, and "Class" all represent tracked objects.
834 const PointerType *PT = Ty->getAsPointerType();
835 if (PT == 0)
836 return true;
837
838 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000839
840 // We assume that id<..>, id, and "Class" all represent tracked objects.
841 if (!OT)
842 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000843
844 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000845 // FIXME: We can memoize here if this gets too expensive.
846 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
847 ObjCInterfaceDecl* ID = OT->getDecl();
848
849 for ( ; ID ; ID = ID->getSuperClass())
850 if (ID->getIdentifier() == NSObjectII)
851 return true;
852
853 return false;
854}
855
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000856bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
857 return isRefType(T, "CF") || // Core Foundation.
858 isRefType(T, "CG") || // Core Graphics.
859 isRefType(T, "DADisk") || // Disk Arbitration API.
860 isRefType(T, "DADissenter") ||
861 isRefType(T, "DASessionRef");
862}
863
Ted Kremenek35920ed2009-01-07 00:39:56 +0000864//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000865// Summary creation for functions (largely uses of Core Foundation).
866//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000867
Ted Kremenek17144e82009-01-12 21:45:02 +0000868static bool isRetain(FunctionDecl* FD, const char* FName) {
869 const char* loc = strstr(FName, "Retain");
870 return loc && loc[sizeof("Retain")-1] == '\0';
871}
872
873static bool isRelease(FunctionDecl* FD, const char* FName) {
874 const char* loc = strstr(FName, "Release");
875 return loc && loc[sizeof("Release")-1] == '\0';
876}
877
Ted Kremenekd13c1872008-06-24 03:56:45 +0000878RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000879 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000880 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000881 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000882 return I->second;
883
Ted Kremenek64cddf12009-05-04 15:34:07 +0000884 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000885 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000886
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000887 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000888 // We generate "stop" summaries for implicitly defined functions.
889 if (FD->isImplicit()) {
890 S = getPersistentStopSummary();
891 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000892 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000893
Ted Kremenek064ef322009-02-23 16:51:39 +0000894 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000895 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000896 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000897 const char* FName = FD->getIdentifier()->getName();
898
Ted Kremenek38c6f022009-03-05 22:11:14 +0000899 // Strip away preceding '_'. Doing this here will effect all the checks
900 // down below.
901 while (*FName == '_') ++FName;
902
Ted Kremenek17144e82009-01-12 21:45:02 +0000903 // Inspect the result type.
904 QualType RetTy = FT->getResultType();
905
906 // FIXME: This should all be refactored into a chain of "summary lookup"
907 // filters.
908 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
909 // FIXES: <rdar://problem/6326900>
910 // This should be addressed using a API table. This strcmp is also
911 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000912 assert (ScratchArgs.isEmpty());
913 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000914 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
915 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000916 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000917
918 // Enable this code once the semantics of NSDeallocateObject are resolved
919 // for GC. <rdar://problem/6619988>
920#if 0
921 // Handle: NSDeallocateObject(id anObject);
922 // This method does allow 'nil' (although we don't check it now).
923 if (strcmp(FName, "NSDeallocateObject") == 0) {
924 return RetTy == Ctx.VoidTy
925 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
926 : getPersistentStopSummary();
927 }
928#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000929
930 // Handle: id NSMakeCollectable(CFTypeRef)
931 if (strcmp(FName, "NSMakeCollectable") == 0) {
932 S = (RetTy == Ctx.getObjCIdType())
933 ? getUnarySummary(FT, cfmakecollectable)
934 : getPersistentStopSummary();
935
936 break;
937 }
938
939 if (RetTy->isPointerType()) {
940 // For CoreFoundation ('CF') types.
941 if (isRefType(RetTy, "CF", &Ctx, FName)) {
942 if (isRetain(FD, FName))
943 S = getUnarySummary(FT, cfretain);
944 else if (strstr(FName, "MakeCollectable"))
945 S = getUnarySummary(FT, cfmakecollectable);
946 else
947 S = getCFCreateGetRuleSummary(FD, FName);
948
949 break;
950 }
951
952 // For CoreGraphics ('CG') types.
953 if (isRefType(RetTy, "CG", &Ctx, FName)) {
954 if (isRetain(FD, FName))
955 S = getUnarySummary(FT, cfretain);
956 else
957 S = getCFCreateGetRuleSummary(FD, FName);
958
959 break;
960 }
961
962 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
963 if (isRefType(RetTy, "DADisk") ||
964 isRefType(RetTy, "DADissenter") ||
965 isRefType(RetTy, "DASessionRef")) {
966 S = getCFCreateGetRuleSummary(FD, FName);
967 break;
968 }
969
970 break;
971 }
972
973 // Check for release functions, the only kind of functions that we care
974 // about that don't return a pointer type.
975 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000976 // Test for 'CGCF'.
977 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
978 FName += 4;
979 else
980 FName += 2;
981
982 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000983 S = getUnarySummary(FT, cfrelease);
984 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000985 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +0000986 // Remaining CoreFoundation and CoreGraphics functions.
987 // We use to assume that they all strictly followed the ownership idiom
988 // and that ownership cannot be transferred. While this is technically
989 // correct, many methods allow a tracked object to escape. For example:
990 //
991 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
992 // CFDictionaryAddValue(y, key, x);
993 // CFRelease(x);
994 // ... it is okay to use 'x' since 'y' has a reference to it
995 //
996 // We handle this and similar cases with the follow heuristic. If the
997 // function name contains "InsertValue", "SetValue" or "AddValue" then
998 // we assume that arguments may "escape."
999 //
1000 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1001 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001002 CStrInCStrNoCase(FName, "SetValue") ||
1003 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001004 ? MayEscape : DoNothing;
1005
1006 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001007 }
1008 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001009 }
1010 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001011
1012 if (!S)
1013 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001014
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001015 // Annotations override defaults.
1016 assert(S);
1017 updateSummaryFromAnnotations(*S, FD);
1018
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001019 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001020 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001021}
1022
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001023RetainSummary*
1024RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1025 const char* FName) {
1026
Ted Kremenek562c1302008-05-05 16:51:50 +00001027 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1028 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001029
Ted Kremenek562c1302008-05-05 16:51:50 +00001030 if (strstr(FName, "Get"))
1031 return getCFSummaryGetRule(FD);
1032
Ted Kremenek286e9852009-05-04 04:57:00 +00001033 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001034}
1035
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001036RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001037RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1038 UnaryFuncKind func) {
1039
Ted Kremenek17144e82009-01-12 21:45:02 +00001040 // Sanity check that this is *really* a unary function. This can
1041 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001042 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001043 if (!FTP || FTP->getNumArgs() != 1)
1044 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001045
Ted Kremeneka56ae162009-05-03 05:20:50 +00001046 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001047
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001048 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001049 case cfretain: {
1050 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001051 return getPersistentSummary(RetEffect::MakeAlias(0),
1052 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001053 }
1054
1055 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001056 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001057 return getPersistentSummary(RetEffect::MakeNoRet(),
1058 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001059 }
1060
1061 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001062 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001063 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001064 }
1065
1066 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001067 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001068 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001069 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001070}
1071
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001072RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001073 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001074
1075 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001076 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1077 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001078 }
1079
Ted Kremenek68621b92009-01-28 05:56:51 +00001080 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001081}
1082
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001083RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001084 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001085 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1086 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001087}
1088
Ted Kremeneka7338b42008-03-11 06:39:11 +00001089//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001090// Summary creation for Selectors.
1091//===----------------------------------------------------------------------===//
1092
Ted Kremenekbcaff792008-05-06 15:44:25 +00001093RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001094RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001095 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001096
Ted Kremenek802cfc72009-02-20 00:05:35 +00001097 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001098 return getPersistentSummary(Loc::IsLocType(RetTy)
1099 ? RetEffect::MakeReceiverAlias()
Ted Kremenek03d242e2009-05-05 18:44:20 +00001100 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001101}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001102
Ted Kremenek2f226732009-05-04 05:31:22 +00001103void
Ted Kremenekb88734c2009-05-04 15:40:58 +00001104RetainSummaryManager::updateSummaryArgEffFromAnnotations(RetainSummary &Summ,
Ted Kremenek03d242e2009-05-05 18:44:20 +00001105 const Decl *D,
1106 unsigned i) {
1107 ArgEffect E = DoNothing;
1108
1109 if (D->getAttr<NSOwnershipRetainAttr>())
1110 E = IncRefMsg;
1111 else if (D->getAttr<CFOwnershipRetainAttr>())
1112 E = IncRef;
1113 else if (D->getAttr<NSOwnershipReleaseAttr>())
1114 E = DecRefMsg;
1115 else if (D->getAttr<CFOwnershipReleaseAttr>())
1116 E = DecRef;
1117 else if (D->getAttr<NSOwnershipAutoreleaseAttr>())
1118 E = Autorelease;
1119 else
1120 return;
1121
1122 if (isa<ParmVarDecl>(D))
1123 Summ.setArgEffect(AF, i, E);
1124 else
1125 Summ.setReceiverEffect(E);
Ted Kremenekb88734c2009-05-04 15:40:58 +00001126}
1127
1128void
Ted Kremenek2f226732009-05-04 05:31:22 +00001129RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001130 const FunctionDecl *FD) {
1131 if (!FD)
1132 return;
1133
1134 // Determine if there is a special return effect for this method.
1135 if (isTrackedObjCObjectType(FD->getResultType())) {
Ted Kremenek028e8112009-05-04 19:10:19 +00001136 if (FD->getAttr<NSOwnershipReturnsAttr>()) {
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001137 Summ.setRetEffect(isGCEnabled()
1138 ? RetEffect::MakeGCNotOwned()
1139 : RetEffect::MakeOwned(RetEffect::ObjC, true));
1140 }
Ted Kremenekfed3c092009-05-05 00:46:09 +00001141 else if (FD->getAttr<CFOwnershipReturnsAttr>()) {
1142 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1143 }
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001144 }
1145
1146 // Determine if there are any arguments with a specific ArgEffect.
1147 unsigned i = 0;
1148 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1149 E = FD->param_end(); I != E; ++I, ++i)
Ted Kremenek03d242e2009-05-05 18:44:20 +00001150 updateSummaryArgEffFromAnnotations(Summ, *I, i);
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001151}
1152
1153void
1154RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
Ted Kremenek2f226732009-05-04 05:31:22 +00001155 const ObjCMethodDecl *MD) {
Ted Kremenek923fc392009-04-24 23:32:32 +00001156 if (!MD)
Ted Kremenek2f226732009-05-04 05:31:22 +00001157 return;
Ted Kremenek923fc392009-04-24 23:32:32 +00001158
1159 // Determine if there is a special return effect for this method.
Ted Kremenek9b42e062009-05-03 04:42:10 +00001160 if (isTrackedObjCObjectType(MD->getResultType())) {
Ted Kremenek028e8112009-05-04 19:10:19 +00001161 if (MD->getAttr<NSOwnershipReturnsAttr>()) {
Ted Kremenek2f226732009-05-04 05:31:22 +00001162 Summ.setRetEffect(isGCEnabled()
1163 ? RetEffect::MakeGCNotOwned()
1164 : RetEffect::MakeOwned(RetEffect::ObjC, true));
Ted Kremenek923fc392009-04-24 23:32:32 +00001165 }
Ted Kremenekfed3c092009-05-05 00:46:09 +00001166 else if (MD->getAttr<CFOwnershipReturnsAttr>()) {
1167 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1168 }
Ted Kremenek923fc392009-04-24 23:32:32 +00001169 }
1170
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001171 // Determine if there are any arguments with a specific ArgEffect.
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001172 unsigned i = 0;
1173 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
Ted Kremenekb88734c2009-05-04 15:40:58 +00001174 E = MD->param_end(); I != E; ++I, ++i)
Ted Kremenek03d242e2009-05-05 18:44:20 +00001175 updateSummaryArgEffFromAnnotations(Summ, *I, i);
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001176
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001177 // Determine any effects on the receiver.
Ted Kremenek03d242e2009-05-05 18:44:20 +00001178 updateSummaryArgEffFromAnnotations(Summ, MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001179}
Ted Kremenek272aa852008-06-25 21:21:56 +00001180
Ted Kremenekbcaff792008-05-06 15:44:25 +00001181RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001182RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1183 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001184
Ted Kremenek578498a2009-04-29 00:42:39 +00001185 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001186 // Scan the method decl for 'void*' arguments. These should be treated
1187 // as 'StopTracking' because they are often used with delegates.
1188 // Delegates are a frequent form of false positives with the retain
1189 // count checker.
1190 unsigned i = 0;
1191 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1192 E = MD->param_end(); I != E; ++I, ++i)
1193 if (ParmVarDecl *PD = *I) {
1194 QualType Ty = Ctx.getCanonicalType(PD->getType());
1195 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001196 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001197 }
1198 }
1199
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001200 // Any special effect for the receiver?
1201 ArgEffect ReceiverEff = DoNothing;
1202
1203 // If one of the arguments in the selector has the keyword 'delegate' we
1204 // should stop tracking the reference count for the receiver. This is
1205 // because the reference count is quite possibly handled by a delegate
1206 // method.
1207 if (S.isKeywordSelector()) {
1208 const std::string &str = S.getAsString();
1209 assert(!str.empty());
1210 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1211 }
1212
Ted Kremenek174a0772009-04-23 23:08:22 +00001213 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001214 if (isTrackedObjCObjectType(RetTy)) {
1215 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1216 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001217 RetEffect E =
1218 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1219 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
1220 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1221 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1222
1223 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001224 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001225
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001226 // Look for methods that return an owned core foundation object.
1227 if (isTrackedCFObjectType(RetTy)) {
1228 RetEffect E =
1229 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1230 ? RetEffect::MakeOwned(RetEffect::CF, true)
1231 : RetEffect::MakeNotOwned(RetEffect::CF);
1232
1233 return getPersistentSummary(E, ReceiverEff, MayEscape);
1234 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001235
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001236 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001237 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001238
Ted Kremenek2f226732009-05-04 05:31:22 +00001239 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001240}
1241
1242RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001243RetainSummaryManager::getInstanceMethodSummary(Selector S,
1244 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001245 const ObjCInterfaceDecl* ID,
1246 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001247 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001248
Ted Kremeneka821b792009-04-29 05:04:30 +00001249 // Look up a summary in our summary cache.
1250 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001251
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001252 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001253 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001254
Ted Kremeneka56ae162009-05-03 05:20:50 +00001255 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001256 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001257
Ted Kremenek2f226732009-05-04 05:31:22 +00001258 // "initXXX": pass-through for receiver.
1259 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1260 == InitRule)
1261 Summ = getInitMethodSummary(RetTy);
1262 else
1263 Summ = getCommonMethodSummary(MD, S, RetTy);
1264
1265 // Annotations override defaults.
1266 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001267
Ted Kremenek2f226732009-05-04 05:31:22 +00001268 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001269 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001270 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001271}
1272
Ted Kremeneka7722b72008-05-06 21:26:51 +00001273RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001274RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001275 const ObjCInterfaceDecl *ID,
1276 const ObjCMethodDecl *MD,
1277 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001278
Ted Kremenek578498a2009-04-29 00:42:39 +00001279 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001280 ObjCMethodSummariesTy::iterator I =
1281 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001282
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001283 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001284 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001285
1286 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
1287
1288 // Annotations override defaults.
1289 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001290
Ted Kremenek2f226732009-05-04 05:31:22 +00001291 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001292 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001293 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001294}
1295
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001296void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001297
Ted Kremeneka56ae162009-05-03 05:20:50 +00001298 assert (ScratchArgs.isEmpty());
Ted Kremenek0e344d42008-05-06 00:30:21 +00001299
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001300 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001301 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001302
Ted Kremenek0e344d42008-05-06 00:30:21 +00001303 RetainSummary* Summ = getPersistentSummary(E);
1304
Ted Kremenek272aa852008-06-25 21:21:56 +00001305 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1306 // NSObject and its derivatives.
1307 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1308 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1309 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001310
1311 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001312 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001313 GetNullarySelector("currentHandler", Ctx),
1314 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001315
1316 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001317 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001318 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1319 GetUnarySelector("addObject", Ctx),
1320 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001321 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001322
1323 // Create the summaries for [NSObject performSelector...]. We treat
1324 // these as 'stop tracking' for the arguments because they are often
1325 // used for delegates that can release the object. When we have better
1326 // inter-procedural analysis we can potentially do something better. This
1327 // workaround is to remove false positives.
1328 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1329 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1330 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1331 "afterDelay", NULL);
1332 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1333 "afterDelay", "inModes", NULL);
1334 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1335 "withObject", "waitUntilDone", NULL);
1336 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1337 "withObject", "waitUntilDone", "modes", NULL);
1338 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1339 "withObject", "waitUntilDone", NULL);
1340 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1341 "withObject", "waitUntilDone", "modes", NULL);
1342 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1343 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001344}
1345
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001346void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001347
Ted Kremeneka56ae162009-05-03 05:20:50 +00001348 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001349
Ted Kremeneka7722b72008-05-06 21:26:51 +00001350 // Create the "init" selector. It just acts as a pass-through for the
1351 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001352 RetainSummary* InitSumm =
1353 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001354 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001355
1356 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001357 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001358 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001359
Ted Kremeneke44927e2008-07-01 17:21:27 +00001360 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001361
1362 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001363 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1364
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001365 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001366 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001367
Ted Kremenek266d8b62008-05-06 02:26:56 +00001368 // Create the "retain" selector.
1369 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001370 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001371 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001372
1373 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001374 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001375 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001376
1377 // Create the "drain" selector.
1378 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001379 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001380
1381 // Create the -dealloc summary.
1382 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1383 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001384
1385 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001386 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001387 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001388
Ted Kremenekaac82832009-02-23 17:45:03 +00001389 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001390 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001391 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001392 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001393
Ted Kremenek45642a42008-08-12 18:48:50 +00001394 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001395 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1396 // self-own themselves. However, they only do this once they are displayed.
1397 // Thus, we need to track an NSWindow's display status.
1398 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001399 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001400 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1401
1402 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1403
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001404
1405#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001406 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001407 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001408
1409 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1410 "styleMask", "backing", "defer", NULL);
1411
1412 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1413 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001414#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001415
1416 // For NSPanel (which subclasses NSWindow), allocated objects are not
1417 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001418 // FIXME: For now we don't track NSPanels. object for the same reason
1419 // as for NSWindow objects.
1420 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1421
Ted Kremenek45642a42008-08-12 18:48:50 +00001422 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1423 "styleMask", "backing", "defer", NULL);
1424
1425 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1426 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001427
Ted Kremenekf2717b02008-07-18 17:24:20 +00001428 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001429 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1430 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001431
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001432 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1433 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001434}
1435
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001436//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001437// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001438//===----------------------------------------------------------------------===//
1439
Ted Kremeneka7338b42008-03-11 06:39:11 +00001440namespace {
1441
Ted Kremenek7d421f32008-04-09 23:49:11 +00001442class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001443public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001444 enum Kind {
1445 Owned = 0, // Owning reference.
1446 NotOwned, // Reference is not owned by still valid (not freed).
1447 Released, // Object has been released.
1448 ReturnedOwned, // Returned object passes ownership to caller.
1449 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001450 ERROR_START,
1451 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1452 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001453 ErrorUseAfterRelease, // Object used after released.
1454 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001455 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001456 ErrorLeak, // A memory leak due to excessive reference counts.
1457 ErrorLeakReturned // A memory leak due to the returning method not having
1458 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001459 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001460
1461private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001462 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001463 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001464 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001465 QualType T;
1466
Ted Kremenek68621b92009-01-28 05:56:51 +00001467 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1468 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001469
Ted Kremenek68621b92009-01-28 05:56:51 +00001470 RefVal(Kind k, unsigned cnt = 0)
1471 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1472
1473public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001474 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001475
1476 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001477
Ted Kremenek6537a642009-03-17 19:42:23 +00001478 unsigned getCount() const { return Cnt; }
1479 void clearCounts() { Cnt = 0; }
1480
Ted Kremenek272aa852008-06-25 21:21:56 +00001481 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001482
1483 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001484
Ted Kremenek6537a642009-03-17 19:42:23 +00001485 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001486
Ted Kremenek6537a642009-03-17 19:42:23 +00001487 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001488
Ted Kremenekffefc352008-04-11 22:25:11 +00001489 bool isOwned() const {
1490 return getKind() == Owned;
1491 }
1492
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001493 bool isNotOwned() const {
1494 return getKind() == NotOwned;
1495 }
1496
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001497 bool isReturnedOwned() const {
1498 return getKind() == ReturnedOwned;
1499 }
1500
1501 bool isReturnedNotOwned() const {
1502 return getKind() == ReturnedNotOwned;
1503 }
1504
1505 bool isNonLeakError() const {
1506 Kind k = getKind();
1507 return isError(k) && !isLeak(k);
1508 }
1509
Ted Kremenek68621b92009-01-28 05:56:51 +00001510 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1511 unsigned Count = 1) {
1512 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001513 }
1514
Ted Kremenek68621b92009-01-28 05:56:51 +00001515 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1516 unsigned Count = 0) {
1517 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001518 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001519
1520 static RefVal makeReturnedOwned(unsigned Count) {
1521 return RefVal(ReturnedOwned, Count);
1522 }
1523
1524 static RefVal makeReturnedNotOwned() {
1525 return RefVal(ReturnedNotOwned);
1526 }
1527
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001528 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001529
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001530 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001531 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001532 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001533
Ted Kremenek272aa852008-06-25 21:21:56 +00001534 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001535 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001536 }
1537
1538 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001539 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001540 }
1541
1542 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001543 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001544 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001545
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001546 void Profile(llvm::FoldingSetNodeID& ID) const {
1547 ID.AddInteger((unsigned) kind);
1548 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001549 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001550 }
1551
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001552 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001553};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001554
1555void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001556 if (!T.isNull())
1557 Out << "Tracked Type:" << T.getAsString() << '\n';
1558
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001559 switch (getKind()) {
1560 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001561 case Owned: {
1562 Out << "Owned";
1563 unsigned cnt = getCount();
1564 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001565 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001566 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001567
Ted Kremenekc4f81022008-04-10 23:09:18 +00001568 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001569 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001570 unsigned cnt = getCount();
1571 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001572 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001573 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001574
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001575 case ReturnedOwned: {
1576 Out << "ReturnedOwned";
1577 unsigned cnt = getCount();
1578 if (cnt) Out << " (+ " << cnt << ")";
1579 break;
1580 }
1581
1582 case ReturnedNotOwned: {
1583 Out << "ReturnedNotOwned";
1584 unsigned cnt = getCount();
1585 if (cnt) Out << " (+ " << cnt << ")";
1586 break;
1587 }
1588
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001589 case Released:
1590 Out << "Released";
1591 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001592
1593 case ErrorDeallocGC:
1594 Out << "-dealloc (GC)";
1595 break;
1596
1597 case ErrorDeallocNotOwned:
1598 Out << "-dealloc (not-owned)";
1599 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001600
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001601 case ErrorLeak:
1602 Out << "Leaked";
1603 break;
1604
Ted Kremenek311f3d42008-10-22 23:56:21 +00001605 case ErrorLeakReturned:
1606 Out << "Leaked (Bad naming)";
1607 break;
1608
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001609 case ErrorUseAfterRelease:
1610 Out << "Use-After-Release [ERROR]";
1611 break;
1612
1613 case ErrorReleaseNotOwned:
1614 Out << "Release of Not-Owned [ERROR]";
1615 break;
1616 }
1617}
Ted Kremenek0d721572008-03-11 17:48:22 +00001618
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001619} // end anonymous namespace
1620
1621//===----------------------------------------------------------------------===//
1622// RefBindings - State used to track object reference counts.
1623//===----------------------------------------------------------------------===//
1624
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001625typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001626static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001627static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001628
1629namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001630 template<>
1631 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1632 static inline void* GDMIndex() { return &RefBIndex; }
1633 };
1634}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001635
1636//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001637// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001638//===----------------------------------------------------------------------===//
1639
Ted Kremenekb6578942009-02-24 19:15:11 +00001640typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1641typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1642typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001643
Ted Kremenekb6578942009-02-24 19:15:11 +00001644static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001645static int AutoRBIndex = 0;
1646
Ted Kremenekb6578942009-02-24 19:15:11 +00001647namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001648namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001649
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001650namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001651template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001652 : public GRStatePartialTrait<ARStack> {
1653 static inline void* GDMIndex() { return &AutoRBIndex; }
1654};
1655
1656template<> struct GRStateTrait<AutoreleasePoolContents>
1657 : public GRStatePartialTrait<ARPoolContents> {
1658 static inline void* GDMIndex() { return &AutoRCIndex; }
1659};
1660} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001661
Ted Kremenek681fb352009-03-20 17:34:15 +00001662static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1663 ARStack stack = state->get<AutoreleaseStack>();
1664 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1665}
1666
1667static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1668 SymbolRef sym) {
1669
1670 SymbolRef pool = GetCurrentAutoreleasePool(state);
1671 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1672 ARCounts newCnts(0);
1673
1674 if (cnts) {
1675 const unsigned *cnt = (*cnts).lookup(sym);
1676 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1677 }
1678 else
1679 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1680
1681 return state.set<AutoreleasePoolContents>(pool, newCnts);
1682}
1683
Ted Kremenek7aef4842008-04-16 20:40:59 +00001684//===----------------------------------------------------------------------===//
1685// Transfer functions.
1686//===----------------------------------------------------------------------===//
1687
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001688namespace {
1689
Ted Kremenek7d421f32008-04-09 23:49:11 +00001690class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001691public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001692 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001693 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001694 virtual void Print(std::ostream& Out, const GRState* state,
1695 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001696 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001697
1698private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001699 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1700 SummaryLogTy;
1701
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001702 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001703 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001704 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001705 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001706
Ted Kremenek708af042009-02-05 06:50:21 +00001707 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001708 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001709 BugType *leakWithinFunction, *leakAtReturn;
1710 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001711
Ted Kremenekb6578942009-02-24 19:15:11 +00001712 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1713 RefVal::Kind& hasErr);
1714
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001715 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1716 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001717 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001718 ExplodedNode<GRState>* Pred,
1719 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001720 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001721
Ted Kremenek0106e202008-10-24 20:32:50 +00001722 std::pair<GRStateRef, bool>
1723 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001724 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001725
Ted Kremenekb6578942009-02-24 19:15:11 +00001726public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001727 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001728 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001729 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1730 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001731 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001732
Ted Kremenek708af042009-02-05 06:50:21 +00001733 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001734
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001735 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001736
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001737 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1738 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001739 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001740
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001741 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001742 const LangOptions& getLangOptions() const { return LOpts; }
1743
Ted Kremenekc26c4692009-02-18 03:48:14 +00001744 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1745 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1746 return I == SummaryLog.end() ? 0 : I->second;
1747 }
1748
Ted Kremeneka7338b42008-03-11 06:39:11 +00001749 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001750
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001751 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001752 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001753 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001754 Expr* Ex,
1755 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001756 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001757 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001758 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001759
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001760 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001761 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001762 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001763 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001764 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001765
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001766
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001767 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001768 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001769 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001770 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001771 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001772
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001773 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001774 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001775 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001776 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001777 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001778
Ted Kremeneka42be302009-02-14 01:43:44 +00001779 // Stores.
1780 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1781
Ted Kremenekffefc352008-04-11 22:25:11 +00001782 // End-of-path.
1783
1784 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001785 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001786
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001787 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001788 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001789 GRStmtNodeBuilder<GRState>& Builder,
1790 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001791 Stmt* S, const GRState* state,
1792 SymbolReaper& SymReaper);
1793
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001794 // Return statements.
1795
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001796 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001797 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001798 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001799 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001800 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001801
1802 // Assumptions.
1803
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001804 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001805 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001806 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001807};
1808
1809} // end anonymous namespace
1810
Ted Kremenek681fb352009-03-20 17:34:15 +00001811static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1812 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001813 if (Sym)
1814 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001815 else
1816 Out << "<pool>";
1817 Out << ":{";
1818
1819 // Get the contents of the pool.
1820 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1821 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1822 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1823
1824 Out << '}';
1825}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001826
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001827void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1828 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001829
1830
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001831
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001832 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001833
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001834 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001835 Out << sep << nl;
1836
1837 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1838 Out << (*I).first << " : ";
1839 (*I).second.print(Out);
1840 Out << nl;
1841 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001842
1843 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001844 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001845 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001846
Ted Kremenek681fb352009-03-20 17:34:15 +00001847 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1848 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1849 PrintPool(Out, *I, state);
1850
1851 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001852}
1853
Ted Kremenek47a72422009-04-29 18:50:19 +00001854//===----------------------------------------------------------------------===//
1855// Error reporting.
1856//===----------------------------------------------------------------------===//
1857
1858namespace {
1859
1860 //===-------------===//
1861 // Bug Descriptions. //
1862 //===-------------===//
1863
1864 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1865 protected:
1866 CFRefCount& TF;
1867
1868 CFRefBug(CFRefCount* tf, const char* name)
1869 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1870 public:
1871
1872 CFRefCount& getTF() { return TF; }
1873 const CFRefCount& getTF() const { return TF; }
1874
1875 // FIXME: Eventually remove.
1876 virtual const char* getDescription() const = 0;
1877
1878 virtual bool isLeak() const { return false; }
1879 };
1880
1881 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1882 public:
1883 UseAfterRelease(CFRefCount* tf)
1884 : CFRefBug(tf, "Use-after-release") {}
1885
1886 const char* getDescription() const {
1887 return "Reference-counted object is used after it is released";
1888 }
1889 };
1890
1891 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1892 public:
1893 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1894
1895 const char* getDescription() const {
1896 return "Incorrect decrement of the reference count of an "
1897 "object is not owned at this point by the caller";
1898 }
1899 };
1900
1901 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1902 public:
1903 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1904 "-dealloc called while using GC") {}
1905
1906 const char *getDescription() const {
1907 return "-dealloc called while using GC";
1908 }
1909 };
1910
1911 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1912 public:
1913 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1914 "-dealloc sent to non-exclusively owned object") {}
1915
1916 const char *getDescription() const {
1917 return "-dealloc sent to object that may be referenced elsewhere";
1918 }
1919 };
1920
1921 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1922 const bool isReturn;
1923 protected:
1924 Leak(CFRefCount* tf, const char* name, bool isRet)
1925 : CFRefBug(tf, name), isReturn(isRet) {}
1926 public:
1927
1928 const char* getDescription() const { return ""; }
1929
1930 bool isLeak() const { return true; }
1931 };
1932
1933 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1934 public:
1935 LeakAtReturn(CFRefCount* tf, const char* name)
1936 : Leak(tf, name, true) {}
1937 };
1938
1939 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1940 public:
1941 LeakWithinFunction(CFRefCount* tf, const char* name)
1942 : Leak(tf, name, false) {}
1943 };
1944
1945 //===---------===//
1946 // Bug Reports. //
1947 //===---------===//
1948
1949 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1950 protected:
1951 SymbolRef Sym;
1952 const CFRefCount &TF;
1953 public:
1954 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1955 ExplodedNode<GRState> *n, SymbolRef sym)
1956 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1957
1958 virtual ~CFRefReport() {}
1959
1960 CFRefBug& getBugType() {
1961 return (CFRefBug&) RangedBugReport::getBugType();
1962 }
1963 const CFRefBug& getBugType() const {
1964 return (const CFRefBug&) RangedBugReport::getBugType();
1965 }
1966
1967 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1968 const SourceRange*& end) {
1969
1970 if (!getBugType().isLeak())
1971 RangedBugReport::getRanges(BR, beg, end);
1972 else
1973 beg = end = 0;
1974 }
1975
1976 SymbolRef getSymbol() const { return Sym; }
1977
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001978 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001979 const ExplodedNode<GRState>* N);
1980
1981 std::pair<const char**,const char**> getExtraDescriptiveText();
1982
1983 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1984 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001985 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00001986 };
1987
1988 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1989 SourceLocation AllocSite;
1990 const MemRegion* AllocBinding;
1991 public:
1992 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1993 ExplodedNode<GRState> *n, SymbolRef sym,
1994 GRExprEngine& Eng);
1995
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001996 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001997 const ExplodedNode<GRState>* N);
1998
1999 SourceLocation getLocation() const { return AllocSite; }
2000 };
2001} // end anonymous namespace
2002
2003void CFRefCount::RegisterChecks(BugReporter& BR) {
2004 useAfterRelease = new UseAfterRelease(this);
2005 BR.Register(useAfterRelease);
2006
2007 releaseNotOwned = new BadRelease(this);
2008 BR.Register(releaseNotOwned);
2009
2010 deallocGC = new DeallocGC(this);
2011 BR.Register(deallocGC);
2012
2013 deallocNotOwned = new DeallocNotOwned(this);
2014 BR.Register(deallocNotOwned);
2015
2016 // First register "return" leaks.
2017 const char* name = 0;
2018
2019 if (isGCEnabled())
2020 name = "Leak of returned object when using garbage collection";
2021 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2022 name = "Leak of returned object when not using garbage collection (GC) in "
2023 "dual GC/non-GC code";
2024 else {
2025 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2026 name = "Leak of returned object";
2027 }
2028
2029 leakAtReturn = new LeakAtReturn(this, name);
2030 BR.Register(leakAtReturn);
2031
2032 // Second, register leaks within a function/method.
2033 if (isGCEnabled())
2034 name = "Leak of object when using garbage collection";
2035 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2036 name = "Leak of object when not using garbage collection (GC) in "
2037 "dual GC/non-GC code";
2038 else {
2039 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2040 name = "Leak";
2041 }
2042
2043 leakWithinFunction = new LeakWithinFunction(this, name);
2044 BR.Register(leakWithinFunction);
2045
2046 // Save the reference to the BugReporter.
2047 this->BR = &BR;
2048}
2049
2050static const char* Msgs[] = {
2051 // GC only
2052 "Code is compiled to only use garbage collection",
2053 // No GC.
2054 "Code is compiled to use reference counts",
2055 // Hybrid, with GC.
2056 "Code is compiled to use either garbage collection (GC) or reference counts"
2057 " (non-GC). The bug occurs with GC enabled",
2058 // Hybrid, without GC
2059 "Code is compiled to use either garbage collection (GC) or reference counts"
2060 " (non-GC). The bug occurs in non-GC mode"
2061};
2062
2063std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2064 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2065
2066 switch (TF.getLangOptions().getGCMode()) {
2067 default:
2068 assert(false);
2069
2070 case LangOptions::GCOnly:
2071 assert (TF.isGCEnabled());
2072 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2073
2074 case LangOptions::NonGC:
2075 assert (!TF.isGCEnabled());
2076 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2077
2078 case LangOptions::HybridGC:
2079 if (TF.isGCEnabled())
2080 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2081 else
2082 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2083 }
2084}
2085
2086static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2087 ArgEffect X) {
2088 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2089 I!=E; ++I)
2090 if (*I == X) return true;
2091
2092 return false;
2093}
2094
2095PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2096 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002097 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002098
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002099 // Check if the type state has changed.
2100 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002101 GRStateRef PrevSt(PrevN->getState(), StMgr);
2102 GRStateRef CurrSt(N->getState(), StMgr);
2103
2104 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2105 if (!CurrT) return NULL;
2106
2107 const RefVal& CurrV = *CurrT;
2108 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2109
2110 // Create a string buffer to constain all the useful things we want
2111 // to tell the user.
2112 std::string sbuf;
2113 llvm::raw_string_ostream os(sbuf);
2114
2115 // This is the allocation site since the previous node had no bindings
2116 // for this symbol.
2117 if (!PrevT) {
2118 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2119
2120 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2121 // Get the name of the callee (if it is available).
2122 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2123 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2124 os << "Call to function '" << FD->getNameAsString() <<'\'';
2125 else
2126 os << "function call";
2127 }
2128 else {
2129 assert (isa<ObjCMessageExpr>(S));
2130 os << "Method";
2131 }
2132
2133 if (CurrV.getObjKind() == RetEffect::CF) {
2134 os << " returns a Core Foundation object with a ";
2135 }
2136 else {
2137 assert (CurrV.getObjKind() == RetEffect::ObjC);
2138 os << " returns an Objective-C object with a ";
2139 }
2140
2141 if (CurrV.isOwned()) {
2142 os << "+1 retain count (owning reference).";
2143
2144 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2145 assert(CurrV.getObjKind() == RetEffect::CF);
2146 os << " "
2147 "Core Foundation objects are not automatically garbage collected.";
2148 }
2149 }
2150 else {
2151 assert (CurrV.isNotOwned());
2152 os << "+0 retain count (non-owning reference).";
2153 }
2154
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002155 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002156 return new PathDiagnosticEventPiece(Pos, os.str());
2157 }
2158
2159 // Gather up the effects that were performed on the object at this
2160 // program point
2161 llvm::SmallVector<ArgEffect, 2> AEffects;
2162
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002163 if (const RetainSummary *Summ =
2164 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002165 // We only have summaries attached to nodes after evaluating CallExpr and
2166 // ObjCMessageExprs.
2167 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2168
2169 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2170 // Iterate through the parameter expressions and see if the symbol
2171 // was ever passed as an argument.
2172 unsigned i = 0;
2173
2174 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2175 AI!=AE; ++AI, ++i) {
2176
2177 // Retrieve the value of the argument. Is it the symbol
2178 // we are interested in?
2179 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2180 continue;
2181
2182 // We have an argument. Get the effect!
2183 AEffects.push_back(Summ->getArg(i));
2184 }
2185 }
2186 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2187 if (Expr *receiver = ME->getReceiver())
2188 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2189 // The symbol we are tracking is the receiver.
2190 AEffects.push_back(Summ->getReceiverEffect());
2191 }
2192 }
2193 }
2194
2195 do {
2196 // Get the previous type state.
2197 RefVal PrevV = *PrevT;
2198
2199 // Specially handle -dealloc.
2200 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2201 // Determine if the object's reference count was pushed to zero.
2202 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2203 // We may not have transitioned to 'release' if we hit an error.
2204 // This case is handled elsewhere.
2205 if (CurrV.getKind() == RefVal::Released) {
2206 assert(CurrV.getCount() == 0);
2207 os << "Object released by directly sending the '-dealloc' message";
2208 break;
2209 }
2210 }
2211
2212 // Specially handle CFMakeCollectable and friends.
2213 if (contains(AEffects, MakeCollectable)) {
2214 // Get the name of the function.
2215 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2216 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2217 const FunctionDecl* FD = X.getAsFunctionDecl();
2218 const std::string& FName = FD->getNameAsString();
2219
2220 if (TF.isGCEnabled()) {
2221 // Determine if the object's reference count was pushed to zero.
2222 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2223
2224 os << "In GC mode a call to '" << FName
2225 << "' decrements an object's retain count and registers the "
2226 "object with the garbage collector. ";
2227
2228 if (CurrV.getKind() == RefVal::Released) {
2229 assert(CurrV.getCount() == 0);
2230 os << "Since it now has a 0 retain count the object can be "
2231 "automatically collected by the garbage collector.";
2232 }
2233 else
2234 os << "An object must have a 0 retain count to be garbage collected. "
2235 "After this call its retain count is +" << CurrV.getCount()
2236 << '.';
2237 }
2238 else
2239 os << "When GC is not enabled a call to '" << FName
2240 << "' has no effect on its argument.";
2241
2242 // Nothing more to say.
2243 break;
2244 }
2245
2246 // Determine if the typestate has changed.
2247 if (!(PrevV == CurrV))
2248 switch (CurrV.getKind()) {
2249 case RefVal::Owned:
2250 case RefVal::NotOwned:
2251
2252 if (PrevV.getCount() == CurrV.getCount())
2253 return 0;
2254
2255 if (PrevV.getCount() > CurrV.getCount())
2256 os << "Reference count decremented.";
2257 else
2258 os << "Reference count incremented.";
2259
2260 if (unsigned Count = CurrV.getCount())
2261 os << " The object now has a +" << Count << " retain count.";
2262
2263 if (PrevV.getKind() == RefVal::Released) {
2264 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2265 os << " The object is not eligible for garbage collection until the "
2266 "retain count reaches 0 again.";
2267 }
2268
2269 break;
2270
2271 case RefVal::Released:
2272 os << "Object released.";
2273 break;
2274
2275 case RefVal::ReturnedOwned:
2276 os << "Object returned to caller as an owning reference (single retain "
2277 "count transferred to caller).";
2278 break;
2279
2280 case RefVal::ReturnedNotOwned:
2281 os << "Object returned to caller with a +0 (non-owning) retain count.";
2282 break;
2283
2284 default:
2285 return NULL;
2286 }
2287
2288 // Emit any remaining diagnostics for the argument effects (if any).
2289 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2290 E=AEffects.end(); I != E; ++I) {
2291
2292 // A bunch of things have alternate behavior under GC.
2293 if (TF.isGCEnabled())
2294 switch (*I) {
2295 default: break;
2296 case Autorelease:
2297 os << "In GC mode an 'autorelease' has no effect.";
2298 continue;
2299 case IncRefMsg:
2300 os << "In GC mode the 'retain' message has no effect.";
2301 continue;
2302 case DecRefMsg:
2303 os << "In GC mode the 'release' message has no effect.";
2304 continue;
2305 }
2306 }
2307 } while(0);
2308
2309 if (os.str().empty())
2310 return 0; // We have nothing to say!
2311
2312 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002313 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002314 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2315
2316 // Add the range by scanning the children of the statement for any bindings
2317 // to Sym.
2318 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2319 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2320 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2321 P->addRange(Exp->getSourceRange());
2322 break;
2323 }
2324
2325 return P;
2326}
2327
2328namespace {
2329 class VISIBILITY_HIDDEN FindUniqueBinding :
2330 public StoreManager::BindingsHandler {
2331 SymbolRef Sym;
2332 const MemRegion* Binding;
2333 bool First;
2334
2335 public:
2336 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2337
2338 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2339 SVal val) {
2340
2341 SymbolRef SymV = val.getAsSymbol();
2342 if (!SymV || SymV != Sym)
2343 return true;
2344
2345 if (Binding) {
2346 First = false;
2347 return false;
2348 }
2349 else
2350 Binding = R;
2351
2352 return true;
2353 }
2354
2355 operator bool() { return First && Binding; }
2356 const MemRegion* getRegion() { return Binding; }
2357 };
2358}
2359
2360static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2361GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2362 SymbolRef Sym) {
2363
2364 // Find both first node that referred to the tracked symbol and the
2365 // memory location that value was store to.
2366 const ExplodedNode<GRState>* Last = N;
2367 const MemRegion* FirstBinding = 0;
2368
2369 while (N) {
2370 const GRState* St = N->getState();
2371 RefBindings B = St->get<RefBindings>();
2372
2373 if (!B.lookup(Sym))
2374 break;
2375
2376 FindUniqueBinding FB(Sym);
2377 StateMgr.iterBindings(St, FB);
2378 if (FB) FirstBinding = FB.getRegion();
2379
2380 Last = N;
2381 N = N->pred_empty() ? NULL : *(N->pred_begin());
2382 }
2383
2384 return std::make_pair(Last, FirstBinding);
2385}
2386
2387PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002388CFRefReport::getEndPath(BugReporterContext& BRC,
2389 const ExplodedNode<GRState>* EndN) {
2390 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002391 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002392 BRC.addNotableSymbol(Sym);
2393 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002394}
2395
2396PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002397CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2398 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002399
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002400 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002401 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002402 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002403
2404 // We are reporting a leak. Walk up the graph to get to the first node where
2405 // the symbol appeared, and also get the first VarDecl that tracked object
2406 // is stored to.
2407 const ExplodedNode<GRState>* AllocNode = 0;
2408 const MemRegion* FirstBinding = 0;
2409
2410 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002411 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002412
2413 // Get the allocate site.
2414 assert(AllocNode);
2415 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2416
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002417 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002418 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2419
2420 // Compute an actual location for the leak. Sometimes a leak doesn't
2421 // occur at an actual statement (e.g., transition between blocks; end
2422 // of function) so we need to walk the graph and compute a real location.
2423 const ExplodedNode<GRState>* LeakN = EndN;
2424 PathDiagnosticLocation L;
2425
2426 while (LeakN) {
2427 ProgramPoint P = LeakN->getLocation();
2428
2429 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2430 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2431 break;
2432 }
2433 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2434 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2435 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2436 break;
2437 }
2438 }
2439
2440 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2441 }
2442
2443 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002444 const Decl &D = BRC.getCodeDecl();
2445 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002446 }
2447
2448 std::string sbuf;
2449 llvm::raw_string_ostream os(sbuf);
2450
2451 os << "Object allocated on line " << AllocLine;
2452
2453 if (FirstBinding)
2454 os << " and stored into '" << FirstBinding->getString() << '\'';
2455
2456 // Get the retain count.
2457 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2458
2459 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2460 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2461 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2462 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002463 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002464 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002465 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002466 << "') does not contain 'copy' or otherwise starts with"
2467 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002468 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002469 }
2470 else
2471 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002472 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002473
2474 return new PathDiagnosticEventPiece(L, os.str());
2475}
2476
2477
2478CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2479 ExplodedNode<GRState> *n,
2480 SymbolRef sym, GRExprEngine& Eng)
2481: CFRefReport(D, tf, n, sym)
2482{
2483
2484 // Most bug reports are cached at the location where they occured.
2485 // With leaks, we want to unique them by the location where they were
2486 // allocated, and only report a single path. To do this, we need to find
2487 // the allocation site of a piece of tracked memory, which we do via a
2488 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2489 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2490 // that all ancestor nodes that represent the allocation site have the
2491 // same SourceLocation.
2492 const ExplodedNode<GRState>* AllocNode = 0;
2493
2494 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2495 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2496
2497 // Get the SourceLocation for the allocation site.
2498 ProgramPoint P = AllocNode->getLocation();
2499 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2500
2501 // Fill in the description of the bug.
2502 Description.clear();
2503 llvm::raw_string_ostream os(Description);
2504 SourceManager& SMgr = Eng.getContext().getSourceManager();
2505 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002506 os << "Potential leak ";
2507 if (tf.isGCEnabled()) {
2508 os << "(when using garbage collection) ";
2509 }
2510 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002511
2512 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2513 if (AllocBinding)
2514 os << " and stored into '" << AllocBinding->getString() << '\'';
2515}
2516
2517//===----------------------------------------------------------------------===//
2518// Main checker logic.
2519//===----------------------------------------------------------------------===//
2520
Ted Kremenek272aa852008-06-25 21:21:56 +00002521/// GetReturnType - Used to get the return type of a message expression or
2522/// function call with the intention of affixing that type to a tracked symbol.
2523/// While the the return type can be queried directly from RetEx, when
2524/// invoking class methods we augment to the return type to be that of
2525/// a pointer to the class (as opposed it just being id).
2526static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2527
2528 QualType RetTy = RetE->getType();
2529
2530 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002531 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002532 if (!PT)
2533 return RetTy;
2534
2535 // If RetEx is not a message expression just return its type.
2536 // If RetEx is a message expression, return its types if it is something
2537 /// more specific than id.
2538
2539 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2540
Steve Naroff17c03822009-02-12 17:52:19 +00002541 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002542 return RetTy;
2543
2544 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2545
2546 // At this point we know the return type of the message expression is id.
2547 // If we have an ObjCInterceDecl, we know this is a call to a class method
2548 // whose type we can resolve. In such cases, promote the return type to
2549 // Class*.
2550 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2551}
2552
2553
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002554void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002555 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002556 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002557 Expr* Ex,
2558 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002559 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002560 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002561 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002562
Ted Kremeneka7338b42008-03-11 06:39:11 +00002563 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002564 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002565 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002566
2567 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002568 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002569 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002570 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002571 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002572
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002573 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002574 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002575 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002576
Ted Kremenek74556a12009-03-26 03:35:11 +00002577 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002578 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002579 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002580 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002581 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002582 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002583 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002584 }
2585 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002586 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002587
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002588 if (isa<Loc>(V)) {
2589 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002590 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002591 continue;
2592
2593 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002594
2595 // FIXME: Either this logic should also be replicated in GRSimpleVals
2596 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002597
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002598 // FIXME: We can have collisions on the conjured symbol if the
2599 // expression *I also creates conjured symbols. We probably want
2600 // to identify conjured symbols by an expression pair: the enclosing
2601 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002602 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002603
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002604 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002605
Ted Kremenek73ec7732009-05-06 18:19:24 +00002606 if (R) {
2607 // Are we dealing with an ElementRegion? If the element type is
2608 // a basic integer type (e.g., char, int) and the underying region
2609 // is also typed then strip off the ElementRegion.
2610 // FIXME: We really need to think about this for the general case
2611 // as sometimes we are reasoning about arrays and other times
2612 // about (char*), etc., is just a form of passing raw bytes.
2613 // e.g., void *p = alloca(); foo((char*)p);
2614 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2615 // Checking for 'integral type' is probably too promiscuous, but
2616 // we'll leave it in for now until we have a systematic way of
2617 // handling all of these cases. Eventually we need to come up
2618 // with an interface to StoreManager so that this logic can be
2619 // approriately delegated to the respective StoreManagers while
2620 // still allowing us to do checker-specific logic (e.g.,
2621 // invalidating reference counts), probably via callbacks.
2622 if (ER->getElementType()->isIntegralType())
2623 if (const TypedRegion *superReg =
2624 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2625 R = superReg;
2626 // FIXME: What about layers of ElementRegions?
2627 }
2628
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002629 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002630 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002631
Ted Kremenek53b24182009-03-04 22:56:43 +00002632 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002633 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002634
Ted Kremenek53b24182009-03-04 22:56:43 +00002635 if (R->isBoundable(Ctx)) {
2636 // Set the value of the variable to be a conjured symbol.
2637 unsigned Count = Builder.getCurrentBlockCount();
2638 QualType T = R->getRValueType(Ctx);
2639
Zhongxing Xu079dc352009-04-09 06:03:54 +00002640 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002641 ValueManager &ValMgr = Eng.getValueManager();
2642 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002643 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002644 }
2645 else if (const RecordType *RT = T->getAsStructureType()) {
2646 // Handle structs in a not so awesome way. Here we just
2647 // eagerly bind new symbols to the fields. In reality we
2648 // should have the store manager handle this. The idea is just
2649 // to prototype some basic functionality here. All of this logic
2650 // should one day soon just go away.
2651 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2652
2653 // No record definition. There is nothing we can do.
2654 if (!RD)
2655 continue;
2656
2657 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2658
2659 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002660 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2661 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002662
2663 // For now just handle scalar fields.
2664 FieldDecl *FD = *FI;
2665 QualType FT = FD->getType();
2666
2667 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002668 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002669 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002670 ValueManager &ValMgr = Eng.getValueManager();
2671 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002672 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002673 }
2674 }
2675 }
2676 else {
2677 // Just blast away other values.
2678 state = state.BindLoc(*MR, UnknownVal());
2679 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002680 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002681 }
2682 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002683 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002684 }
2685 else {
2686 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002687 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002688 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002689 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002690 else if (isa<nonloc::LocAsInteger>(V))
2691 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002692 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002693
Ted Kremenek272aa852008-06-25 21:21:56 +00002694 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002695 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002696 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002697 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002698 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002699 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002700 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002701 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002702 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002703 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002704 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002705 }
2706 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002707
Ted Kremenek272aa852008-06-25 21:21:56 +00002708 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002709 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002710 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002711 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002712 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002713 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002714
Ted Kremenekf2717b02008-07-18 17:24:20 +00002715 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002716 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002717
2718 switch (RE.getKind()) {
2719 default:
2720 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002721
Ted Kremenek8f90e712008-10-17 22:23:12 +00002722 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002723
Ted Kremenek455dd862008-04-11 20:23:24 +00002724 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002725 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2726 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002727
Ted Kremenek8f90e712008-10-17 22:23:12 +00002728 // FIXME: We eventually should handle structs and other compound types
2729 // that are returned by value.
2730
2731 QualType T = Ex->getType();
2732
Ted Kremenek79413a52008-11-13 06:10:40 +00002733 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002734 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002735 ValueManager &ValMgr = Eng.getValueManager();
2736 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002737 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002738 }
2739
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002740 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002741 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002742
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002743 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002744 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002745 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002746 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002747 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002748 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002749 break;
2750 }
2751
Ted Kremenek227c5372008-05-06 02:41:27 +00002752 case RetEffect::ReceiverAlias: {
2753 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002754 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002755 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002756 break;
2757 }
2758
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002759 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002760 case RetEffect::OwnedSymbol: {
2761 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002762 ValueManager &ValMgr = Eng.getValueManager();
2763 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2764 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2765 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2766 RetT));
2767 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002768
2769 // FIXME: Add a flag to the checker where allocations are assumed to
2770 // *not fail.
2771#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002772 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2773 bool isFeasible;
2774 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2775 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2776 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002777#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002778
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002779 break;
2780 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002781
2782 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002783 case RetEffect::NotOwnedSymbol: {
2784 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002785 ValueManager &ValMgr = Eng.getValueManager();
2786 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2787 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2788 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2789 RetT));
2790 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002791 break;
2792 }
2793 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002794
Ted Kremenek0dd65012009-02-18 02:00:25 +00002795 // Generate a sink node if we are at the end of a path.
2796 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002797 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2798 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002799
2800 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002801 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002802}
2803
2804
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002805void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002806 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002807 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002808 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002809 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002810 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002811 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002812 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002813
Ted Kremenek286e9852009-05-04 04:57:00 +00002814 assert(Summ);
2815 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002816 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002817}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002818
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002819void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002820 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002821 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002822 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002823 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002824 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002825
Ted Kremenek272aa852008-06-25 21:21:56 +00002826 if (Expr* Receiver = ME->getReceiver()) {
2827 // We need the type-information of the tracked receiver object
2828 // Retrieve it from the state.
2829 ObjCInterfaceDecl* ID = 0;
2830
2831 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2832 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002833 // FIXME: Is this really working as expected? There are cases where
2834 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002835 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002836 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002837
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002838 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002839 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002840 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002841 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002842
2843 if (const PointerType* PT = Ty->getAsPointerType()) {
2844 QualType PointeeTy = PT->getPointeeType();
2845
2846 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2847 ID = IT->getDecl();
2848 }
2849 }
2850 }
2851
Ted Kremenek04e00302009-04-29 17:09:14 +00002852 // FIXME: The receiver could be a reference to a class, meaning that
2853 // we should use the class method.
2854 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002855
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002856 // Special-case: are we sending a mesage to "self"?
2857 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002858 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2859 if (Expr* Receiver = ME->getReceiver()) {
2860 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2861 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2862 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2863 // Update the summary to make the default argument effect
2864 // 'StopTracking'.
2865 Summ = Summaries.copySummary(Summ);
2866 Summ->setDefaultArgEffect(StopTracking);
2867 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002868 }
2869 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002870 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002871 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002872 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002873
Ted Kremenek286e9852009-05-04 04:57:00 +00002874 if (!Summ)
2875 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002876
Ted Kremenek286e9852009-05-04 04:57:00 +00002877 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002878 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002879}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002880
2881namespace {
2882class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2883 GRStateRef state;
2884public:
2885 StopTrackingCallback(GRStateRef st) : state(st) {}
2886 GRStateRef getState() { return state; }
2887
2888 bool VisitSymbol(SymbolRef sym) {
2889 state = state.remove<RefBindings>(sym);
2890 return true;
2891 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002892
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002893 const GRState* getState() const { return state.getState(); }
2894};
2895} // end anonymous namespace
2896
2897
Ted Kremeneka42be302009-02-14 01:43:44 +00002898void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002899 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002900 bool escapes = false;
2901
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002902 // A value escapes in three possible cases (this may change):
2903 //
2904 // (1) we are binding to something that is not a memory region.
2905 // (2) we are binding to a memregion that does not have stack storage
2906 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002907 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002908 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002909
Ted Kremeneka42be302009-02-14 01:43:44 +00002910 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002911 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002912 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002913 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2914 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002915
2916 if (!escapes) {
2917 // To test (3), generate a new state with the binding removed. If it is
2918 // the same state, then it escapes (since the store cannot represent
2919 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002920 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002921 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002922 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002923
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002924 // If our store can represent the binding and we aren't storing to something
2925 // that doesn't have local storage then just return and have the simulation
2926 // state continue as is.
2927 if (!escapes)
2928 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002929
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002930 // Otherwise, find all symbols referenced by 'val' that we are tracking
2931 // and stop tracking them.
2932 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002933}
2934
Ted Kremenek0106e202008-10-24 20:32:50 +00002935std::pair<GRStateRef,bool>
2936CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2937 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002938 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002939 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002940
Ted Kremenek47a72422009-04-29 18:50:19 +00002941 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002942 hasLeak = V.isOwned() ||
2943 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002944
Ted Kremenek47a72422009-04-29 18:50:19 +00002945 GRStateRef state(St, VMgr);
2946
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002947 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002948 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002949
Ted Kremenek0106e202008-10-24 20:32:50 +00002950 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2951 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002952}
2953
Ted Kremenek541db372008-04-24 23:57:27 +00002954
Ted Kremenekffefc352008-04-11 22:25:11 +00002955
Ted Kremenek541db372008-04-24 23:57:27 +00002956// Dead symbols.
2957
Ted Kremenek708af042009-02-05 06:50:21 +00002958
Ted Kremenek541db372008-04-24 23:57:27 +00002959
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002960 // Return statements.
2961
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002962void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002963 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002964 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002965 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002966 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002967
2968 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002969 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002970 return;
2971
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002972 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002973 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002974
Ted Kremenek74556a12009-03-26 03:35:11 +00002975 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002976 return;
2977
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002978 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002979 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002980
2981 if (!T)
2982 return;
2983
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002984 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002985 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002986
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002987 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002988 case RefVal::Owned: {
2989 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002990 assert (cnt > 0);
2991 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002992 break;
2993 }
2994
2995 case RefVal::NotOwned: {
2996 unsigned cnt = X.getCount();
2997 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2998 : RefVal::makeReturnedNotOwned();
2999 break;
3000 }
3001
3002 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003003 return;
3004 }
3005
3006 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003007 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003008 Pred = Builder.MakeNode(Dst, S, Pred, state);
3009
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003010 // Did we cache out?
3011 if (!Pred)
3012 return;
3013
Ted Kremenek47a72422009-04-29 18:50:19 +00003014 // Any leaks or other errors?
3015 if (X.isReturnedOwned() && X.getCount() == 0) {
3016 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3017
Ted Kremenek314b1952009-04-29 23:03:22 +00003018 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003019 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3020 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003021 static int ReturnOwnLeakTag = 0;
3022 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00003023 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003024 if (ExplodedNode<GRState> *N =
3025 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
3026 CFRefLeakReport *report =
3027 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3028 N, Sym, Eng);
3029 BR->EmitReport(report);
3030 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003031 }
3032 }
3033 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003034}
3035
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003036// Assumptions.
3037
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003038const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3039 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003040 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003041 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003042
3043 // FIXME: We may add to the interface of EvalAssume the list of symbols
3044 // whose assumptions have changed. For now we just iterate through the
3045 // bindings and check if any of the tracked symbols are NULL. This isn't
3046 // too bad since the number of symbols we will track in practice are
3047 // probably small and EvalAssume is only called at branches and a few
3048 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003049 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003050
3051 if (B.isEmpty())
3052 return St;
3053
3054 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003055
3056 GRStateRef state(St, VMgr);
3057 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003058
3059 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003060 // Check if the symbol is null (or equal to any constant).
3061 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003062 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003063 changed = true;
3064 B = RefBFactory.Remove(B, I.getKey());
3065 }
3066 }
3067
Ted Kremenek91781202008-08-17 03:20:02 +00003068 if (changed)
3069 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003070
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003071 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003072}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003073
Ted Kremenekb6578942009-02-24 19:15:11 +00003074GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3075 RefVal V, ArgEffect E,
3076 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003077
3078 // In GC mode [... release] and [... retain] do nothing.
3079 switch (E) {
3080 default: break;
3081 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3082 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003083 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003084 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3085 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003086 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003087
Ted Kremenek6537a642009-03-17 19:42:23 +00003088 // Handle all use-after-releases.
3089 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3090 V = V ^ RefVal::ErrorUseAfterRelease;
3091 hasErr = V.getKind();
3092 return state.set<RefBindings>(sym, V);
3093 }
3094
Ted Kremenek0d721572008-03-11 17:48:22 +00003095 switch (E) {
3096 default:
3097 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003098
3099 case Dealloc:
3100 // Any use of -dealloc in GC is *bad*.
3101 if (isGCEnabled()) {
3102 V = V ^ RefVal::ErrorDeallocGC;
3103 hasErr = V.getKind();
3104 break;
3105 }
3106
3107 switch (V.getKind()) {
3108 default:
3109 assert(false && "Invalid case.");
3110 case RefVal::Owned:
3111 // The object immediately transitions to the released state.
3112 V = V ^ RefVal::Released;
3113 V.clearCounts();
3114 return state.set<RefBindings>(sym, V);
3115 case RefVal::NotOwned:
3116 V = V ^ RefVal::ErrorDeallocNotOwned;
3117 hasErr = V.getKind();
3118 break;
3119 }
3120 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003121
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003122 case NewAutoreleasePool:
3123 assert(!isGCEnabled());
3124 return state.add<AutoreleaseStack>(sym);
3125
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003126 case MayEscape:
3127 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003128 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003129 break;
3130 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003131
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003132 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003133
Ted Kremenekede40b72008-07-09 18:11:16 +00003134 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003135 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003136 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003137
Ted Kremenek9b112d22009-01-28 21:44:40 +00003138 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003139 if (isGCEnabled())
3140 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003141
3142 // Update the autorelease counts.
3143 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003144
3145 // Fall-through.
3146
Ted Kremenek227c5372008-05-06 02:41:27 +00003147 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003148 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003149
Ted Kremenek0d721572008-03-11 17:48:22 +00003150 case IncRef:
3151 switch (V.getKind()) {
3152 default:
3153 assert(false);
3154
3155 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003156 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003157 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003158 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003159 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003160 // Non-GC cases are handled above.
3161 assert(isGCEnabled());
3162 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003163 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003164 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003165 break;
3166
Ted Kremenek272aa852008-06-25 21:21:56 +00003167 case SelfOwn:
3168 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003169 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003170 case DecRef:
3171 switch (V.getKind()) {
3172 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003173 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003174 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003175
Ted Kremenek272aa852008-06-25 21:21:56 +00003176 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003177 assert(V.getCount() > 0);
3178 if (V.getCount() == 1) V = V ^ RefVal::Released;
3179 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003180 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003181
Ted Kremenek272aa852008-06-25 21:21:56 +00003182 case RefVal::NotOwned:
3183 if (V.getCount() > 0)
3184 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003185 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003186 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003187 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003188 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003189 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003190
Ted Kremenek0d721572008-03-11 17:48:22 +00003191 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003192 // Non-GC cases are handled above.
3193 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003194 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003195 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003196 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003197 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003198 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003199 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003200 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003201}
3202
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003203//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003204// Handle dead symbols and end-of-path.
3205//===----------------------------------------------------------------------===//
3206
3207void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3208 GREndPathNodeBuilder<GRState>& Builder) {
3209
3210 const GRState* St = Builder.getState();
3211 RefBindings B = St->get<RefBindings>();
3212
3213 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3214 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3215
3216 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3217 bool hasLeak = false;
3218
3219 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003220 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3221 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003222
3223 St = X.first;
3224 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3225 }
3226
3227 if (Leaked.empty())
3228 return;
3229
3230 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3231
3232 if (!N)
3233 return;
3234
3235 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3236 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3237
3238 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3239 : leakWithinFunction);
3240 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003241 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003242 BR->EmitReport(report);
3243 }
3244}
3245
3246void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3247 GRExprEngine& Eng,
3248 GRStmtNodeBuilder<GRState>& Builder,
3249 ExplodedNode<GRState>* Pred,
3250 Stmt* S,
3251 const GRState* St,
3252 SymbolReaper& SymReaper) {
3253
Ted Kremenek876d8df2009-02-19 23:47:02 +00003254 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003255 RefBindings B = St->get<RefBindings>();
3256 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3257
3258 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3259 E = SymReaper.dead_end(); I != E; ++I) {
3260
3261 const RefVal* T = B.lookup(*I);
3262 if (!T) continue;
3263
3264 bool hasLeak = false;
3265
3266 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003267 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003268
3269 St = X.first;
3270
3271 if (hasLeak)
3272 Leaked.push_back(std::make_pair(*I,X.second));
3273 }
3274
Ted Kremenek876d8df2009-02-19 23:47:02 +00003275 if (!Leaked.empty()) {
3276 // Create a new intermediate node representing the leak point. We
3277 // use a special program point that represents this checker-specific
3278 // transition. We use the address of RefBIndex as a unique tag for this
3279 // checker. We will create another node (if we don't cache out) that
3280 // removes the retain-count bindings from the state.
3281 // NOTE: We use 'generateNode' so that it does interplay with the
3282 // auto-transition logic.
3283 ExplodedNode<GRState>* N =
3284 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003285
Ted Kremenek876d8df2009-02-19 23:47:02 +00003286 if (!N)
3287 return;
3288
3289 // Generate the bug reports.
3290 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3291 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3292
3293 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3294 : leakWithinFunction);
3295 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003296 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3297 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003298 BR->EmitReport(report);
3299 }
Ted Kremenek708af042009-02-05 06:50:21 +00003300
Ted Kremenek876d8df2009-02-19 23:47:02 +00003301 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003302 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003303
3304 // Now generate a new node that nukes the old bindings.
3305 GRStateRef state(St, Eng.getStateManager());
3306 RefBindings::Factory& F = state.get_context<RefBindings>();
3307
3308 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3309 E = SymReaper.dead_end(); I!=E; ++I)
3310 B = F.Remove(B, *I);
3311
3312 state = state.set<RefBindings>(B);
3313 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003314}
3315
3316void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3317 GRStmtNodeBuilder<GRState>& Builder,
3318 Expr* NodeExpr, Expr* ErrorExpr,
3319 ExplodedNode<GRState>* Pred,
3320 const GRState* St,
3321 RefVal::Kind hasErr, SymbolRef Sym) {
3322 Builder.BuildSinks = true;
3323 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3324
3325 if (!N) return;
3326
3327 CFRefBug *BT = 0;
3328
Ted Kremenek6537a642009-03-17 19:42:23 +00003329 switch (hasErr) {
3330 default:
3331 assert(false && "Unhandled error.");
3332 return;
3333 case RefVal::ErrorUseAfterRelease:
3334 BT = static_cast<CFRefBug*>(useAfterRelease);
3335 break;
3336 case RefVal::ErrorReleaseNotOwned:
3337 BT = static_cast<CFRefBug*>(releaseNotOwned);
3338 break;
3339 case RefVal::ErrorDeallocGC:
3340 BT = static_cast<CFRefBug*>(deallocGC);
3341 break;
3342 case RefVal::ErrorDeallocNotOwned:
3343 BT = static_cast<CFRefBug*>(deallocNotOwned);
3344 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003345 }
3346
Ted Kremenekc26c4692009-02-18 03:48:14 +00003347 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003348 report->addRange(ErrorExpr->getSourceRange());
3349 BR->EmitReport(report);
3350}
3351
3352//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003353// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003354//===----------------------------------------------------------------------===//
3355
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003356GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3357 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003358 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003359}