blob: 686ef2c2638d618e93cc7d4ff9f88d6e31540178 [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenekc3bc6c82009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
Ted Kremenek314b1952009-04-29 23:03:22 +0000152static const ObjCMethodDecl*
153ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
154 ObjCInterfaceDecl *ID =
155 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
156
157 return MD->isInstanceMethod()
158 ? ID->lookupInstanceMethod(Context, MD->getSelector())
159 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000160}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000161
Ted Kremenek7d421f32008-04-09 23:49:11 +0000162//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000163// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000164//===----------------------------------------------------------------------===//
165
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000166static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(0, &II);
169}
170
Ted Kremenek0e344d42008-05-06 00:30:21 +0000171static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
172 IdentifierInfo* II = &Ctx.Idents.get(name);
173 return Ctx.Selectors.getSelector(1, &II);
174}
175
Ted Kremenek272aa852008-06-25 21:21:56 +0000176//===----------------------------------------------------------------------===//
177// Type querying functions.
178//===----------------------------------------------------------------------===//
179
Ted Kremenek17144e82009-01-12 21:45:02 +0000180static bool hasPrefix(const char* s, const char* prefix) {
181 if (!prefix)
182 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000183
Ted Kremenek17144e82009-01-12 21:45:02 +0000184 char c = *s;
185 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000186
Ted Kremenek17144e82009-01-12 21:45:02 +0000187 while (c != '\0' && cP != '\0') {
188 if (c != cP) break;
189 c = *(++s);
190 cP = *(++prefix);
191 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000192
Ted Kremenek17144e82009-01-12 21:45:02 +0000193 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000194}
195
Ted Kremenek17144e82009-01-12 21:45:02 +0000196static bool hasSuffix(const char* s, const char* suffix) {
197 const char* loc = strstr(s, suffix);
198 return loc && strcmp(suffix, loc) == 0;
199}
200
201static bool isRefType(QualType RetTy, const char* prefix,
202 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
205 const char* TDName = TD->getDecl()->getIdentifier()->getName();
206 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
207 }
208
209 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Is the type void*?
213 const PointerType* PT = RetTy->getAsPointerType();
214 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000215 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000216
217 // Does the name start with the prefix?
218 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000219}
220
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000221//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000222// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000223//===----------------------------------------------------------------------===//
224
Ted Kremenek272aa852008-06-25 21:21:56 +0000225/// ArgEffect is used to summarize a function/method call's effect on a
226/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000227enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
228 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
229 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000230
Ted Kremeneka7338b42008-03-11 06:39:11 +0000231namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000232template <> struct FoldingSetTrait<ArgEffect> {
233static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
234 ID.AddInteger((unsigned) X);
235}
Ted Kremenek272aa852008-06-25 21:21:56 +0000236};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000237} // end llvm namespace
238
Ted Kremeneka56ae162009-05-03 05:20:50 +0000239/// ArgEffects summarizes the effects of a function/method call on all of
240/// its arguments.
241typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
242
Ted Kremeneka7338b42008-03-11 06:39:11 +0000243namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000244
245/// RetEffect is used to summarize a function/method call's behavior with
246/// respect to its return value.
247class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000248public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000249 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000250 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000251
252 enum ObjKind { CF, ObjC, AnyObj };
253
Ted Kremeneka7338b42008-03-11 06:39:11 +0000254private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000255 Kind K;
256 ObjKind O;
257 unsigned index;
258
259 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
260 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000261
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000263 Kind getKind() const { return K; }
264
265 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000266
267 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000268 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000269 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000271
Ted Kremenek314b1952009-04-29 23:03:22 +0000272 bool isOwned() const {
273 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
274 }
275
Ted Kremenek272aa852008-06-25 21:21:56 +0000276 static RetEffect MakeAlias(unsigned Idx) {
277 return RetEffect(Alias, Idx);
278 }
279 static RetEffect MakeReceiverAlias() {
280 return RetEffect(ReceiverAlias);
281 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000282 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
283 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000284 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000285 static RetEffect MakeNotOwned(ObjKind o) {
286 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000287 }
288 static RetEffect MakeGCNotOwned() {
289 return RetEffect(GCNotOwnedSymbol, ObjC);
290 }
291
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 static RetEffect MakeNoRet() {
293 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000294 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000295
Ted Kremenek272aa852008-06-25 21:21:56 +0000296 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000297 ID.AddInteger((unsigned)K);
298 ID.AddInteger((unsigned)O);
299 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000300 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000301};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000302
Ted Kremenek272aa852008-06-25 21:21:56 +0000303
Ted Kremenek2f226732009-05-04 05:31:22 +0000304class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000305 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
306 /// specifies the argument (starting from 0). This can be sparsely
307 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000308 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000309
310 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
311 /// do not have an entry in Args.
312 ArgEffect DefaultArgEffect;
313
Ted Kremenek272aa852008-06-25 21:21:56 +0000314 /// Receiver - If this summary applies to an Objective-C message expression,
315 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000316 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000317
318 /// Ret - The effect on the return value. Used to indicate if the
319 /// function/method call returns a new tracked symbol, returns an
320 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000321 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000322
Ted Kremenekf2717b02008-07-18 17:24:20 +0000323 /// EndPath - Indicates that execution of this method/function should
324 /// terminate the simulation of a path.
325 bool EndPath;
326
Ted Kremeneka7338b42008-03-11 06:39:11 +0000327public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000328 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000329 ArgEffect ReceiverEff, bool endpath = false)
330 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
331 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000332
Ted Kremenek272aa852008-06-25 21:21:56 +0000333 /// getArg - Return the argument effect on the argument specified by
334 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000335 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000336 if (const ArgEffect *AE = Args.lookup(idx))
337 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000338
Ted Kremenekbcaff792008-05-06 15:44:25 +0000339 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000340 }
341
Ted Kremenek2f226732009-05-04 05:31:22 +0000342 /// setDefaultArgEffect - Set the default argument effect.
343 void setDefaultArgEffect(ArgEffect E) {
344 DefaultArgEffect = E;
345 }
346
347 /// setArg - Set the argument effect on the argument specified by idx.
348 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
349 Args = AF.Add(Args, idx, E);
350 }
351
Ted Kremenek272aa852008-06-25 21:21:56 +0000352 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000354
Ted Kremenek2f226732009-05-04 05:31:22 +0000355 /// setRetEffect - Set the effect of the return value of the call.
356 void setRetEffect(RetEffect E) { Ret = E; }
357
Ted Kremenekf2717b02008-07-18 17:24:20 +0000358 /// isEndPath - Returns true if executing the given method/function should
359 /// terminate the path.
360 bool isEndPath() const { return EndPath; }
361
Ted Kremenek272aa852008-06-25 21:21:56 +0000362 /// getReceiverEffect - Returns the effect on the receiver of the call.
363 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000364 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000365
Ted Kremenek2f226732009-05-04 05:31:22 +0000366 /// setReceiverEffect - Set the effect on the receiver of the call.
367 void setReceiverEffect(ArgEffect E) { Receiver = E; }
368
Ted Kremeneka56ae162009-05-03 05:20:50 +0000369 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370
Ted Kremeneka56ae162009-05-03 05:20:50 +0000371 ExprIterator begin_args() const { return Args.begin(); }
372 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373
Ted Kremeneka56ae162009-05-03 05:20:50 +0000374 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000375 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000376 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000377 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000378 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000379 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000380 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000381 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000382 }
383
384 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000385 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000386 }
387};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000388} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390//===----------------------------------------------------------------------===//
391// Data structures for constructing summaries.
392//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000393
Ted Kremenek272aa852008-06-25 21:21:56 +0000394namespace {
395class VISIBILITY_HIDDEN ObjCSummaryKey {
396 IdentifierInfo* II;
397 Selector S;
398public:
399 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
400 : II(ii), S(s) {}
401
Ted Kremenek314b1952009-04-29 23:03:22 +0000402 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000403 : II(d ? d->getIdentifier() : 0), S(s) {}
404
405 ObjCSummaryKey(Selector s)
406 : II(0), S(s) {}
407
408 IdentifierInfo* getIdentifier() const { return II; }
409 Selector getSelector() const { return S; }
410};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000411}
412
413namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000414template <> struct DenseMapInfo<ObjCSummaryKey> {
415 static inline ObjCSummaryKey getEmptyKey() {
416 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
417 DenseMapInfo<Selector>::getEmptyKey());
418 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000419
Ted Kremenek272aa852008-06-25 21:21:56 +0000420 static inline ObjCSummaryKey getTombstoneKey() {
421 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
422 DenseMapInfo<Selector>::getTombstoneKey());
423 }
424
425 static unsigned getHashValue(const ObjCSummaryKey &V) {
426 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
427 & 0x88888888)
428 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
429 & 0x55555555);
430 }
431
432 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
433 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
434 RHS.getIdentifier()) &&
435 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
436 RHS.getSelector());
437 }
438
439 static bool isPod() {
440 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
441 DenseMapInfo<Selector>::isPod();
442 }
443};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000444} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000445
Ted Kremenek84f010c2008-06-23 23:30:29 +0000446namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000447class VISIBILITY_HIDDEN ObjCSummaryCache {
448 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
449 MapTy M;
450public:
451 ObjCSummaryCache() {}
452
453 typedef MapTy::iterator iterator;
454
Ted Kremenek314b1952009-04-29 23:03:22 +0000455 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
456 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000457 // Lookup the method using the decl for the class @interface. If we
458 // have no decl, lookup using the class name.
459 return D ? find(D, S) : find(ClsName, S);
460 }
461
Ted Kremenek314b1952009-04-29 23:03:22 +0000462 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000463 // Do a lookup with the (D,S) pair. If we find a match return
464 // the iterator.
465 ObjCSummaryKey K(D, S);
466 MapTy::iterator I = M.find(K);
467
468 if (I != M.end() || !D)
469 return I;
470
471 // Walk the super chain. If we find a hit with a parent, we'll end
472 // up returning that summary. We actually allow that key (null,S), as
473 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
474 // generate initial summaries without having to worry about NSObject
475 // being declared.
476 // FIXME: We may change this at some point.
477 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
478 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
479 break;
480
481 if (!C)
482 return I;
483 }
484
485 // Cache the summary with original key to make the next lookup faster
486 // and return the iterator.
487 M[K] = I->second;
488 return I;
489 }
490
Ted Kremenek9449ca92008-08-12 20:41:56 +0000491
Ted Kremenek272aa852008-06-25 21:21:56 +0000492 iterator find(Expr* Receiver, Selector S) {
493 return find(getReceiverDecl(Receiver), S);
494 }
495
496 iterator find(IdentifierInfo* II, Selector S) {
497 // FIXME: Class method lookup. Right now we dont' have a good way
498 // of going between IdentifierInfo* and the class hierarchy.
499 iterator I = M.find(ObjCSummaryKey(II, S));
500 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
501 }
502
503 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
504
505 const PointerType* PT = E->getType()->getAsPointerType();
506 if (!PT) return 0;
507
508 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
509 if (!OI) return 0;
510
511 return OI ? OI->getDecl() : 0;
512 }
513
514 iterator end() { return M.end(); }
515
516 RetainSummary*& operator[](ObjCMessageExpr* ME) {
517
518 Selector S = ME->getSelector();
519
520 if (Expr* Receiver = ME->getReceiver()) {
521 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
522 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
523 }
524
525 return M[ObjCSummaryKey(ME->getClassName(), S)];
526 }
527
528 RetainSummary*& operator[](ObjCSummaryKey K) {
529 return M[K];
530 }
531
532 RetainSummary*& operator[](Selector S) {
533 return M[ ObjCSummaryKey(S) ];
534 }
535};
536} // end anonymous namespace
537
538//===----------------------------------------------------------------------===//
539// Data structures for managing collections of summaries.
540//===----------------------------------------------------------------------===//
541
542namespace {
543class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000544
545 //==-----------------------------------------------------------------==//
546 // Typedefs.
547 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000548
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000549 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
550 FuncSummariesTy;
551
Ted Kremenek84f010c2008-06-23 23:30:29 +0000552 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000553
554 //==-----------------------------------------------------------------==//
555 // Data.
556 //==-----------------------------------------------------------------==//
557
Ted Kremenek272aa852008-06-25 21:21:56 +0000558 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000559 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000560
Ted Kremenekede40b72008-07-09 18:11:16 +0000561 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
562 /// "CFDictionaryCreate".
563 IdentifierInfo* CFDictionaryCreateII;
564
Ted Kremenek272aa852008-06-25 21:21:56 +0000565 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000566 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000567
Ted Kremenek272aa852008-06-25 21:21:56 +0000568 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000569 FuncSummariesTy FuncSummaries;
570
Ted Kremenek272aa852008-06-25 21:21:56 +0000571 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
572 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000573 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000574
Ted Kremenek272aa852008-06-25 21:21:56 +0000575 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000576 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000577
Ted Kremenek272aa852008-06-25 21:21:56 +0000578 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
579 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000580 llvm::BumpPtrAllocator BPAlloc;
581
Ted Kremeneka56ae162009-05-03 05:20:50 +0000582 /// AF - A factory for ArgEffects objects.
583 ArgEffects::Factory AF;
584
Ted Kremenek272aa852008-06-25 21:21:56 +0000585 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000586 ArgEffects ScratchArgs;
587
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000588 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
589 /// objects.
590 RetEffect ObjCAllocRetE;
591
Ted Kremenek286e9852009-05-04 04:57:00 +0000592 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000593 RetainSummary* StopSummary;
594
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000595 //==-----------------------------------------------------------------==//
596 // Methods.
597 //==-----------------------------------------------------------------==//
598
Ted Kremenek272aa852008-06-25 21:21:56 +0000599 /// getArgEffects - Returns a persistent ArgEffects object based on the
600 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000601 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000602
Ted Kremenek562c1302008-05-05 16:51:50 +0000603 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000604
605public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000606 RetainSummary *getDefaultSummary() {
607 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
608 return new (Summ) RetainSummary(DefaultSummary);
609 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000610
Ted Kremenek064ef322009-02-23 16:51:39 +0000611 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000612
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000613 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
614 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000615 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000616
Ted Kremeneka56ae162009-05-03 05:20:50 +0000617 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000618 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000619 ArgEffect DefaultEff = MayEscape,
620 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000621
Ted Kremenek266d8b62008-05-06 02:26:56 +0000622 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000623 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000624 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000625 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000626 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000627
Ted Kremeneka821b792009-04-29 05:04:30 +0000628 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000629 if (StopSummary)
630 return StopSummary;
631
632 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
633 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000634
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000635 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000636 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000637
Ted Kremeneka821b792009-04-29 05:04:30 +0000638 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000639
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000640 void InitializeClassMethodSummaries();
641 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000642
Ted Kremenek9b42e062009-05-03 04:42:10 +0000643 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000644 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000645
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000646private:
647
Ted Kremenekf2717b02008-07-18 17:24:20 +0000648 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
649 RetainSummary* Summ) {
650 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
651 }
652
Ted Kremenek272aa852008-06-25 21:21:56 +0000653 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
654 ObjCClassMethodSummaries[S] = Summ;
655 }
656
657 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
658 ObjCMethodSummaries[S] = Summ;
659 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000660
661 void addClassMethSummary(const char* Cls, const char* nullaryName,
662 RetainSummary *Summ) {
663 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
664 Selector S = GetNullarySelector(nullaryName, Ctx);
665 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
666 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000667
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000668 void addInstMethSummary(const char* Cls, const char* nullaryName,
669 RetainSummary *Summ) {
670 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
671 Selector S = GetNullarySelector(nullaryName, Ctx);
672 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
673 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000674
675 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000676 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000677
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000678 while (const char* s = va_arg(argp, const char*))
679 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000680
681 return Ctx.Selectors.getSelector(II.size(), &II[0]);
682 }
683
684 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
685 RetainSummary* Summ, va_list argp) {
686 Selector S = generateSelector(argp);
687 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000688 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000689
690 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
691 va_list argp;
692 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000693 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000694 va_end(argp);
695 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000696
697 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
698 va_list argp;
699 va_start(argp, Summ);
700 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
701 va_end(argp);
702 }
703
704 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
705 va_list argp;
706 va_start(argp, Summ);
707 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
708 va_end(argp);
709 }
710
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000711 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000712 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
713 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000714 DoNothing, DoNothing, true);
715 va_list argp;
716 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000717 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000718 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000719 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000720
Ted Kremeneka7338b42008-03-11 06:39:11 +0000721public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000722
723 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000724 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000725 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000726 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000727 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
728 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000729 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
730 RetEffect::MakeNoRet() /* return effect */,
731 DoNothing /* receiver effect */,
732 MayEscape /* default argument effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000733 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000734
735 InitializeClassMethodSummaries();
736 InitializeMethodSummaries();
737 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000738
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000739 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000740
Ted Kremenekd13c1872008-06-24 03:56:45 +0000741 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000742
Ted Kremenek314b1952009-04-29 23:03:22 +0000743 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
744 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000745 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000746 ID, ME->getMethodDecl(), ME->getType());
747 }
748
Ted Kremenek04e00302009-04-29 17:09:14 +0000749 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000750 const ObjCInterfaceDecl* ID,
751 const ObjCMethodDecl *MD,
752 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000753
754 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000755 const ObjCInterfaceDecl *ID,
756 const ObjCMethodDecl *MD,
757 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000758
759 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
760 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
761 ME->getClassInfo().first,
762 ME->getMethodDecl(), ME->getType());
763 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000764
765 /// getMethodSummary - This version of getMethodSummary is used to query
766 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000767 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
768 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000769 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000770 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000771 IdentifierInfo *ClsName = ID->getIdentifier();
772 QualType ResultTy = MD->getResultType();
773
Ted Kremenek81eb4642009-04-30 05:47:23 +0000774 // Resolve the method decl last.
775 if (const ObjCMethodDecl *InterfaceMD =
776 ResolveToInterfaceMethodDecl(MD, Ctx))
777 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000778
Ted Kremenek91b89a42009-04-29 17:17:48 +0000779 if (MD->isInstanceMethod())
780 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
781 else
782 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
783 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000784
Ted Kremenek314b1952009-04-29 23:03:22 +0000785 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
786 Selector S, QualType RetTy);
787
Ted Kremenek03d242e2009-05-05 18:44:20 +0000788 void updateSummaryArgEffFromAnnotations(RetainSummary &Summ, const Decl *D,
789 unsigned argIdx = 0);
Ted Kremenekb88734c2009-05-04 15:40:58 +0000790
Ted Kremenek2f226732009-05-04 05:31:22 +0000791 void updateSummaryFromAnnotations(RetainSummary &Summ,
792 const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000793
Ted Kremenekf5b44c62009-05-04 16:43:50 +0000794 void updateSummaryFromAnnotations(RetainSummary &Summ,
795 const FunctionDecl *FD);
796
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000797 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000798
799 RetainSummary *copySummary(RetainSummary *OldSumm) {
800 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
801 new (Summ) RetainSummary(*OldSumm);
802 return Summ;
803 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000804};
805
806} // end anonymous namespace
807
808//===----------------------------------------------------------------------===//
809// Implementation of checker data structures.
810//===----------------------------------------------------------------------===//
811
Ted Kremeneka56ae162009-05-03 05:20:50 +0000812RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000813
Ted Kremeneka56ae162009-05-03 05:20:50 +0000814ArgEffects RetainSummaryManager::getArgEffects() {
815 ArgEffects AE = ScratchArgs;
816 ScratchArgs = AF.GetEmptyMap();
817 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000818}
819
Ted Kremenek266d8b62008-05-06 02:26:56 +0000820RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000821RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000822 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000823 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000824 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000825 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000826 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000827 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000828 return Summ;
829}
830
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000831//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000832// Predicates.
833//===----------------------------------------------------------------------===//
834
Ted Kremenek9b42e062009-05-03 04:42:10 +0000835bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000836 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000837 return false;
838
Ted Kremenek0d813552009-04-23 22:11:07 +0000839 // We assume that id<..>, id, and "Class" all represent tracked objects.
840 const PointerType *PT = Ty->getAsPointerType();
841 if (PT == 0)
842 return true;
843
844 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000845
846 // We assume that id<..>, id, and "Class" all represent tracked objects.
847 if (!OT)
848 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000849
850 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000851 // FIXME: We can memoize here if this gets too expensive.
852 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
853 ObjCInterfaceDecl* ID = OT->getDecl();
854
855 for ( ; ID ; ID = ID->getSuperClass())
856 if (ID->getIdentifier() == NSObjectII)
857 return true;
858
859 return false;
860}
861
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000862bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
863 return isRefType(T, "CF") || // Core Foundation.
864 isRefType(T, "CG") || // Core Graphics.
865 isRefType(T, "DADisk") || // Disk Arbitration API.
866 isRefType(T, "DADissenter") ||
867 isRefType(T, "DASessionRef");
868}
869
Ted Kremenek35920ed2009-01-07 00:39:56 +0000870//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000871// Summary creation for functions (largely uses of Core Foundation).
872//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000873
Ted Kremenek17144e82009-01-12 21:45:02 +0000874static bool isRetain(FunctionDecl* FD, const char* FName) {
875 const char* loc = strstr(FName, "Retain");
876 return loc && loc[sizeof("Retain")-1] == '\0';
877}
878
879static bool isRelease(FunctionDecl* FD, const char* FName) {
880 const char* loc = strstr(FName, "Release");
881 return loc && loc[sizeof("Release")-1] == '\0';
882}
883
Ted Kremenekd13c1872008-06-24 03:56:45 +0000884RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000885 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000886 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000887 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000888 return I->second;
889
Ted Kremenek64cddf12009-05-04 15:34:07 +0000890 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000891 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000892
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000893 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000894 // We generate "stop" summaries for implicitly defined functions.
895 if (FD->isImplicit()) {
896 S = getPersistentStopSummary();
897 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000898 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000899
Ted Kremenek064ef322009-02-23 16:51:39 +0000900 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000901 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000902 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000903 const char* FName = FD->getIdentifier()->getName();
904
Ted Kremenek38c6f022009-03-05 22:11:14 +0000905 // Strip away preceding '_'. Doing this here will effect all the checks
906 // down below.
907 while (*FName == '_') ++FName;
908
Ted Kremenek17144e82009-01-12 21:45:02 +0000909 // Inspect the result type.
910 QualType RetTy = FT->getResultType();
911
912 // FIXME: This should all be refactored into a chain of "summary lookup"
913 // filters.
914 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
915 // FIXES: <rdar://problem/6326900>
916 // This should be addressed using a API table. This strcmp is also
917 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000918 assert (ScratchArgs.isEmpty());
919 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000920 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
921 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000922 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000923
924 // Enable this code once the semantics of NSDeallocateObject are resolved
925 // for GC. <rdar://problem/6619988>
926#if 0
927 // Handle: NSDeallocateObject(id anObject);
928 // This method does allow 'nil' (although we don't check it now).
929 if (strcmp(FName, "NSDeallocateObject") == 0) {
930 return RetTy == Ctx.VoidTy
931 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
932 : getPersistentStopSummary();
933 }
934#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000935
936 // Handle: id NSMakeCollectable(CFTypeRef)
937 if (strcmp(FName, "NSMakeCollectable") == 0) {
938 S = (RetTy == Ctx.getObjCIdType())
939 ? getUnarySummary(FT, cfmakecollectable)
940 : getPersistentStopSummary();
941
942 break;
943 }
944
945 if (RetTy->isPointerType()) {
946 // For CoreFoundation ('CF') types.
947 if (isRefType(RetTy, "CF", &Ctx, FName)) {
948 if (isRetain(FD, FName))
949 S = getUnarySummary(FT, cfretain);
950 else if (strstr(FName, "MakeCollectable"))
951 S = getUnarySummary(FT, cfmakecollectable);
952 else
953 S = getCFCreateGetRuleSummary(FD, FName);
954
955 break;
956 }
957
958 // For CoreGraphics ('CG') types.
959 if (isRefType(RetTy, "CG", &Ctx, FName)) {
960 if (isRetain(FD, FName))
961 S = getUnarySummary(FT, cfretain);
962 else
963 S = getCFCreateGetRuleSummary(FD, FName);
964
965 break;
966 }
967
968 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
969 if (isRefType(RetTy, "DADisk") ||
970 isRefType(RetTy, "DADissenter") ||
971 isRefType(RetTy, "DASessionRef")) {
972 S = getCFCreateGetRuleSummary(FD, FName);
973 break;
974 }
975
976 break;
977 }
978
979 // Check for release functions, the only kind of functions that we care
980 // about that don't return a pointer type.
981 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000982 // Test for 'CGCF'.
983 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
984 FName += 4;
985 else
986 FName += 2;
987
988 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000989 S = getUnarySummary(FT, cfrelease);
990 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000991 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +0000992 // Remaining CoreFoundation and CoreGraphics functions.
993 // We use to assume that they all strictly followed the ownership idiom
994 // and that ownership cannot be transferred. While this is technically
995 // correct, many methods allow a tracked object to escape. For example:
996 //
997 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
998 // CFDictionaryAddValue(y, key, x);
999 // CFRelease(x);
1000 // ... it is okay to use 'x' since 'y' has a reference to it
1001 //
1002 // We handle this and similar cases with the follow heuristic. If the
1003 // function name contains "InsertValue", "SetValue" or "AddValue" then
1004 // we assume that arguments may "escape."
1005 //
1006 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1007 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001008 CStrInCStrNoCase(FName, "SetValue") ||
1009 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001010 ? MayEscape : DoNothing;
1011
1012 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001013 }
1014 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001015 }
1016 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001017
1018 if (!S)
1019 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001020
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001021 // Annotations override defaults.
1022 assert(S);
1023 updateSummaryFromAnnotations(*S, FD);
1024
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001025 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001026 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001027}
1028
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001029RetainSummary*
1030RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1031 const char* FName) {
1032
Ted Kremenek562c1302008-05-05 16:51:50 +00001033 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1034 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001035
Ted Kremenek562c1302008-05-05 16:51:50 +00001036 if (strstr(FName, "Get"))
1037 return getCFSummaryGetRule(FD);
1038
Ted Kremenek286e9852009-05-04 04:57:00 +00001039 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001040}
1041
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001042RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001043RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1044 UnaryFuncKind func) {
1045
Ted Kremenek17144e82009-01-12 21:45:02 +00001046 // Sanity check that this is *really* a unary function. This can
1047 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001048 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001049 if (!FTP || FTP->getNumArgs() != 1)
1050 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001051
Ted Kremeneka56ae162009-05-03 05:20:50 +00001052 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001053
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001054 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001055 case cfretain: {
1056 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001057 return getPersistentSummary(RetEffect::MakeAlias(0),
1058 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001059 }
1060
1061 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001062 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001063 return getPersistentSummary(RetEffect::MakeNoRet(),
1064 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001065 }
1066
1067 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001068 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001069 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001070 }
1071
1072 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001073 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001074 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001075 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001076}
1077
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001078RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001079 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001080
1081 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001082 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1083 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001084 }
1085
Ted Kremenek68621b92009-01-28 05:56:51 +00001086 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001087}
1088
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001089RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001090 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001091 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1092 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001093}
1094
Ted Kremeneka7338b42008-03-11 06:39:11 +00001095//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001096// Summary creation for Selectors.
1097//===----------------------------------------------------------------------===//
1098
Ted Kremenekbcaff792008-05-06 15:44:25 +00001099RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001100RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001101 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001102
Ted Kremenek802cfc72009-02-20 00:05:35 +00001103 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001104 return getPersistentSummary(Loc::IsLocType(RetTy)
1105 ? RetEffect::MakeReceiverAlias()
Ted Kremenek03d242e2009-05-05 18:44:20 +00001106 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001107}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001108
Ted Kremenek2f226732009-05-04 05:31:22 +00001109void
Ted Kremenekb88734c2009-05-04 15:40:58 +00001110RetainSummaryManager::updateSummaryArgEffFromAnnotations(RetainSummary &Summ,
Ted Kremenek03d242e2009-05-05 18:44:20 +00001111 const Decl *D,
1112 unsigned i) {
1113 ArgEffect E = DoNothing;
1114
1115 if (D->getAttr<NSOwnershipRetainAttr>())
1116 E = IncRefMsg;
1117 else if (D->getAttr<CFOwnershipRetainAttr>())
1118 E = IncRef;
1119 else if (D->getAttr<NSOwnershipReleaseAttr>())
1120 E = DecRefMsg;
1121 else if (D->getAttr<CFOwnershipReleaseAttr>())
1122 E = DecRef;
1123 else if (D->getAttr<NSOwnershipAutoreleaseAttr>())
1124 E = Autorelease;
1125 else
1126 return;
1127
1128 if (isa<ParmVarDecl>(D))
1129 Summ.setArgEffect(AF, i, E);
1130 else
1131 Summ.setReceiverEffect(E);
Ted Kremenekb88734c2009-05-04 15:40:58 +00001132}
1133
1134void
Ted Kremenek2f226732009-05-04 05:31:22 +00001135RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001136 const FunctionDecl *FD) {
1137 if (!FD)
1138 return;
1139
1140 // Determine if there is a special return effect for this method.
1141 if (isTrackedObjCObjectType(FD->getResultType())) {
Ted Kremenek028e8112009-05-04 19:10:19 +00001142 if (FD->getAttr<NSOwnershipReturnsAttr>()) {
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001143 Summ.setRetEffect(ObjCAllocRetE);
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001144 }
Ted Kremenekfed3c092009-05-05 00:46:09 +00001145 else if (FD->getAttr<CFOwnershipReturnsAttr>()) {
1146 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1147 }
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001148 }
1149
1150 // Determine if there are any arguments with a specific ArgEffect.
1151 unsigned i = 0;
1152 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1153 E = FD->param_end(); I != E; ++I, ++i)
Ted Kremenek03d242e2009-05-05 18:44:20 +00001154 updateSummaryArgEffFromAnnotations(Summ, *I, i);
Ted Kremenekf5b44c62009-05-04 16:43:50 +00001155}
1156
1157void
1158RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
Ted Kremenek2f226732009-05-04 05:31:22 +00001159 const ObjCMethodDecl *MD) {
Ted Kremenek923fc392009-04-24 23:32:32 +00001160 if (!MD)
Ted Kremenek2f226732009-05-04 05:31:22 +00001161 return;
Ted Kremenek923fc392009-04-24 23:32:32 +00001162
1163 // Determine if there is a special return effect for this method.
Ted Kremenek9b42e062009-05-03 04:42:10 +00001164 if (isTrackedObjCObjectType(MD->getResultType())) {
Ted Kremenek028e8112009-05-04 19:10:19 +00001165 if (MD->getAttr<NSOwnershipReturnsAttr>()) {
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001166 Summ.setRetEffect(ObjCAllocRetE);
Ted Kremenek923fc392009-04-24 23:32:32 +00001167 }
Ted Kremenekfed3c092009-05-05 00:46:09 +00001168 else if (MD->getAttr<CFOwnershipReturnsAttr>()) {
1169 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1170 }
Ted Kremenek923fc392009-04-24 23:32:32 +00001171 }
1172
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001173 // Determine if there are any arguments with a specific ArgEffect.
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001174 unsigned i = 0;
1175 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
Ted Kremenekb88734c2009-05-04 15:40:58 +00001176 E = MD->param_end(); I != E; ++I, ++i)
Ted Kremenek03d242e2009-05-05 18:44:20 +00001177 updateSummaryArgEffFromAnnotations(Summ, *I, i);
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001178
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001179 // Determine any effects on the receiver.
Ted Kremenek03d242e2009-05-05 18:44:20 +00001180 updateSummaryArgEffFromAnnotations(Summ, MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001181}
Ted Kremenek272aa852008-06-25 21:21:56 +00001182
Ted Kremenekbcaff792008-05-06 15:44:25 +00001183RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001184RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1185 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001186
Ted Kremenek578498a2009-04-29 00:42:39 +00001187 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001188 // Scan the method decl for 'void*' arguments. These should be treated
1189 // as 'StopTracking' because they are often used with delegates.
1190 // Delegates are a frequent form of false positives with the retain
1191 // count checker.
1192 unsigned i = 0;
1193 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1194 E = MD->param_end(); I != E; ++I, ++i)
1195 if (ParmVarDecl *PD = *I) {
1196 QualType Ty = Ctx.getCanonicalType(PD->getType());
1197 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001198 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001199 }
1200 }
1201
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001202 // Any special effect for the receiver?
1203 ArgEffect ReceiverEff = DoNothing;
1204
1205 // If one of the arguments in the selector has the keyword 'delegate' we
1206 // should stop tracking the reference count for the receiver. This is
1207 // because the reference count is quite possibly handled by a delegate
1208 // method.
1209 if (S.isKeywordSelector()) {
1210 const std::string &str = S.getAsString();
1211 assert(!str.empty());
1212 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1213 }
1214
Ted Kremenek174a0772009-04-23 23:08:22 +00001215 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001216 if (isTrackedObjCObjectType(RetTy)) {
1217 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1218 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001219 RetEffect E =
1220 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001221 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001222
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 Kremenek5535e5e2009-05-07 23:40:42 +00001296void RetainSummaryManager::InitializeClassMethodSummaries() {
1297 assert(ScratchArgs.isEmpty());
1298 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001299
Ted Kremenek272aa852008-06-25 21:21:56 +00001300 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1301 // NSObject and its derivatives.
1302 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1303 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1304 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001305
1306 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001307 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001308 GetNullarySelector("currentHandler", Ctx),
1309 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001310
1311 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001312 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001313 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1314 GetUnarySelector("addObject", Ctx),
1315 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001316 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001317
1318 // Create the summaries for [NSObject performSelector...]. We treat
1319 // these as 'stop tracking' for the arguments because they are often
1320 // used for delegates that can release the object. When we have better
1321 // inter-procedural analysis we can potentially do something better. This
1322 // workaround is to remove false positives.
1323 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1324 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1325 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1326 "afterDelay", NULL);
1327 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1328 "afterDelay", "inModes", NULL);
1329 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1330 "withObject", "waitUntilDone", NULL);
1331 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1332 "withObject", "waitUntilDone", "modes", NULL);
1333 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1334 "withObject", "waitUntilDone", NULL);
1335 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1336 "withObject", "waitUntilDone", "modes", NULL);
1337 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1338 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001339}
1340
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001341void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001342
Ted Kremeneka56ae162009-05-03 05:20:50 +00001343 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001344
Ted Kremeneka7722b72008-05-06 21:26:51 +00001345 // Create the "init" selector. It just acts as a pass-through for the
1346 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001347 RetainSummary* InitSumm =
1348 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001349 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001350
1351 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001352 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001353
1354 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001355 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1356
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001357 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001358 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001359
Ted Kremenek266d8b62008-05-06 02:26:56 +00001360 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001361 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001362 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001363 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001364
1365 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001366 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001367 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001368
1369 // Create the "drain" selector.
1370 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001371 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001372
1373 // Create the -dealloc summary.
1374 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1375 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001376
1377 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001378 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001379 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001380
Ted Kremenekaac82832009-02-23 17:45:03 +00001381 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001382 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001383 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001384 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001385
Ted Kremenek45642a42008-08-12 18:48:50 +00001386 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001387 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1388 // self-own themselves. However, they only do this once they are displayed.
1389 // Thus, we need to track an NSWindow's display status.
1390 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001391 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001392 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1393
1394 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1395
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001396
1397#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001398 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001399 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001400
1401 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1402 "styleMask", "backing", "defer", NULL);
1403
1404 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1405 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001406#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001407
1408 // For NSPanel (which subclasses NSWindow), allocated objects are not
1409 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001410 // FIXME: For now we don't track NSPanels. object for the same reason
1411 // as for NSWindow objects.
1412 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1413
Ted Kremenek45642a42008-08-12 18:48:50 +00001414 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1415 "styleMask", "backing", "defer", NULL);
1416
1417 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1418 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001419
Ted Kremenekf2717b02008-07-18 17:24:20 +00001420 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001421 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1422 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001423
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001424 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1425 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001426}
1427
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001428//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001429// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001430//===----------------------------------------------------------------------===//
1431
Ted Kremeneka7338b42008-03-11 06:39:11 +00001432namespace {
1433
Ted Kremenek7d421f32008-04-09 23:49:11 +00001434class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001435public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001436 enum Kind {
1437 Owned = 0, // Owning reference.
1438 NotOwned, // Reference is not owned by still valid (not freed).
1439 Released, // Object has been released.
1440 ReturnedOwned, // Returned object passes ownership to caller.
1441 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001442 ERROR_START,
1443 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1444 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001445 ErrorUseAfterRelease, // Object used after released.
1446 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001447 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001448 ErrorLeak, // A memory leak due to excessive reference counts.
1449 ErrorLeakReturned // A memory leak due to the returning method not having
1450 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001451 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001452
1453private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001454 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001455 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001456 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001457 QualType T;
1458
Ted Kremenek68621b92009-01-28 05:56:51 +00001459 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1460 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001461
Ted Kremenek68621b92009-01-28 05:56:51 +00001462 RefVal(Kind k, unsigned cnt = 0)
1463 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1464
1465public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001466 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001467
1468 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001469
Ted Kremenek6537a642009-03-17 19:42:23 +00001470 unsigned getCount() const { return Cnt; }
1471 void clearCounts() { Cnt = 0; }
1472
Ted Kremenek272aa852008-06-25 21:21:56 +00001473 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001474
1475 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001476
Ted Kremenek6537a642009-03-17 19:42:23 +00001477 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001478
Ted Kremenek6537a642009-03-17 19:42:23 +00001479 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001480
Ted Kremenekffefc352008-04-11 22:25:11 +00001481 bool isOwned() const {
1482 return getKind() == Owned;
1483 }
1484
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001485 bool isNotOwned() const {
1486 return getKind() == NotOwned;
1487 }
1488
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001489 bool isReturnedOwned() const {
1490 return getKind() == ReturnedOwned;
1491 }
1492
1493 bool isReturnedNotOwned() const {
1494 return getKind() == ReturnedNotOwned;
1495 }
1496
1497 bool isNonLeakError() const {
1498 Kind k = getKind();
1499 return isError(k) && !isLeak(k);
1500 }
1501
Ted Kremenek68621b92009-01-28 05:56:51 +00001502 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1503 unsigned Count = 1) {
1504 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001505 }
1506
Ted Kremenek68621b92009-01-28 05:56:51 +00001507 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1508 unsigned Count = 0) {
1509 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001510 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001511
1512 static RefVal makeReturnedOwned(unsigned Count) {
1513 return RefVal(ReturnedOwned, Count);
1514 }
1515
1516 static RefVal makeReturnedNotOwned() {
1517 return RefVal(ReturnedNotOwned);
1518 }
1519
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001520 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001521
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001522 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001523 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001524 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001525
Ted Kremenek272aa852008-06-25 21:21:56 +00001526 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001527 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001528 }
1529
1530 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001531 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001532 }
1533
1534 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001535 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001536 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001537
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001538 void Profile(llvm::FoldingSetNodeID& ID) const {
1539 ID.AddInteger((unsigned) kind);
1540 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001541 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001542 }
1543
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001544 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001545};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001546
1547void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001548 if (!T.isNull())
1549 Out << "Tracked Type:" << T.getAsString() << '\n';
1550
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001551 switch (getKind()) {
1552 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001553 case Owned: {
1554 Out << "Owned";
1555 unsigned cnt = getCount();
1556 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001557 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001558 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001559
Ted Kremenekc4f81022008-04-10 23:09:18 +00001560 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001561 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001562 unsigned cnt = getCount();
1563 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001564 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001565 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001566
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001567 case ReturnedOwned: {
1568 Out << "ReturnedOwned";
1569 unsigned cnt = getCount();
1570 if (cnt) Out << " (+ " << cnt << ")";
1571 break;
1572 }
1573
1574 case ReturnedNotOwned: {
1575 Out << "ReturnedNotOwned";
1576 unsigned cnt = getCount();
1577 if (cnt) Out << " (+ " << cnt << ")";
1578 break;
1579 }
1580
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001581 case Released:
1582 Out << "Released";
1583 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001584
1585 case ErrorDeallocGC:
1586 Out << "-dealloc (GC)";
1587 break;
1588
1589 case ErrorDeallocNotOwned:
1590 Out << "-dealloc (not-owned)";
1591 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001592
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001593 case ErrorLeak:
1594 Out << "Leaked";
1595 break;
1596
Ted Kremenek311f3d42008-10-22 23:56:21 +00001597 case ErrorLeakReturned:
1598 Out << "Leaked (Bad naming)";
1599 break;
1600
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001601 case ErrorUseAfterRelease:
1602 Out << "Use-After-Release [ERROR]";
1603 break;
1604
1605 case ErrorReleaseNotOwned:
1606 Out << "Release of Not-Owned [ERROR]";
1607 break;
1608 }
1609}
Ted Kremenek0d721572008-03-11 17:48:22 +00001610
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001611} // end anonymous namespace
1612
1613//===----------------------------------------------------------------------===//
1614// RefBindings - State used to track object reference counts.
1615//===----------------------------------------------------------------------===//
1616
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001617typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001618static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001619static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001620
1621namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001622 template<>
1623 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1624 static inline void* GDMIndex() { return &RefBIndex; }
1625 };
1626}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001627
1628//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001629// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001630//===----------------------------------------------------------------------===//
1631
Ted Kremenekb6578942009-02-24 19:15:11 +00001632typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1633typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1634typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001635
Ted Kremenekb6578942009-02-24 19:15:11 +00001636static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001637static int AutoRBIndex = 0;
1638
Ted Kremenekb6578942009-02-24 19:15:11 +00001639namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001640namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001641
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001642namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001643template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001644 : public GRStatePartialTrait<ARStack> {
1645 static inline void* GDMIndex() { return &AutoRBIndex; }
1646};
1647
1648template<> struct GRStateTrait<AutoreleasePoolContents>
1649 : public GRStatePartialTrait<ARPoolContents> {
1650 static inline void* GDMIndex() { return &AutoRCIndex; }
1651};
1652} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001653
Ted Kremenek681fb352009-03-20 17:34:15 +00001654static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1655 ARStack stack = state->get<AutoreleaseStack>();
1656 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1657}
1658
1659static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1660 SymbolRef sym) {
1661
1662 SymbolRef pool = GetCurrentAutoreleasePool(state);
1663 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1664 ARCounts newCnts(0);
1665
1666 if (cnts) {
1667 const unsigned *cnt = (*cnts).lookup(sym);
1668 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1669 }
1670 else
1671 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1672
1673 return state.set<AutoreleasePoolContents>(pool, newCnts);
1674}
1675
Ted Kremenek7aef4842008-04-16 20:40:59 +00001676//===----------------------------------------------------------------------===//
1677// Transfer functions.
1678//===----------------------------------------------------------------------===//
1679
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001680namespace {
1681
Ted Kremenek7d421f32008-04-09 23:49:11 +00001682class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001683public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001684 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001685 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001686 virtual void Print(std::ostream& Out, const GRState* state,
1687 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001688 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001689
1690private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001691 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1692 SummaryLogTy;
1693
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001694 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001695 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001696 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001697 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001698
Ted Kremenek708af042009-02-05 06:50:21 +00001699 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001700 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001701 BugType *leakWithinFunction, *leakAtReturn;
1702 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001703
Ted Kremenekb6578942009-02-24 19:15:11 +00001704 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1705 RefVal::Kind& hasErr);
1706
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001707 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1708 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001709 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001710 ExplodedNode<GRState>* Pred,
1711 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001712 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001713
Ted Kremenek0106e202008-10-24 20:32:50 +00001714 std::pair<GRStateRef, bool>
1715 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001716 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001717
Ted Kremenekb6578942009-02-24 19:15:11 +00001718public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001719 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001720 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001721 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1722 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001723 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001724
Ted Kremenek708af042009-02-05 06:50:21 +00001725 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001726
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001727 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001728
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001729 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1730 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001731 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001732
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001733 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001734 const LangOptions& getLangOptions() const { return LOpts; }
1735
Ted Kremenekc26c4692009-02-18 03:48:14 +00001736 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1737 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1738 return I == SummaryLog.end() ? 0 : I->second;
1739 }
1740
Ted Kremeneka7338b42008-03-11 06:39:11 +00001741 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001742
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001743 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001744 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001745 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001746 Expr* Ex,
1747 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001748 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001749 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001750 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001751
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001752 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001753 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001754 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001755 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001756 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001757
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001758
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001759 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001760 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001761 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001762 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001763 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001764
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001765 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001766 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001767 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001768 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001769 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001770
Ted Kremeneka42be302009-02-14 01:43:44 +00001771 // Stores.
1772 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1773
Ted Kremenekffefc352008-04-11 22:25:11 +00001774 // End-of-path.
1775
1776 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001777 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001778
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001779 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001780 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001781 GRStmtNodeBuilder<GRState>& Builder,
1782 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001783 Stmt* S, const GRState* state,
1784 SymbolReaper& SymReaper);
1785
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001786 // Return statements.
1787
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001788 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001789 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001790 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001791 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001792 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001793
1794 // Assumptions.
1795
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001796 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001797 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001798 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001799};
1800
1801} // end anonymous namespace
1802
Ted Kremenek681fb352009-03-20 17:34:15 +00001803static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1804 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001805 if (Sym)
1806 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001807 else
1808 Out << "<pool>";
1809 Out << ":{";
1810
1811 // Get the contents of the pool.
1812 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1813 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1814 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1815
1816 Out << '}';
1817}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001818
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001819void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1820 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001821
1822
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001823
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001824 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001825
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001826 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001827 Out << sep << nl;
1828
1829 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1830 Out << (*I).first << " : ";
1831 (*I).second.print(Out);
1832 Out << nl;
1833 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001834
1835 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001836 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001837 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001838
Ted Kremenek681fb352009-03-20 17:34:15 +00001839 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1840 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1841 PrintPool(Out, *I, state);
1842
1843 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001844}
1845
Ted Kremenek47a72422009-04-29 18:50:19 +00001846//===----------------------------------------------------------------------===//
1847// Error reporting.
1848//===----------------------------------------------------------------------===//
1849
1850namespace {
1851
1852 //===-------------===//
1853 // Bug Descriptions. //
1854 //===-------------===//
1855
1856 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1857 protected:
1858 CFRefCount& TF;
1859
1860 CFRefBug(CFRefCount* tf, const char* name)
1861 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1862 public:
1863
1864 CFRefCount& getTF() { return TF; }
1865 const CFRefCount& getTF() const { return TF; }
1866
1867 // FIXME: Eventually remove.
1868 virtual const char* getDescription() const = 0;
1869
1870 virtual bool isLeak() const { return false; }
1871 };
1872
1873 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1874 public:
1875 UseAfterRelease(CFRefCount* tf)
1876 : CFRefBug(tf, "Use-after-release") {}
1877
1878 const char* getDescription() const {
1879 return "Reference-counted object is used after it is released";
1880 }
1881 };
1882
1883 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1884 public:
1885 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1886
1887 const char* getDescription() const {
1888 return "Incorrect decrement of the reference count of an "
1889 "object is not owned at this point by the caller";
1890 }
1891 };
1892
1893 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1894 public:
1895 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1896 "-dealloc called while using GC") {}
1897
1898 const char *getDescription() const {
1899 return "-dealloc called while using GC";
1900 }
1901 };
1902
1903 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1904 public:
1905 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1906 "-dealloc sent to non-exclusively owned object") {}
1907
1908 const char *getDescription() const {
1909 return "-dealloc sent to object that may be referenced elsewhere";
1910 }
1911 };
1912
1913 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1914 const bool isReturn;
1915 protected:
1916 Leak(CFRefCount* tf, const char* name, bool isRet)
1917 : CFRefBug(tf, name), isReturn(isRet) {}
1918 public:
1919
1920 const char* getDescription() const { return ""; }
1921
1922 bool isLeak() const { return true; }
1923 };
1924
1925 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1926 public:
1927 LeakAtReturn(CFRefCount* tf, const char* name)
1928 : Leak(tf, name, true) {}
1929 };
1930
1931 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1932 public:
1933 LeakWithinFunction(CFRefCount* tf, const char* name)
1934 : Leak(tf, name, false) {}
1935 };
1936
1937 //===---------===//
1938 // Bug Reports. //
1939 //===---------===//
1940
1941 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1942 protected:
1943 SymbolRef Sym;
1944 const CFRefCount &TF;
1945 public:
1946 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1947 ExplodedNode<GRState> *n, SymbolRef sym)
1948 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1949
1950 virtual ~CFRefReport() {}
1951
1952 CFRefBug& getBugType() {
1953 return (CFRefBug&) RangedBugReport::getBugType();
1954 }
1955 const CFRefBug& getBugType() const {
1956 return (const CFRefBug&) RangedBugReport::getBugType();
1957 }
1958
1959 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1960 const SourceRange*& end) {
1961
1962 if (!getBugType().isLeak())
1963 RangedBugReport::getRanges(BR, beg, end);
1964 else
1965 beg = end = 0;
1966 }
1967
1968 SymbolRef getSymbol() const { return Sym; }
1969
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001970 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001971 const ExplodedNode<GRState>* N);
1972
1973 std::pair<const char**,const char**> getExtraDescriptiveText();
1974
1975 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1976 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001977 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00001978 };
1979
1980 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1981 SourceLocation AllocSite;
1982 const MemRegion* AllocBinding;
1983 public:
1984 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1985 ExplodedNode<GRState> *n, SymbolRef sym,
1986 GRExprEngine& Eng);
1987
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001988 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001989 const ExplodedNode<GRState>* N);
1990
1991 SourceLocation getLocation() const { return AllocSite; }
1992 };
1993} // end anonymous namespace
1994
1995void CFRefCount::RegisterChecks(BugReporter& BR) {
1996 useAfterRelease = new UseAfterRelease(this);
1997 BR.Register(useAfterRelease);
1998
1999 releaseNotOwned = new BadRelease(this);
2000 BR.Register(releaseNotOwned);
2001
2002 deallocGC = new DeallocGC(this);
2003 BR.Register(deallocGC);
2004
2005 deallocNotOwned = new DeallocNotOwned(this);
2006 BR.Register(deallocNotOwned);
2007
2008 // First register "return" leaks.
2009 const char* name = 0;
2010
2011 if (isGCEnabled())
2012 name = "Leak of returned object when using garbage collection";
2013 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2014 name = "Leak of returned object when not using garbage collection (GC) in "
2015 "dual GC/non-GC code";
2016 else {
2017 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2018 name = "Leak of returned object";
2019 }
2020
2021 leakAtReturn = new LeakAtReturn(this, name);
2022 BR.Register(leakAtReturn);
2023
2024 // Second, register leaks within a function/method.
2025 if (isGCEnabled())
2026 name = "Leak of object when using garbage collection";
2027 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2028 name = "Leak of object when not using garbage collection (GC) in "
2029 "dual GC/non-GC code";
2030 else {
2031 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2032 name = "Leak";
2033 }
2034
2035 leakWithinFunction = new LeakWithinFunction(this, name);
2036 BR.Register(leakWithinFunction);
2037
2038 // Save the reference to the BugReporter.
2039 this->BR = &BR;
2040}
2041
2042static const char* Msgs[] = {
2043 // GC only
2044 "Code is compiled to only use garbage collection",
2045 // No GC.
2046 "Code is compiled to use reference counts",
2047 // Hybrid, with GC.
2048 "Code is compiled to use either garbage collection (GC) or reference counts"
2049 " (non-GC). The bug occurs with GC enabled",
2050 // Hybrid, without GC
2051 "Code is compiled to use either garbage collection (GC) or reference counts"
2052 " (non-GC). The bug occurs in non-GC mode"
2053};
2054
2055std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2056 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2057
2058 switch (TF.getLangOptions().getGCMode()) {
2059 default:
2060 assert(false);
2061
2062 case LangOptions::GCOnly:
2063 assert (TF.isGCEnabled());
2064 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2065
2066 case LangOptions::NonGC:
2067 assert (!TF.isGCEnabled());
2068 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2069
2070 case LangOptions::HybridGC:
2071 if (TF.isGCEnabled())
2072 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2073 else
2074 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2075 }
2076}
2077
2078static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2079 ArgEffect X) {
2080 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2081 I!=E; ++I)
2082 if (*I == X) return true;
2083
2084 return false;
2085}
2086
2087PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2088 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002089 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002090
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002091 // Check if the type state has changed.
2092 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002093 GRStateRef PrevSt(PrevN->getState(), StMgr);
2094 GRStateRef CurrSt(N->getState(), StMgr);
2095
2096 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2097 if (!CurrT) return NULL;
2098
2099 const RefVal& CurrV = *CurrT;
2100 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2101
2102 // Create a string buffer to constain all the useful things we want
2103 // to tell the user.
2104 std::string sbuf;
2105 llvm::raw_string_ostream os(sbuf);
2106
2107 // This is the allocation site since the previous node had no bindings
2108 // for this symbol.
2109 if (!PrevT) {
2110 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2111
2112 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2113 // Get the name of the callee (if it is available).
2114 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2115 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2116 os << "Call to function '" << FD->getNameAsString() <<'\'';
2117 else
2118 os << "function call";
2119 }
2120 else {
2121 assert (isa<ObjCMessageExpr>(S));
2122 os << "Method";
2123 }
2124
2125 if (CurrV.getObjKind() == RetEffect::CF) {
2126 os << " returns a Core Foundation object with a ";
2127 }
2128 else {
2129 assert (CurrV.getObjKind() == RetEffect::ObjC);
2130 os << " returns an Objective-C object with a ";
2131 }
2132
2133 if (CurrV.isOwned()) {
2134 os << "+1 retain count (owning reference).";
2135
2136 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2137 assert(CurrV.getObjKind() == RetEffect::CF);
2138 os << " "
2139 "Core Foundation objects are not automatically garbage collected.";
2140 }
2141 }
2142 else {
2143 assert (CurrV.isNotOwned());
2144 os << "+0 retain count (non-owning reference).";
2145 }
2146
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002147 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002148 return new PathDiagnosticEventPiece(Pos, os.str());
2149 }
2150
2151 // Gather up the effects that were performed on the object at this
2152 // program point
2153 llvm::SmallVector<ArgEffect, 2> AEffects;
2154
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002155 if (const RetainSummary *Summ =
2156 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002157 // We only have summaries attached to nodes after evaluating CallExpr and
2158 // ObjCMessageExprs.
2159 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2160
2161 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2162 // Iterate through the parameter expressions and see if the symbol
2163 // was ever passed as an argument.
2164 unsigned i = 0;
2165
2166 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2167 AI!=AE; ++AI, ++i) {
2168
2169 // Retrieve the value of the argument. Is it the symbol
2170 // we are interested in?
2171 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2172 continue;
2173
2174 // We have an argument. Get the effect!
2175 AEffects.push_back(Summ->getArg(i));
2176 }
2177 }
2178 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2179 if (Expr *receiver = ME->getReceiver())
2180 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2181 // The symbol we are tracking is the receiver.
2182 AEffects.push_back(Summ->getReceiverEffect());
2183 }
2184 }
2185 }
2186
2187 do {
2188 // Get the previous type state.
2189 RefVal PrevV = *PrevT;
2190
2191 // Specially handle -dealloc.
2192 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2193 // Determine if the object's reference count was pushed to zero.
2194 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2195 // We may not have transitioned to 'release' if we hit an error.
2196 // This case is handled elsewhere.
2197 if (CurrV.getKind() == RefVal::Released) {
2198 assert(CurrV.getCount() == 0);
2199 os << "Object released by directly sending the '-dealloc' message";
2200 break;
2201 }
2202 }
2203
2204 // Specially handle CFMakeCollectable and friends.
2205 if (contains(AEffects, MakeCollectable)) {
2206 // Get the name of the function.
2207 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2208 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2209 const FunctionDecl* FD = X.getAsFunctionDecl();
2210 const std::string& FName = FD->getNameAsString();
2211
2212 if (TF.isGCEnabled()) {
2213 // Determine if the object's reference count was pushed to zero.
2214 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2215
2216 os << "In GC mode a call to '" << FName
2217 << "' decrements an object's retain count and registers the "
2218 "object with the garbage collector. ";
2219
2220 if (CurrV.getKind() == RefVal::Released) {
2221 assert(CurrV.getCount() == 0);
2222 os << "Since it now has a 0 retain count the object can be "
2223 "automatically collected by the garbage collector.";
2224 }
2225 else
2226 os << "An object must have a 0 retain count to be garbage collected. "
2227 "After this call its retain count is +" << CurrV.getCount()
2228 << '.';
2229 }
2230 else
2231 os << "When GC is not enabled a call to '" << FName
2232 << "' has no effect on its argument.";
2233
2234 // Nothing more to say.
2235 break;
2236 }
2237
2238 // Determine if the typestate has changed.
2239 if (!(PrevV == CurrV))
2240 switch (CurrV.getKind()) {
2241 case RefVal::Owned:
2242 case RefVal::NotOwned:
2243
2244 if (PrevV.getCount() == CurrV.getCount())
2245 return 0;
2246
2247 if (PrevV.getCount() > CurrV.getCount())
2248 os << "Reference count decremented.";
2249 else
2250 os << "Reference count incremented.";
2251
2252 if (unsigned Count = CurrV.getCount())
2253 os << " The object now has a +" << Count << " retain count.";
2254
2255 if (PrevV.getKind() == RefVal::Released) {
2256 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2257 os << " The object is not eligible for garbage collection until the "
2258 "retain count reaches 0 again.";
2259 }
2260
2261 break;
2262
2263 case RefVal::Released:
2264 os << "Object released.";
2265 break;
2266
2267 case RefVal::ReturnedOwned:
2268 os << "Object returned to caller as an owning reference (single retain "
2269 "count transferred to caller).";
2270 break;
2271
2272 case RefVal::ReturnedNotOwned:
2273 os << "Object returned to caller with a +0 (non-owning) retain count.";
2274 break;
2275
2276 default:
2277 return NULL;
2278 }
2279
2280 // Emit any remaining diagnostics for the argument effects (if any).
2281 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2282 E=AEffects.end(); I != E; ++I) {
2283
2284 // A bunch of things have alternate behavior under GC.
2285 if (TF.isGCEnabled())
2286 switch (*I) {
2287 default: break;
2288 case Autorelease:
2289 os << "In GC mode an 'autorelease' has no effect.";
2290 continue;
2291 case IncRefMsg:
2292 os << "In GC mode the 'retain' message has no effect.";
2293 continue;
2294 case DecRefMsg:
2295 os << "In GC mode the 'release' message has no effect.";
2296 continue;
2297 }
2298 }
2299 } while(0);
2300
2301 if (os.str().empty())
2302 return 0; // We have nothing to say!
2303
2304 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002305 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002306 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2307
2308 // Add the range by scanning the children of the statement for any bindings
2309 // to Sym.
2310 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2311 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2312 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2313 P->addRange(Exp->getSourceRange());
2314 break;
2315 }
2316
2317 return P;
2318}
2319
2320namespace {
2321 class VISIBILITY_HIDDEN FindUniqueBinding :
2322 public StoreManager::BindingsHandler {
2323 SymbolRef Sym;
2324 const MemRegion* Binding;
2325 bool First;
2326
2327 public:
2328 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2329
2330 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2331 SVal val) {
2332
2333 SymbolRef SymV = val.getAsSymbol();
2334 if (!SymV || SymV != Sym)
2335 return true;
2336
2337 if (Binding) {
2338 First = false;
2339 return false;
2340 }
2341 else
2342 Binding = R;
2343
2344 return true;
2345 }
2346
2347 operator bool() { return First && Binding; }
2348 const MemRegion* getRegion() { return Binding; }
2349 };
2350}
2351
2352static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2353GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2354 SymbolRef Sym) {
2355
2356 // Find both first node that referred to the tracked symbol and the
2357 // memory location that value was store to.
2358 const ExplodedNode<GRState>* Last = N;
2359 const MemRegion* FirstBinding = 0;
2360
2361 while (N) {
2362 const GRState* St = N->getState();
2363 RefBindings B = St->get<RefBindings>();
2364
2365 if (!B.lookup(Sym))
2366 break;
2367
2368 FindUniqueBinding FB(Sym);
2369 StateMgr.iterBindings(St, FB);
2370 if (FB) FirstBinding = FB.getRegion();
2371
2372 Last = N;
2373 N = N->pred_empty() ? NULL : *(N->pred_begin());
2374 }
2375
2376 return std::make_pair(Last, FirstBinding);
2377}
2378
2379PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002380CFRefReport::getEndPath(BugReporterContext& BRC,
2381 const ExplodedNode<GRState>* EndN) {
2382 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002383 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002384 BRC.addNotableSymbol(Sym);
2385 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002386}
2387
2388PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002389CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2390 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002391
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002392 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002393 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002394 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002395
2396 // We are reporting a leak. Walk up the graph to get to the first node where
2397 // the symbol appeared, and also get the first VarDecl that tracked object
2398 // is stored to.
2399 const ExplodedNode<GRState>* AllocNode = 0;
2400 const MemRegion* FirstBinding = 0;
2401
2402 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002403 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002404
2405 // Get the allocate site.
2406 assert(AllocNode);
2407 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2408
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002409 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002410 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2411
2412 // Compute an actual location for the leak. Sometimes a leak doesn't
2413 // occur at an actual statement (e.g., transition between blocks; end
2414 // of function) so we need to walk the graph and compute a real location.
2415 const ExplodedNode<GRState>* LeakN = EndN;
2416 PathDiagnosticLocation L;
2417
2418 while (LeakN) {
2419 ProgramPoint P = LeakN->getLocation();
2420
2421 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2422 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2423 break;
2424 }
2425 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2426 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2427 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2428 break;
2429 }
2430 }
2431
2432 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2433 }
2434
2435 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002436 const Decl &D = BRC.getCodeDecl();
2437 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002438 }
2439
2440 std::string sbuf;
2441 llvm::raw_string_ostream os(sbuf);
2442
2443 os << "Object allocated on line " << AllocLine;
2444
2445 if (FirstBinding)
2446 os << " and stored into '" << FirstBinding->getString() << '\'';
2447
2448 // Get the retain count.
2449 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2450
2451 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2452 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2453 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2454 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002455 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002456 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002457 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002458 << "') does not contain 'copy' or otherwise starts with"
2459 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002460 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002461 }
2462 else
2463 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002464 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002465
2466 return new PathDiagnosticEventPiece(L, os.str());
2467}
2468
2469
2470CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2471 ExplodedNode<GRState> *n,
2472 SymbolRef sym, GRExprEngine& Eng)
2473: CFRefReport(D, tf, n, sym)
2474{
2475
2476 // Most bug reports are cached at the location where they occured.
2477 // With leaks, we want to unique them by the location where they were
2478 // allocated, and only report a single path. To do this, we need to find
2479 // the allocation site of a piece of tracked memory, which we do via a
2480 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2481 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2482 // that all ancestor nodes that represent the allocation site have the
2483 // same SourceLocation.
2484 const ExplodedNode<GRState>* AllocNode = 0;
2485
2486 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2487 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2488
2489 // Get the SourceLocation for the allocation site.
2490 ProgramPoint P = AllocNode->getLocation();
2491 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2492
2493 // Fill in the description of the bug.
2494 Description.clear();
2495 llvm::raw_string_ostream os(Description);
2496 SourceManager& SMgr = Eng.getContext().getSourceManager();
2497 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002498 os << "Potential leak ";
2499 if (tf.isGCEnabled()) {
2500 os << "(when using garbage collection) ";
2501 }
2502 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002503
2504 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2505 if (AllocBinding)
2506 os << " and stored into '" << AllocBinding->getString() << '\'';
2507}
2508
2509//===----------------------------------------------------------------------===//
2510// Main checker logic.
2511//===----------------------------------------------------------------------===//
2512
Ted Kremenek272aa852008-06-25 21:21:56 +00002513/// GetReturnType - Used to get the return type of a message expression or
2514/// function call with the intention of affixing that type to a tracked symbol.
2515/// While the the return type can be queried directly from RetEx, when
2516/// invoking class methods we augment to the return type to be that of
2517/// a pointer to the class (as opposed it just being id).
2518static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2519
2520 QualType RetTy = RetE->getType();
2521
2522 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002523 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002524 if (!PT)
2525 return RetTy;
2526
2527 // If RetEx is not a message expression just return its type.
2528 // If RetEx is a message expression, return its types if it is something
2529 /// more specific than id.
2530
2531 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2532
Steve Naroff17c03822009-02-12 17:52:19 +00002533 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002534 return RetTy;
2535
2536 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2537
2538 // At this point we know the return type of the message expression is id.
2539 // If we have an ObjCInterceDecl, we know this is a call to a class method
2540 // whose type we can resolve. In such cases, promote the return type to
2541 // Class*.
2542 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2543}
2544
2545
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002546void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002547 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002548 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002549 Expr* Ex,
2550 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002551 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002552 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002553 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002554
Ted Kremeneka7338b42008-03-11 06:39:11 +00002555 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002556 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002557 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002558
2559 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002560 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002561 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002562 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002563 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002564
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002565 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002566 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002567 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002568
Ted Kremenek74556a12009-03-26 03:35:11 +00002569 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002570 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002571 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002572 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002573 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002574 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002575 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002576 }
2577 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002578 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002579
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002580 if (isa<Loc>(V)) {
2581 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002582 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002583 continue;
2584
2585 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002586
2587 // FIXME: Either this logic should also be replicated in GRSimpleVals
2588 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002589
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002590 // FIXME: We can have collisions on the conjured symbol if the
2591 // expression *I also creates conjured symbols. We probably want
2592 // to identify conjured symbols by an expression pair: the enclosing
2593 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002594 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002595
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002596 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002597
Ted Kremenek73ec7732009-05-06 18:19:24 +00002598 if (R) {
2599 // Are we dealing with an ElementRegion? If the element type is
2600 // a basic integer type (e.g., char, int) and the underying region
2601 // is also typed then strip off the ElementRegion.
2602 // FIXME: We really need to think about this for the general case
2603 // as sometimes we are reasoning about arrays and other times
2604 // about (char*), etc., is just a form of passing raw bytes.
2605 // e.g., void *p = alloca(); foo((char*)p);
2606 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2607 // Checking for 'integral type' is probably too promiscuous, but
2608 // we'll leave it in for now until we have a systematic way of
2609 // handling all of these cases. Eventually we need to come up
2610 // with an interface to StoreManager so that this logic can be
2611 // approriately delegated to the respective StoreManagers while
2612 // still allowing us to do checker-specific logic (e.g.,
2613 // invalidating reference counts), probably via callbacks.
2614 if (ER->getElementType()->isIntegralType())
2615 if (const TypedRegion *superReg =
2616 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2617 R = superReg;
2618 // FIXME: What about layers of ElementRegions?
2619 }
2620
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002621 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002622 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002623
Ted Kremenek53b24182009-03-04 22:56:43 +00002624 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002625 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002626
Ted Kremenek53b24182009-03-04 22:56:43 +00002627 if (R->isBoundable(Ctx)) {
2628 // Set the value of the variable to be a conjured symbol.
2629 unsigned Count = Builder.getCurrentBlockCount();
2630 QualType T = R->getRValueType(Ctx);
2631
Zhongxing Xu079dc352009-04-09 06:03:54 +00002632 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002633 ValueManager &ValMgr = Eng.getValueManager();
2634 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002635 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002636 }
2637 else if (const RecordType *RT = T->getAsStructureType()) {
2638 // Handle structs in a not so awesome way. Here we just
2639 // eagerly bind new symbols to the fields. In reality we
2640 // should have the store manager handle this. The idea is just
2641 // to prototype some basic functionality here. All of this logic
2642 // should one day soon just go away.
2643 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2644
2645 // No record definition. There is nothing we can do.
2646 if (!RD)
2647 continue;
2648
2649 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2650
2651 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002652 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2653 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002654
2655 // For now just handle scalar fields.
2656 FieldDecl *FD = *FI;
2657 QualType FT = FD->getType();
2658
2659 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002660 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002661 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002662 ValueManager &ValMgr = Eng.getValueManager();
2663 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002664 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002665 }
2666 }
2667 }
2668 else {
2669 // Just blast away other values.
2670 state = state.BindLoc(*MR, UnknownVal());
2671 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002672 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002673 }
2674 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002675 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002676 }
2677 else {
2678 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002679 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002680 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002681 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002682 else if (isa<nonloc::LocAsInteger>(V))
2683 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002684 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002685
Ted Kremenek272aa852008-06-25 21:21:56 +00002686 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002687 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002688 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002689 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002690 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002691 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002692 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002693 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002694 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002695 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002696 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002697 }
2698 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002699
Ted Kremenek272aa852008-06-25 21:21:56 +00002700 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002701 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002702 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002703 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002704 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002705 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002706
Ted Kremenekf2717b02008-07-18 17:24:20 +00002707 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002708 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002709
2710 switch (RE.getKind()) {
2711 default:
2712 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002713
Ted Kremenek8f90e712008-10-17 22:23:12 +00002714 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002715
Ted Kremenek455dd862008-04-11 20:23:24 +00002716 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002717 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2718 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002719
Ted Kremenek8f90e712008-10-17 22:23:12 +00002720 // FIXME: We eventually should handle structs and other compound types
2721 // that are returned by value.
2722
2723 QualType T = Ex->getType();
2724
Ted Kremenek79413a52008-11-13 06:10:40 +00002725 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002726 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002727 ValueManager &ValMgr = Eng.getValueManager();
2728 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002729 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002730 }
2731
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002732 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002733 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002734
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002735 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002736 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002737 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002738 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002739 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002740 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002741 break;
2742 }
2743
Ted Kremenek227c5372008-05-06 02:41:27 +00002744 case RetEffect::ReceiverAlias: {
2745 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002746 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002747 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002748 break;
2749 }
2750
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002751 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002752 case RetEffect::OwnedSymbol: {
2753 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002754 ValueManager &ValMgr = Eng.getValueManager();
2755 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2756 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2757 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2758 RetT));
2759 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002760
2761 // FIXME: Add a flag to the checker where allocations are assumed to
2762 // *not fail.
2763#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002764 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2765 bool isFeasible;
2766 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2767 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2768 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002769#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002770
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002771 break;
2772 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002773
2774 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002775 case RetEffect::NotOwnedSymbol: {
2776 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002777 ValueManager &ValMgr = Eng.getValueManager();
2778 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2779 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2780 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2781 RetT));
2782 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002783 break;
2784 }
2785 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002786
Ted Kremenek0dd65012009-02-18 02:00:25 +00002787 // Generate a sink node if we are at the end of a path.
2788 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002789 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2790 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002791
2792 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002793 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002794}
2795
2796
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002797void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002798 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002799 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002800 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002801 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002802 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002803 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002804 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002805
Ted Kremenek286e9852009-05-04 04:57:00 +00002806 assert(Summ);
2807 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002808 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002809}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002810
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002811void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002812 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002813 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002814 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002815 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002816 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002817
Ted Kremenek272aa852008-06-25 21:21:56 +00002818 if (Expr* Receiver = ME->getReceiver()) {
2819 // We need the type-information of the tracked receiver object
2820 // Retrieve it from the state.
2821 ObjCInterfaceDecl* ID = 0;
2822
2823 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2824 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002825 // FIXME: Is this really working as expected? There are cases where
2826 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002827 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002828 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002829
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002830 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002831 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002832 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002833 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002834
2835 if (const PointerType* PT = Ty->getAsPointerType()) {
2836 QualType PointeeTy = PT->getPointeeType();
2837
2838 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2839 ID = IT->getDecl();
2840 }
2841 }
2842 }
2843
Ted Kremenek04e00302009-04-29 17:09:14 +00002844 // FIXME: The receiver could be a reference to a class, meaning that
2845 // we should use the class method.
2846 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002847
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002848 // Special-case: are we sending a mesage to "self"?
2849 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002850 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2851 if (Expr* Receiver = ME->getReceiver()) {
2852 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2853 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2854 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2855 // Update the summary to make the default argument effect
2856 // 'StopTracking'.
2857 Summ = Summaries.copySummary(Summ);
2858 Summ->setDefaultArgEffect(StopTracking);
2859 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002860 }
2861 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002862 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002863 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002864 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002865
Ted Kremenek286e9852009-05-04 04:57:00 +00002866 if (!Summ)
2867 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002868
Ted Kremenek286e9852009-05-04 04:57:00 +00002869 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002870 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002871}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002872
2873namespace {
2874class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2875 GRStateRef state;
2876public:
2877 StopTrackingCallback(GRStateRef st) : state(st) {}
2878 GRStateRef getState() { return state; }
2879
2880 bool VisitSymbol(SymbolRef sym) {
2881 state = state.remove<RefBindings>(sym);
2882 return true;
2883 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002884
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002885 const GRState* getState() const { return state.getState(); }
2886};
2887} // end anonymous namespace
2888
2889
Ted Kremeneka42be302009-02-14 01:43:44 +00002890void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002891 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002892 bool escapes = false;
2893
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002894 // A value escapes in three possible cases (this may change):
2895 //
2896 // (1) we are binding to something that is not a memory region.
2897 // (2) we are binding to a memregion that does not have stack storage
2898 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002899 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002900 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002901
Ted Kremeneka42be302009-02-14 01:43:44 +00002902 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002903 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002904 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002905 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2906 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002907
2908 if (!escapes) {
2909 // To test (3), generate a new state with the binding removed. If it is
2910 // the same state, then it escapes (since the store cannot represent
2911 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002912 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002913 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002914 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002915
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002916 // If our store can represent the binding and we aren't storing to something
2917 // that doesn't have local storage then just return and have the simulation
2918 // state continue as is.
2919 if (!escapes)
2920 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002921
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002922 // Otherwise, find all symbols referenced by 'val' that we are tracking
2923 // and stop tracking them.
2924 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002925}
2926
Ted Kremenek0106e202008-10-24 20:32:50 +00002927std::pair<GRStateRef,bool>
2928CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2929 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002930 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002931 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002932
Ted Kremenek47a72422009-04-29 18:50:19 +00002933 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002934 hasLeak = V.isOwned() ||
2935 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002936
Ted Kremenek47a72422009-04-29 18:50:19 +00002937 GRStateRef state(St, VMgr);
2938
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002939 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002940 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002941
Ted Kremenek0106e202008-10-24 20:32:50 +00002942 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2943 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002944}
2945
Ted Kremenek541db372008-04-24 23:57:27 +00002946
Ted Kremenekffefc352008-04-11 22:25:11 +00002947
Ted Kremenek541db372008-04-24 23:57:27 +00002948// Dead symbols.
2949
Ted Kremenek708af042009-02-05 06:50:21 +00002950
Ted Kremenek541db372008-04-24 23:57:27 +00002951
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002952 // Return statements.
2953
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002954void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002955 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002956 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002957 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002958 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002959
2960 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002961 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002962 return;
2963
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002964 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002965 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002966
Ted Kremenek74556a12009-03-26 03:35:11 +00002967 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002968 return;
2969
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002970 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002971 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002972
2973 if (!T)
2974 return;
2975
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002976 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002977 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002978
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002979 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002980 case RefVal::Owned: {
2981 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002982 assert (cnt > 0);
2983 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002984 break;
2985 }
2986
2987 case RefVal::NotOwned: {
2988 unsigned cnt = X.getCount();
2989 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2990 : RefVal::makeReturnedNotOwned();
2991 break;
2992 }
2993
2994 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002995 return;
2996 }
2997
2998 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002999 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003000 Pred = Builder.MakeNode(Dst, S, Pred, state);
3001
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003002 // Did we cache out?
3003 if (!Pred)
3004 return;
3005
Ted Kremenek47a72422009-04-29 18:50:19 +00003006 // Any leaks or other errors?
3007 if (X.isReturnedOwned() && X.getCount() == 0) {
3008 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3009
Ted Kremenek314b1952009-04-29 23:03:22 +00003010 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003011 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3012 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003013 static int ReturnOwnLeakTag = 0;
3014 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00003015 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003016 if (ExplodedNode<GRState> *N =
3017 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
3018 CFRefLeakReport *report =
3019 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3020 N, Sym, Eng);
3021 BR->EmitReport(report);
3022 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003023 }
3024 }
3025 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003026}
3027
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003028// Assumptions.
3029
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003030const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3031 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003032 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003033 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003034
3035 // FIXME: We may add to the interface of EvalAssume the list of symbols
3036 // whose assumptions have changed. For now we just iterate through the
3037 // bindings and check if any of the tracked symbols are NULL. This isn't
3038 // too bad since the number of symbols we will track in practice are
3039 // probably small and EvalAssume is only called at branches and a few
3040 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003041 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003042
3043 if (B.isEmpty())
3044 return St;
3045
3046 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003047
3048 GRStateRef state(St, VMgr);
3049 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003050
3051 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003052 // Check if the symbol is null (or equal to any constant).
3053 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003054 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003055 changed = true;
3056 B = RefBFactory.Remove(B, I.getKey());
3057 }
3058 }
3059
Ted Kremenek91781202008-08-17 03:20:02 +00003060 if (changed)
3061 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003062
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003063 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003064}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003065
Ted Kremenekb6578942009-02-24 19:15:11 +00003066GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3067 RefVal V, ArgEffect E,
3068 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003069
3070 // In GC mode [... release] and [... retain] do nothing.
3071 switch (E) {
3072 default: break;
3073 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3074 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003075 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003076 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3077 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003078 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003079
Ted Kremenek6537a642009-03-17 19:42:23 +00003080 // Handle all use-after-releases.
3081 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3082 V = V ^ RefVal::ErrorUseAfterRelease;
3083 hasErr = V.getKind();
3084 return state.set<RefBindings>(sym, V);
3085 }
3086
Ted Kremenek0d721572008-03-11 17:48:22 +00003087 switch (E) {
3088 default:
3089 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003090
3091 case Dealloc:
3092 // Any use of -dealloc in GC is *bad*.
3093 if (isGCEnabled()) {
3094 V = V ^ RefVal::ErrorDeallocGC;
3095 hasErr = V.getKind();
3096 break;
3097 }
3098
3099 switch (V.getKind()) {
3100 default:
3101 assert(false && "Invalid case.");
3102 case RefVal::Owned:
3103 // The object immediately transitions to the released state.
3104 V = V ^ RefVal::Released;
3105 V.clearCounts();
3106 return state.set<RefBindings>(sym, V);
3107 case RefVal::NotOwned:
3108 V = V ^ RefVal::ErrorDeallocNotOwned;
3109 hasErr = V.getKind();
3110 break;
3111 }
3112 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003113
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003114 case NewAutoreleasePool:
3115 assert(!isGCEnabled());
3116 return state.add<AutoreleaseStack>(sym);
3117
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003118 case MayEscape:
3119 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003120 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003121 break;
3122 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003123
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003124 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003125
Ted Kremenekede40b72008-07-09 18:11:16 +00003126 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003127 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003128 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003129
Ted Kremenek9b112d22009-01-28 21:44:40 +00003130 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003131 if (isGCEnabled())
3132 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003133
3134 // Update the autorelease counts.
3135 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003136
3137 // Fall-through.
3138
Ted Kremenek227c5372008-05-06 02:41:27 +00003139 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003140 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003141
Ted Kremenek0d721572008-03-11 17:48:22 +00003142 case IncRef:
3143 switch (V.getKind()) {
3144 default:
3145 assert(false);
3146
3147 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003148 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003149 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003150 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003151 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003152 // Non-GC cases are handled above.
3153 assert(isGCEnabled());
3154 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003155 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003156 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003157 break;
3158
Ted Kremenek272aa852008-06-25 21:21:56 +00003159 case SelfOwn:
3160 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003161 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003162 case DecRef:
3163 switch (V.getKind()) {
3164 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003165 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003166 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003167
Ted Kremenek272aa852008-06-25 21:21:56 +00003168 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003169 assert(V.getCount() > 0);
3170 if (V.getCount() == 1) V = V ^ RefVal::Released;
3171 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003172 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003173
Ted Kremenek272aa852008-06-25 21:21:56 +00003174 case RefVal::NotOwned:
3175 if (V.getCount() > 0)
3176 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003177 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003178 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003179 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003180 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003181 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003182
Ted Kremenek0d721572008-03-11 17:48:22 +00003183 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003184 // Non-GC cases are handled above.
3185 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003186 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003187 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003188 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003189 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003190 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003191 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003192 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003193}
3194
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003195//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003196// Handle dead symbols and end-of-path.
3197//===----------------------------------------------------------------------===//
3198
3199void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3200 GREndPathNodeBuilder<GRState>& Builder) {
3201
3202 const GRState* St = Builder.getState();
3203 RefBindings B = St->get<RefBindings>();
3204
3205 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3206 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3207
3208 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3209 bool hasLeak = false;
3210
3211 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003212 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3213 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003214
3215 St = X.first;
3216 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3217 }
3218
3219 if (Leaked.empty())
3220 return;
3221
3222 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3223
3224 if (!N)
3225 return;
3226
3227 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3228 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3229
3230 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3231 : leakWithinFunction);
3232 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003233 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003234 BR->EmitReport(report);
3235 }
3236}
3237
3238void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3239 GRExprEngine& Eng,
3240 GRStmtNodeBuilder<GRState>& Builder,
3241 ExplodedNode<GRState>* Pred,
3242 Stmt* S,
3243 const GRState* St,
3244 SymbolReaper& SymReaper) {
3245
Ted Kremenek876d8df2009-02-19 23:47:02 +00003246 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003247 RefBindings B = St->get<RefBindings>();
3248 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3249
3250 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3251 E = SymReaper.dead_end(); I != E; ++I) {
3252
3253 const RefVal* T = B.lookup(*I);
3254 if (!T) continue;
3255
3256 bool hasLeak = false;
3257
3258 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003259 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003260
3261 St = X.first;
3262
3263 if (hasLeak)
3264 Leaked.push_back(std::make_pair(*I,X.second));
3265 }
3266
Ted Kremenek876d8df2009-02-19 23:47:02 +00003267 if (!Leaked.empty()) {
3268 // Create a new intermediate node representing the leak point. We
3269 // use a special program point that represents this checker-specific
3270 // transition. We use the address of RefBIndex as a unique tag for this
3271 // checker. We will create another node (if we don't cache out) that
3272 // removes the retain-count bindings from the state.
3273 // NOTE: We use 'generateNode' so that it does interplay with the
3274 // auto-transition logic.
3275 ExplodedNode<GRState>* N =
3276 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003277
Ted Kremenek876d8df2009-02-19 23:47:02 +00003278 if (!N)
3279 return;
3280
3281 // Generate the bug reports.
3282 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3283 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3284
3285 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3286 : leakWithinFunction);
3287 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003288 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3289 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003290 BR->EmitReport(report);
3291 }
Ted Kremenek708af042009-02-05 06:50:21 +00003292
Ted Kremenek876d8df2009-02-19 23:47:02 +00003293 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003294 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003295
3296 // Now generate a new node that nukes the old bindings.
3297 GRStateRef state(St, Eng.getStateManager());
3298 RefBindings::Factory& F = state.get_context<RefBindings>();
3299
3300 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3301 E = SymReaper.dead_end(); I!=E; ++I)
3302 B = F.Remove(B, *I);
3303
3304 state = state.set<RefBindings>(B);
3305 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003306}
3307
3308void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3309 GRStmtNodeBuilder<GRState>& Builder,
3310 Expr* NodeExpr, Expr* ErrorExpr,
3311 ExplodedNode<GRState>* Pred,
3312 const GRState* St,
3313 RefVal::Kind hasErr, SymbolRef Sym) {
3314 Builder.BuildSinks = true;
3315 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3316
3317 if (!N) return;
3318
3319 CFRefBug *BT = 0;
3320
Ted Kremenek6537a642009-03-17 19:42:23 +00003321 switch (hasErr) {
3322 default:
3323 assert(false && "Unhandled error.");
3324 return;
3325 case RefVal::ErrorUseAfterRelease:
3326 BT = static_cast<CFRefBug*>(useAfterRelease);
3327 break;
3328 case RefVal::ErrorReleaseNotOwned:
3329 BT = static_cast<CFRefBug*>(releaseNotOwned);
3330 break;
3331 case RefVal::ErrorDeallocGC:
3332 BT = static_cast<CFRefBug*>(deallocGC);
3333 break;
3334 case RefVal::ErrorDeallocNotOwned:
3335 BT = static_cast<CFRefBug*>(deallocNotOwned);
3336 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003337 }
3338
Ted Kremenekc26c4692009-02-18 03:48:14 +00003339 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003340 report->addRange(ErrorExpr->getSourceRange());
3341 BR->EmitReport(report);
3342}
3343
3344//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003345// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003346//===----------------------------------------------------------------------===//
3347
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003348GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3349 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003350 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003351}