blob: e00ede090b5c4d8c6ffbd6fb64bfad9652a8b60b [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 Kremenek41a4bc62009-05-08 23:09:42 +0000162namespace {
163class VISIBILITY_HIDDEN GenericNodeBuilder {
164 GRStmtNodeBuilder<GRState> *SNB;
165 Stmt *S;
166 const void *tag;
167 GREndPathNodeBuilder<GRState> *ENB;
168public:
169 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
170 const void *t)
171 : SNB(&snb), S(s), tag(t), ENB(0) {}
172 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
173 : SNB(0), S(0), tag(0), ENB(&enb) {}
174
175 ExplodedNode<GRState> *MakeNode(const GRState *state,
176 ExplodedNode<GRState> *Pred) {
177 if (SNB)
Ted Kremenek3e3328d2009-05-09 01:50:57 +0000178 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000179
180 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000181 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000182 }
183};
184} // end anonymous namespace
185
Ted Kremenek7d421f32008-04-09 23:49:11 +0000186//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000187// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000188//===----------------------------------------------------------------------===//
189
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000190static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000191 IdentifierInfo* II = &Ctx.Idents.get(name);
192 return Ctx.Selectors.getSelector(0, &II);
193}
194
Ted Kremenek0e344d42008-05-06 00:30:21 +0000195static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
196 IdentifierInfo* II = &Ctx.Idents.get(name);
197 return Ctx.Selectors.getSelector(1, &II);
198}
199
Ted Kremenek272aa852008-06-25 21:21:56 +0000200//===----------------------------------------------------------------------===//
201// Type querying functions.
202//===----------------------------------------------------------------------===//
203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204static bool hasPrefix(const char* s, const char* prefix) {
205 if (!prefix)
206 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000207
Ted Kremenek17144e82009-01-12 21:45:02 +0000208 char c = *s;
209 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000210
Ted Kremenek17144e82009-01-12 21:45:02 +0000211 while (c != '\0' && cP != '\0') {
212 if (c != cP) break;
213 c = *(++s);
214 cP = *(++prefix);
215 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000216
Ted Kremenek17144e82009-01-12 21:45:02 +0000217 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000218}
219
Ted Kremenek17144e82009-01-12 21:45:02 +0000220static bool hasSuffix(const char* s, const char* suffix) {
221 const char* loc = strstr(s, suffix);
222 return loc && strcmp(suffix, loc) == 0;
223}
224
225static bool isRefType(QualType RetTy, const char* prefix,
226 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000227
Ted Kremenek2f289b62009-05-12 04:53:03 +0000228 // Recursively walk the typedef stack, allowing typedefs of reference types.
229 while (1) {
230 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
231 const char* TDName = TD->getDecl()->getIdentifier()->getName();
232 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
233 return true;
234
235 RetTy = TD->getDecl()->getUnderlyingType();
236 continue;
237 }
238 break;
Ted Kremenek17144e82009-01-12 21:45:02 +0000239 }
240
241 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000242 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000243
244 // Is the type void*?
245 const PointerType* PT = RetTy->getAsPointerType();
246 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000247 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000248
249 // Does the name start with the prefix?
250 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000251}
252
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000253//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000254// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000255//===----------------------------------------------------------------------===//
256
Ted Kremenek272aa852008-06-25 21:21:56 +0000257/// ArgEffect is used to summarize a function/method call's effect on a
258/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000259enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
260 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
261 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000262
Ted Kremeneka7338b42008-03-11 06:39:11 +0000263namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000264template <> struct FoldingSetTrait<ArgEffect> {
265static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
266 ID.AddInteger((unsigned) X);
267}
Ted Kremenek272aa852008-06-25 21:21:56 +0000268};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000269} // end llvm namespace
270
Ted Kremeneka56ae162009-05-03 05:20:50 +0000271/// ArgEffects summarizes the effects of a function/method call on all of
272/// its arguments.
273typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
274
Ted Kremeneka7338b42008-03-11 06:39:11 +0000275namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000276
277/// RetEffect is used to summarize a function/method call's behavior with
278/// respect to its return value.
279class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000280public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000281 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000282 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
283 OwnedWhenTrackedReceiver };
Ted Kremenek68621b92009-01-28 05:56:51 +0000284
285 enum ObjKind { CF, ObjC, AnyObj };
286
Ted Kremeneka7338b42008-03-11 06:39:11 +0000287private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000288 Kind K;
289 ObjKind O;
290 unsigned index;
291
292 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
293 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000294
Ted Kremeneka7338b42008-03-11 06:39:11 +0000295public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000296 Kind getKind() const { return K; }
297
298 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000299
300 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000301 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000302 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000303 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000304
Ted Kremenek314b1952009-04-29 23:03:22 +0000305 bool isOwned() const {
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000306 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
307 K == OwnedWhenTrackedReceiver;
Ted Kremenek314b1952009-04-29 23:03:22 +0000308 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +0000309
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000310 static RetEffect MakeOwnedWhenTrackedReceiver() {
311 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
312 }
313
Ted Kremenek272aa852008-06-25 21:21:56 +0000314 static RetEffect MakeAlias(unsigned Idx) {
315 return RetEffect(Alias, Idx);
316 }
317 static RetEffect MakeReceiverAlias() {
318 return RetEffect(ReceiverAlias);
319 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000320 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
321 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000322 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000323 static RetEffect MakeNotOwned(ObjKind o) {
324 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000325 }
326 static RetEffect MakeGCNotOwned() {
327 return RetEffect(GCNotOwnedSymbol, ObjC);
328 }
329
Ted Kremenek272aa852008-06-25 21:21:56 +0000330 static RetEffect MakeNoRet() {
331 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000332 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000333
Ted Kremenek272aa852008-06-25 21:21:56 +0000334 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000335 ID.AddInteger((unsigned)K);
336 ID.AddInteger((unsigned)O);
337 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000338 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000339};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000340
Ted Kremenek272aa852008-06-25 21:21:56 +0000341
Ted Kremenek2f226732009-05-04 05:31:22 +0000342class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000343 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
344 /// specifies the argument (starting from 0). This can be sparsely
345 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000346 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000347
348 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
349 /// do not have an entry in Args.
350 ArgEffect DefaultArgEffect;
351
Ted Kremenek272aa852008-06-25 21:21:56 +0000352 /// Receiver - If this summary applies to an Objective-C message expression,
353 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000354 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000355
356 /// Ret - The effect on the return value. Used to indicate if the
357 /// function/method call returns a new tracked symbol, returns an
358 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000359 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000360
Ted Kremenekf2717b02008-07-18 17:24:20 +0000361 /// EndPath - Indicates that execution of this method/function should
362 /// terminate the simulation of a path.
363 bool EndPath;
364
Ted Kremeneka7338b42008-03-11 06:39:11 +0000365public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000366 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000367 ArgEffect ReceiverEff, bool endpath = false)
368 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
369 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370
Ted Kremenek272aa852008-06-25 21:21:56 +0000371 /// getArg - Return the argument effect on the argument specified by
372 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000373 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000374 if (const ArgEffect *AE = Args.lookup(idx))
375 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000376
Ted Kremenekbcaff792008-05-06 15:44:25 +0000377 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000378 }
379
Ted Kremenek2f226732009-05-04 05:31:22 +0000380 /// setDefaultArgEffect - Set the default argument effect.
381 void setDefaultArgEffect(ArgEffect E) {
382 DefaultArgEffect = E;
383 }
384
385 /// setArg - Set the argument effect on the argument specified by idx.
386 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
387 Args = AF.Add(Args, idx, E);
388 }
389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000391 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000392
Ted Kremenek2f226732009-05-04 05:31:22 +0000393 /// setRetEffect - Set the effect of the return value of the call.
394 void setRetEffect(RetEffect E) { Ret = E; }
395
Ted Kremenekf2717b02008-07-18 17:24:20 +0000396 /// isEndPath - Returns true if executing the given method/function should
397 /// terminate the path.
398 bool isEndPath() const { return EndPath; }
399
Ted Kremenek272aa852008-06-25 21:21:56 +0000400 /// getReceiverEffect - Returns the effect on the receiver of the call.
401 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000402 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000403
Ted Kremenek2f226732009-05-04 05:31:22 +0000404 /// setReceiverEffect - Set the effect on the receiver of the call.
405 void setReceiverEffect(ArgEffect E) { Receiver = E; }
406
Ted Kremeneka56ae162009-05-03 05:20:50 +0000407 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000408
Ted Kremeneka56ae162009-05-03 05:20:50 +0000409 ExprIterator begin_args() const { return Args.begin(); }
410 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000411
Ted Kremeneka56ae162009-05-03 05:20:50 +0000412 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000413 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000414 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000415 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000416 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000417 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000418 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000419 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000420 }
421
422 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000423 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000424 }
425};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000426} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000427
Ted Kremenek272aa852008-06-25 21:21:56 +0000428//===----------------------------------------------------------------------===//
429// Data structures for constructing summaries.
430//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000431
Ted Kremenek272aa852008-06-25 21:21:56 +0000432namespace {
433class VISIBILITY_HIDDEN ObjCSummaryKey {
434 IdentifierInfo* II;
435 Selector S;
436public:
437 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
438 : II(ii), S(s) {}
439
Ted Kremenek314b1952009-04-29 23:03:22 +0000440 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000441 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +0000442
443 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
444 : II(d ? d->getIdentifier() : ii), S(s) {}
Ted Kremenek272aa852008-06-25 21:21:56 +0000445
446 ObjCSummaryKey(Selector s)
447 : II(0), S(s) {}
448
449 IdentifierInfo* getIdentifier() const { return II; }
450 Selector getSelector() const { return S; }
451};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000452}
453
454namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000455template <> struct DenseMapInfo<ObjCSummaryKey> {
456 static inline ObjCSummaryKey getEmptyKey() {
457 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
458 DenseMapInfo<Selector>::getEmptyKey());
459 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000460
Ted Kremenek272aa852008-06-25 21:21:56 +0000461 static inline ObjCSummaryKey getTombstoneKey() {
462 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
463 DenseMapInfo<Selector>::getTombstoneKey());
464 }
465
466 static unsigned getHashValue(const ObjCSummaryKey &V) {
467 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
468 & 0x88888888)
469 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
470 & 0x55555555);
471 }
472
473 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
474 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
475 RHS.getIdentifier()) &&
476 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
477 RHS.getSelector());
478 }
479
480 static bool isPod() {
481 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
482 DenseMapInfo<Selector>::isPod();
483 }
484};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000485} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000486
Ted Kremenek84f010c2008-06-23 23:30:29 +0000487namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000488class VISIBILITY_HIDDEN ObjCSummaryCache {
489 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
490 MapTy M;
491public:
492 ObjCSummaryCache() {}
493
494 typedef MapTy::iterator iterator;
495
Ted Kremenek314b1952009-04-29 23:03:22 +0000496 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
497 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000498 // Lookup the method using the decl for the class @interface. If we
499 // have no decl, lookup using the class name.
500 return D ? find(D, S) : find(ClsName, S);
501 }
502
Ted Kremenek314b1952009-04-29 23:03:22 +0000503 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000504 // Do a lookup with the (D,S) pair. If we find a match return
505 // the iterator.
506 ObjCSummaryKey K(D, S);
507 MapTy::iterator I = M.find(K);
508
509 if (I != M.end() || !D)
510 return I;
511
512 // Walk the super chain. If we find a hit with a parent, we'll end
513 // up returning that summary. We actually allow that key (null,S), as
514 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
515 // generate initial summaries without having to worry about NSObject
516 // being declared.
517 // FIXME: We may change this at some point.
518 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
519 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
520 break;
521
522 if (!C)
523 return I;
524 }
525
526 // Cache the summary with original key to make the next lookup faster
527 // and return the iterator.
528 M[K] = I->second;
529 return I;
530 }
531
Ted Kremenek9449ca92008-08-12 20:41:56 +0000532
Ted Kremenek272aa852008-06-25 21:21:56 +0000533 iterator find(Expr* Receiver, Selector S) {
534 return find(getReceiverDecl(Receiver), S);
535 }
536
537 iterator find(IdentifierInfo* II, Selector S) {
538 // FIXME: Class method lookup. Right now we dont' have a good way
539 // of going between IdentifierInfo* and the class hierarchy.
540 iterator I = M.find(ObjCSummaryKey(II, S));
541 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
542 }
543
544 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
545
546 const PointerType* PT = E->getType()->getAsPointerType();
547 if (!PT) return 0;
548
549 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
550 if (!OI) return 0;
551
552 return OI ? OI->getDecl() : 0;
553 }
554
555 iterator end() { return M.end(); }
556
557 RetainSummary*& operator[](ObjCMessageExpr* ME) {
558
559 Selector S = ME->getSelector();
560
561 if (Expr* Receiver = ME->getReceiver()) {
562 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
563 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
564 }
565
566 return M[ObjCSummaryKey(ME->getClassName(), S)];
567 }
568
569 RetainSummary*& operator[](ObjCSummaryKey K) {
570 return M[K];
571 }
572
573 RetainSummary*& operator[](Selector S) {
574 return M[ ObjCSummaryKey(S) ];
575 }
576};
577} // end anonymous namespace
578
579//===----------------------------------------------------------------------===//
580// Data structures for managing collections of summaries.
581//===----------------------------------------------------------------------===//
582
583namespace {
584class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000585
586 //==-----------------------------------------------------------------==//
587 // Typedefs.
588 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000589
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000590 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
591 FuncSummariesTy;
592
Ted Kremenek84f010c2008-06-23 23:30:29 +0000593 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000594
595 //==-----------------------------------------------------------------==//
596 // Data.
597 //==-----------------------------------------------------------------==//
598
Ted Kremenek272aa852008-06-25 21:21:56 +0000599 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000600 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000601
Ted Kremenekede40b72008-07-09 18:11:16 +0000602 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
603 /// "CFDictionaryCreate".
604 IdentifierInfo* CFDictionaryCreateII;
605
Ted Kremenek272aa852008-06-25 21:21:56 +0000606 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000607 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000608
Ted Kremenek272aa852008-06-25 21:21:56 +0000609 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000610 FuncSummariesTy FuncSummaries;
611
Ted Kremenek272aa852008-06-25 21:21:56 +0000612 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
613 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000614 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000615
Ted Kremenek272aa852008-06-25 21:21:56 +0000616 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000617 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000618
Ted Kremenek272aa852008-06-25 21:21:56 +0000619 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
620 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000621 llvm::BumpPtrAllocator BPAlloc;
622
Ted Kremeneka56ae162009-05-03 05:20:50 +0000623 /// AF - A factory for ArgEffects objects.
624 ArgEffects::Factory AF;
625
Ted Kremenek272aa852008-06-25 21:21:56 +0000626 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000627 ArgEffects ScratchArgs;
628
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000629 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
630 /// objects.
631 RetEffect ObjCAllocRetE;
632
Ted Kremenek286e9852009-05-04 04:57:00 +0000633 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000634 RetainSummary* StopSummary;
635
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000636 //==-----------------------------------------------------------------==//
637 // Methods.
638 //==-----------------------------------------------------------------==//
639
Ted Kremenek272aa852008-06-25 21:21:56 +0000640 /// getArgEffects - Returns a persistent ArgEffects object based on the
641 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000642 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000643
Ted Kremenek562c1302008-05-05 16:51:50 +0000644 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000645
646public:
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000647 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
648
Ted Kremenek2f226732009-05-04 05:31:22 +0000649 RetainSummary *getDefaultSummary() {
650 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
651 return new (Summ) RetainSummary(DefaultSummary);
652 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000653
Ted Kremenek064ef322009-02-23 16:51:39 +0000654 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000655
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000656 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
657 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000658 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000659
Ted Kremeneka56ae162009-05-03 05:20:50 +0000660 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000661 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000662 ArgEffect DefaultEff = MayEscape,
663 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000664
Ted Kremenek266d8b62008-05-06 02:26:56 +0000665 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000666 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000667 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000668 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000669 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000670
Ted Kremeneka821b792009-04-29 05:04:30 +0000671 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000672 if (StopSummary)
673 return StopSummary;
674
675 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
676 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000677
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000678 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000679 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000680
Ted Kremeneka821b792009-04-29 05:04:30 +0000681 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000682
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000683 void InitializeClassMethodSummaries();
684 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000685
Ted Kremenek9b42e062009-05-03 04:42:10 +0000686 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000687 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000688
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000689private:
690
Ted Kremenekf2717b02008-07-18 17:24:20 +0000691 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
692 RetainSummary* Summ) {
693 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
694 }
695
Ted Kremenek272aa852008-06-25 21:21:56 +0000696 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
697 ObjCClassMethodSummaries[S] = Summ;
698 }
699
700 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
701 ObjCMethodSummaries[S] = Summ;
702 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000703
704 void addClassMethSummary(const char* Cls, const char* nullaryName,
705 RetainSummary *Summ) {
706 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
707 Selector S = GetNullarySelector(nullaryName, Ctx);
708 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
709 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000710
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000711 void addInstMethSummary(const char* Cls, const char* nullaryName,
712 RetainSummary *Summ) {
713 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
714 Selector S = GetNullarySelector(nullaryName, Ctx);
715 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
716 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000717
718 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000719 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000720
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000721 while (const char* s = va_arg(argp, const char*))
722 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000723
724 return Ctx.Selectors.getSelector(II.size(), &II[0]);
725 }
726
727 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
728 RetainSummary* Summ, va_list argp) {
729 Selector S = generateSelector(argp);
730 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000731 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000732
733 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
734 va_list argp;
735 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000736 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000737 va_end(argp);
738 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000739
740 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
741 va_list argp;
742 va_start(argp, Summ);
743 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
744 va_end(argp);
745 }
746
747 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
748 va_list argp;
749 va_start(argp, Summ);
750 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
751 va_end(argp);
752 }
753
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000754 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000755 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
756 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000757 DoNothing, DoNothing, true);
758 va_list argp;
759 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000760 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000761 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000762 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000763
Ted Kremeneka7338b42008-03-11 06:39:11 +0000764public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000765
766 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000767 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000768 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000769 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000770 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
771 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000772 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
773 RetEffect::MakeNoRet() /* return effect */,
Ted Kremeneka13b0862009-05-11 18:30:24 +0000774 MayEscape, /* default argument effect */
775 DoNothing /* receiver effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000776 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000777
778 InitializeClassMethodSummaries();
779 InitializeMethodSummaries();
780 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000781
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000782 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000783
Ted Kremenekd13c1872008-06-24 03:56:45 +0000784 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000785
Ted Kremenek314b1952009-04-29 23:03:22 +0000786 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
787 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000788 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000789 ID, ME->getMethodDecl(), ME->getType());
790 }
791
Ted Kremenek04e00302009-04-29 17:09:14 +0000792 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000793 const ObjCInterfaceDecl* ID,
794 const ObjCMethodDecl *MD,
795 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000796
797 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000798 const ObjCInterfaceDecl *ID,
799 const ObjCMethodDecl *MD,
800 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000801
802 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
803 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
804 ME->getClassInfo().first,
805 ME->getMethodDecl(), ME->getType());
806 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000807
808 /// getMethodSummary - This version of getMethodSummary is used to query
809 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000810 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
811 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000812 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000813 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000814 IdentifierInfo *ClsName = ID->getIdentifier();
815 QualType ResultTy = MD->getResultType();
816
Ted Kremenek81eb4642009-04-30 05:47:23 +0000817 // Resolve the method decl last.
818 if (const ObjCMethodDecl *InterfaceMD =
819 ResolveToInterfaceMethodDecl(MD, Ctx))
820 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000821
Ted Kremenek91b89a42009-04-29 17:17:48 +0000822 if (MD->isInstanceMethod())
823 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
824 else
825 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
826 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000827
Ted Kremenek314b1952009-04-29 23:03:22 +0000828 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
829 Selector S, QualType RetTy);
830
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000831 void updateSummaryFromAnnotations(RetainSummary &Summ,
832 const ObjCMethodDecl *MD);
833
834 void updateSummaryFromAnnotations(RetainSummary &Summ,
835 const FunctionDecl *FD);
836
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000837 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000838
839 RetainSummary *copySummary(RetainSummary *OldSumm) {
840 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
841 new (Summ) RetainSummary(*OldSumm);
842 return Summ;
843 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000844};
845
846} // end anonymous namespace
847
848//===----------------------------------------------------------------------===//
849// Implementation of checker data structures.
850//===----------------------------------------------------------------------===//
851
Ted Kremeneka56ae162009-05-03 05:20:50 +0000852RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000853
Ted Kremeneka56ae162009-05-03 05:20:50 +0000854ArgEffects RetainSummaryManager::getArgEffects() {
855 ArgEffects AE = ScratchArgs;
856 ScratchArgs = AF.GetEmptyMap();
857 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000858}
859
Ted Kremenek266d8b62008-05-06 02:26:56 +0000860RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000861RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000862 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000863 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000864 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000865 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000866 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000867 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000868 return Summ;
869}
870
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000871//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000872// Predicates.
873//===----------------------------------------------------------------------===//
874
Ted Kremenek9b42e062009-05-03 04:42:10 +0000875bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000876 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000877 return false;
878
Ted Kremenek0d813552009-04-23 22:11:07 +0000879 // We assume that id<..>, id, and "Class" all represent tracked objects.
880 const PointerType *PT = Ty->getAsPointerType();
881 if (PT == 0)
882 return true;
883
884 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000885
886 // We assume that id<..>, id, and "Class" all represent tracked objects.
887 if (!OT)
888 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000889
890 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000891 // FIXME: We can memoize here if this gets too expensive.
892 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
893 ObjCInterfaceDecl* ID = OT->getDecl();
894
895 for ( ; ID ; ID = ID->getSuperClass())
896 if (ID->getIdentifier() == NSObjectII)
897 return true;
898
899 return false;
900}
901
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000902bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
903 return isRefType(T, "CF") || // Core Foundation.
904 isRefType(T, "CG") || // Core Graphics.
905 isRefType(T, "DADisk") || // Disk Arbitration API.
906 isRefType(T, "DADissenter") ||
907 isRefType(T, "DASessionRef");
908}
909
Ted Kremenek35920ed2009-01-07 00:39:56 +0000910//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000911// Summary creation for functions (largely uses of Core Foundation).
912//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000913
Ted Kremenek17144e82009-01-12 21:45:02 +0000914static bool isRetain(FunctionDecl* FD, const char* FName) {
915 const char* loc = strstr(FName, "Retain");
916 return loc && loc[sizeof("Retain")-1] == '\0';
917}
918
919static bool isRelease(FunctionDecl* FD, const char* FName) {
920 const char* loc = strstr(FName, "Release");
921 return loc && loc[sizeof("Release")-1] == '\0';
922}
923
Ted Kremenekd13c1872008-06-24 03:56:45 +0000924RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000925 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000926 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000927 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000928 return I->second;
929
Ted Kremenek64cddf12009-05-04 15:34:07 +0000930 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000931 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000932
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000933 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000934 // We generate "stop" summaries for implicitly defined functions.
935 if (FD->isImplicit()) {
936 S = getPersistentStopSummary();
937 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000938 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000939
Ted Kremenek064ef322009-02-23 16:51:39 +0000940 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000941 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000942 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000943 const char* FName = FD->getIdentifier()->getName();
944
Ted Kremenek38c6f022009-03-05 22:11:14 +0000945 // Strip away preceding '_'. Doing this here will effect all the checks
946 // down below.
947 while (*FName == '_') ++FName;
948
Ted Kremenek17144e82009-01-12 21:45:02 +0000949 // Inspect the result type.
950 QualType RetTy = FT->getResultType();
951
952 // FIXME: This should all be refactored into a chain of "summary lookup"
953 // filters.
954 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
955 // FIXES: <rdar://problem/6326900>
956 // This should be addressed using a API table. This strcmp is also
957 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000958 assert (ScratchArgs.isEmpty());
959 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000960 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
961 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000962 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000963
964 // Enable this code once the semantics of NSDeallocateObject are resolved
965 // for GC. <rdar://problem/6619988>
966#if 0
967 // Handle: NSDeallocateObject(id anObject);
968 // This method does allow 'nil' (although we don't check it now).
969 if (strcmp(FName, "NSDeallocateObject") == 0) {
970 return RetTy == Ctx.VoidTy
971 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
972 : getPersistentStopSummary();
973 }
974#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000975
976 // Handle: id NSMakeCollectable(CFTypeRef)
977 if (strcmp(FName, "NSMakeCollectable") == 0) {
978 S = (RetTy == Ctx.getObjCIdType())
979 ? getUnarySummary(FT, cfmakecollectable)
980 : getPersistentStopSummary();
981
982 break;
983 }
984
985 if (RetTy->isPointerType()) {
986 // For CoreFoundation ('CF') types.
987 if (isRefType(RetTy, "CF", &Ctx, FName)) {
988 if (isRetain(FD, FName))
989 S = getUnarySummary(FT, cfretain);
990 else if (strstr(FName, "MakeCollectable"))
991 S = getUnarySummary(FT, cfmakecollectable);
992 else
993 S = getCFCreateGetRuleSummary(FD, FName);
994
995 break;
996 }
997
998 // For CoreGraphics ('CG') types.
999 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1000 if (isRetain(FD, FName))
1001 S = getUnarySummary(FT, cfretain);
1002 else
1003 S = getCFCreateGetRuleSummary(FD, FName);
1004
1005 break;
1006 }
1007
1008 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1009 if (isRefType(RetTy, "DADisk") ||
1010 isRefType(RetTy, "DADissenter") ||
1011 isRefType(RetTy, "DASessionRef")) {
1012 S = getCFCreateGetRuleSummary(FD, FName);
1013 break;
1014 }
1015
1016 break;
1017 }
1018
1019 // Check for release functions, the only kind of functions that we care
1020 // about that don't return a pointer type.
1021 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001022 // Test for 'CGCF'.
1023 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1024 FName += 4;
1025 else
1026 FName += 2;
1027
1028 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001029 S = getUnarySummary(FT, cfrelease);
1030 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001031 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001032 // Remaining CoreFoundation and CoreGraphics functions.
1033 // We use to assume that they all strictly followed the ownership idiom
1034 // and that ownership cannot be transferred. While this is technically
1035 // correct, many methods allow a tracked object to escape. For example:
1036 //
1037 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1038 // CFDictionaryAddValue(y, key, x);
1039 // CFRelease(x);
1040 // ... it is okay to use 'x' since 'y' has a reference to it
1041 //
1042 // We handle this and similar cases with the follow heuristic. If the
1043 // function name contains "InsertValue", "SetValue" or "AddValue" then
1044 // we assume that arguments may "escape."
1045 //
1046 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1047 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001048 CStrInCStrNoCase(FName, "SetValue") ||
1049 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001050 ? MayEscape : DoNothing;
1051
1052 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001053 }
1054 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001055 }
1056 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001057
1058 if (!S)
1059 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001060
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001061 // Annotations override defaults.
1062 assert(S);
1063 updateSummaryFromAnnotations(*S, FD);
1064
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001065 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001066 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001067}
1068
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001069RetainSummary*
1070RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1071 const char* FName) {
1072
Ted Kremenek562c1302008-05-05 16:51:50 +00001073 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1074 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001075
Ted Kremenek562c1302008-05-05 16:51:50 +00001076 if (strstr(FName, "Get"))
1077 return getCFSummaryGetRule(FD);
1078
Ted Kremenek286e9852009-05-04 04:57:00 +00001079 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001080}
1081
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001082RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001083RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1084 UnaryFuncKind func) {
1085
Ted Kremenek17144e82009-01-12 21:45:02 +00001086 // Sanity check that this is *really* a unary function. This can
1087 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001088 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001089 if (!FTP || FTP->getNumArgs() != 1)
1090 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001091
Ted Kremeneka56ae162009-05-03 05:20:50 +00001092 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001093
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001094 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001095 case cfretain: {
1096 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001097 return getPersistentSummary(RetEffect::MakeAlias(0),
1098 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001099 }
1100
1101 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001102 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001103 return getPersistentSummary(RetEffect::MakeNoRet(),
1104 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001105 }
1106
1107 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001108 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001109 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001110 }
1111
1112 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001113 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001114 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001115 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001116}
1117
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001118RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001119 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001120
1121 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001122 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1123 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001124 }
1125
Ted Kremenek68621b92009-01-28 05:56:51 +00001126 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001127}
1128
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001129RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001130 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001131 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1132 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001133}
1134
Ted Kremeneka7338b42008-03-11 06:39:11 +00001135//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001136// Summary creation for Selectors.
1137//===----------------------------------------------------------------------===//
1138
Ted Kremenekbcaff792008-05-06 15:44:25 +00001139RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001140RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001141 assert(ScratchArgs.isEmpty());
1142 // 'init' methods conceptually return a newly allocated object and claim
1143 // the receiver.
1144 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
1145 return getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1146 DecRefMsg);
1147
1148 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001149}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001150
1151void
1152RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1153 const FunctionDecl *FD) {
1154 if (!FD)
1155 return;
1156
1157 // Determine if there is a special return effect for this method.
1158 if (isTrackedObjCObjectType(FD->getResultType())) {
1159 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1160 Summ.setRetEffect(ObjCAllocRetE);
1161 }
1162 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1163 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1164 }
1165 }
1166}
1167
1168void
1169RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1170 const ObjCMethodDecl *MD) {
1171 if (!MD)
1172 return;
1173
1174 // Determine if there is a special return effect for this method.
1175 if (isTrackedObjCObjectType(MD->getResultType())) {
1176 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1177 Summ.setRetEffect(ObjCAllocRetE);
1178 }
1179 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1180 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1181 }
1182 }
1183}
1184
Ted Kremenekbcaff792008-05-06 15:44:25 +00001185RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001186RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1187 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001188
Ted Kremenek578498a2009-04-29 00:42:39 +00001189 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001190 // Scan the method decl for 'void*' arguments. These should be treated
1191 // as 'StopTracking' because they are often used with delegates.
1192 // Delegates are a frequent form of false positives with the retain
1193 // count checker.
1194 unsigned i = 0;
1195 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1196 E = MD->param_end(); I != E; ++I, ++i)
1197 if (ParmVarDecl *PD = *I) {
1198 QualType Ty = Ctx.getCanonicalType(PD->getType());
1199 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001200 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001201 }
1202 }
1203
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001204 // Any special effect for the receiver?
1205 ArgEffect ReceiverEff = DoNothing;
1206
1207 // If one of the arguments in the selector has the keyword 'delegate' we
1208 // should stop tracking the reference count for the receiver. This is
1209 // because the reference count is quite possibly handled by a delegate
1210 // method.
1211 if (S.isKeywordSelector()) {
1212 const std::string &str = S.getAsString();
1213 assert(!str.empty());
1214 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1215 }
1216
Ted Kremenek174a0772009-04-23 23:08:22 +00001217 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001218 if (isTrackedObjCObjectType(RetTy)) {
1219 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1220 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001221 RetEffect E =
1222 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001223 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001224
1225 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001226 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001227
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001228 // Look for methods that return an owned core foundation object.
1229 if (isTrackedCFObjectType(RetTy)) {
1230 RetEffect E =
1231 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1232 ? RetEffect::MakeOwned(RetEffect::CF, true)
1233 : RetEffect::MakeNotOwned(RetEffect::CF);
1234
1235 return getPersistentSummary(E, ReceiverEff, MayEscape);
1236 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001237
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001238 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001239 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001240
Ted Kremenek2f226732009-05-04 05:31:22 +00001241 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001242}
1243
1244RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001245RetainSummaryManager::getInstanceMethodSummary(Selector S,
1246 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001247 const ObjCInterfaceDecl* ID,
1248 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001249 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001250
Ted Kremeneka821b792009-04-29 05:04:30 +00001251 // Look up a summary in our summary cache.
1252 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001253
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001254 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001255 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001256
Ted Kremeneka56ae162009-05-03 05:20:50 +00001257 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001258 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001259
Ted Kremenek2f226732009-05-04 05:31:22 +00001260 // "initXXX": pass-through for receiver.
1261 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1262 == InitRule)
1263 Summ = getInitMethodSummary(RetTy);
1264 else
1265 Summ = getCommonMethodSummary(MD, S, RetTy);
1266
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001267 // Annotations override defaults.
1268 updateSummaryFromAnnotations(*Summ, MD);
1269
Ted Kremenek2f226732009-05-04 05:31:22 +00001270 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001271 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001272 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001273}
1274
Ted Kremeneka7722b72008-05-06 21:26:51 +00001275RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001276RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001277 const ObjCInterfaceDecl *ID,
1278 const ObjCMethodDecl *MD,
1279 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001280
Ted Kremenek578498a2009-04-29 00:42:39 +00001281 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001282 ObjCMethodSummariesTy::iterator I =
1283 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001284
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001285 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001286 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001287
1288 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001289
1290 // Annotations override defaults.
1291 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001292
Ted Kremenek2f226732009-05-04 05:31:22 +00001293 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001294 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001295 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001296}
1297
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001298void RetainSummaryManager::InitializeClassMethodSummaries() {
1299 assert(ScratchArgs.isEmpty());
1300 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001301
Ted Kremenek272aa852008-06-25 21:21:56 +00001302 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1303 // NSObject and its derivatives.
1304 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1305 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1306 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001307
1308 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001309 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001310 GetNullarySelector("currentHandler", Ctx),
1311 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001312
1313 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001314 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001315 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1316 GetUnarySelector("addObject", Ctx),
1317 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001318 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001319
1320 // Create the summaries for [NSObject performSelector...]. We treat
1321 // these as 'stop tracking' for the arguments because they are often
1322 // used for delegates that can release the object. When we have better
1323 // inter-procedural analysis we can potentially do something better. This
1324 // workaround is to remove false positives.
1325 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1326 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1327 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1328 "afterDelay", NULL);
1329 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1330 "afterDelay", "inModes", NULL);
1331 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1332 "withObject", "waitUntilDone", NULL);
1333 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1334 "withObject", "waitUntilDone", "modes", NULL);
1335 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1336 "withObject", "waitUntilDone", NULL);
1337 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1338 "withObject", "waitUntilDone", "modes", NULL);
1339 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1340 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001341}
1342
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001343void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001344
Ted Kremeneka56ae162009-05-03 05:20:50 +00001345 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001346
Ted Kremeneka7722b72008-05-06 21:26:51 +00001347 // Create the "init" selector. It just acts as a pass-through for the
1348 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001349 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
1350 getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1351 DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001352
1353 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001354 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001355
1356 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001357 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1358
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001359 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001360 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001361
Ted Kremenek266d8b62008-05-06 02:26:56 +00001362 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001363 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001364 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001365 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001366
1367 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001368 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001369 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001370
1371 // Create the "drain" selector.
1372 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001373 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001374
1375 // Create the -dealloc summary.
1376 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1377 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001378
1379 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001380 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001381 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001382
Ted Kremenekaac82832009-02-23 17:45:03 +00001383 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001384 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001385 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001386 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001387
Ted Kremenek45642a42008-08-12 18:48:50 +00001388 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001389 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1390 // self-own themselves. However, they only do this once they are displayed.
1391 // Thus, we need to track an NSWindow's display status.
1392 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001393 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001394 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1395 StopTracking,
1396 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001397
1398 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1399
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001400#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001401 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001402 "styleMask", "backing", "defer", NULL);
1403
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001404 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001405 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001406#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001407
Ted Kremenek45642a42008-08-12 18:48:50 +00001408 // 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 Kremenek0b7f0512009-05-12 20:06:54 +00001414#if 0
1415 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001416 "styleMask", "backing", "defer", NULL);
1417
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001418 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001419 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001420#endif
Ted Kremenek272aa852008-06-25 21:21:56 +00001421
Ted Kremenekf2717b02008-07-18 17:24:20 +00001422 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001423 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1424 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001425
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001426 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1427 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001428}
1429
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001430//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001431// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001432//===----------------------------------------------------------------------===//
1433
Ted Kremeneka7338b42008-03-11 06:39:11 +00001434namespace {
1435
Ted Kremenek7d421f32008-04-09 23:49:11 +00001436class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001437public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001438 enum Kind {
1439 Owned = 0, // Owning reference.
1440 NotOwned, // Reference is not owned by still valid (not freed).
1441 Released, // Object has been released.
1442 ReturnedOwned, // Returned object passes ownership to caller.
1443 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001444 ERROR_START,
1445 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1446 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001447 ErrorUseAfterRelease, // Object used after released.
1448 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001449 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001450 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001451 ErrorLeakReturned, // A memory leak due to the returning method not having
1452 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001453 ErrorGCLeakReturned,
1454 ErrorOverAutorelease,
1455 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001456 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001457
1458private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001459 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001460 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001461 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001462 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001463 QualType T;
1464
Ted Kremenek4d99d342009-05-08 20:01:42 +00001465 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1466 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001467
Ted Kremenek68621b92009-01-28 05:56:51 +00001468 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001469 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001470
1471public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001472 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001473
1474 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001475
Ted Kremenek4d99d342009-05-08 20:01:42 +00001476 unsigned getCount() const { return Cnt; }
1477 unsigned getAutoreleaseCount() const { return ACnt; }
1478 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1479 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001480 void setCount(unsigned i) { Cnt = i; }
1481 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001482
Ted Kremenek272aa852008-06-25 21:21:56 +00001483 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001484
1485 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001486
Ted Kremenek6537a642009-03-17 19:42:23 +00001487 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001488
Ted Kremenek6537a642009-03-17 19:42:23 +00001489 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001490
Ted Kremenekffefc352008-04-11 22:25:11 +00001491 bool isOwned() const {
1492 return getKind() == Owned;
1493 }
1494
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001495 bool isNotOwned() const {
1496 return getKind() == NotOwned;
1497 }
1498
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001499 bool isReturnedOwned() const {
1500 return getKind() == ReturnedOwned;
1501 }
1502
1503 bool isReturnedNotOwned() const {
1504 return getKind() == ReturnedNotOwned;
1505 }
1506
1507 bool isNonLeakError() const {
1508 Kind k = getKind();
1509 return isError(k) && !isLeak(k);
1510 }
1511
Ted Kremenek68621b92009-01-28 05:56:51 +00001512 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1513 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001514 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001515 }
1516
Ted Kremenek68621b92009-01-28 05:56:51 +00001517 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1518 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001519 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001520 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001521
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001522 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001523
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001524 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001525 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001526 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001527
Ted Kremenek272aa852008-06-25 21:21:56 +00001528 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001529 return RefVal(getKind(), getObjKind(), getCount() - i,
1530 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001531 }
1532
1533 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001534 return RefVal(getKind(), getObjKind(), getCount() + i,
1535 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001536 }
1537
1538 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001539 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1540 getType());
1541 }
1542
1543 RefVal autorelease() const {
1544 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1545 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001546 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001547
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001548 void Profile(llvm::FoldingSetNodeID& ID) const {
1549 ID.AddInteger((unsigned) kind);
1550 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001551 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001552 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001553 }
1554
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001555 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001556};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001557
1558void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001559 if (!T.isNull())
1560 Out << "Tracked Type:" << T.getAsString() << '\n';
1561
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001562 switch (getKind()) {
1563 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001564 case Owned: {
1565 Out << "Owned";
1566 unsigned cnt = getCount();
1567 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001568 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001569 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001570
Ted Kremenekc4f81022008-04-10 23:09:18 +00001571 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001572 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001573 unsigned cnt = getCount();
1574 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001575 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001576 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001577
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001578 case ReturnedOwned: {
1579 Out << "ReturnedOwned";
1580 unsigned cnt = getCount();
1581 if (cnt) Out << " (+ " << cnt << ")";
1582 break;
1583 }
1584
1585 case ReturnedNotOwned: {
1586 Out << "ReturnedNotOwned";
1587 unsigned cnt = getCount();
1588 if (cnt) Out << " (+ " << cnt << ")";
1589 break;
1590 }
1591
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001592 case Released:
1593 Out << "Released";
1594 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001595
1596 case ErrorDeallocGC:
1597 Out << "-dealloc (GC)";
1598 break;
1599
1600 case ErrorDeallocNotOwned:
1601 Out << "-dealloc (not-owned)";
1602 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001603
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001604 case ErrorLeak:
1605 Out << "Leaked";
1606 break;
1607
Ted Kremenek311f3d42008-10-22 23:56:21 +00001608 case ErrorLeakReturned:
1609 Out << "Leaked (Bad naming)";
1610 break;
1611
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001612 case ErrorGCLeakReturned:
1613 Out << "Leaked (GC-ed at return)";
1614 break;
1615
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001616 case ErrorUseAfterRelease:
1617 Out << "Use-After-Release [ERROR]";
1618 break;
1619
1620 case ErrorReleaseNotOwned:
1621 Out << "Release of Not-Owned [ERROR]";
1622 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001623
1624 case RefVal::ErrorOverAutorelease:
1625 Out << "Over autoreleased";
1626 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001627
1628 case RefVal::ErrorReturnedNotOwned:
1629 Out << "Non-owned object returned instead of owned";
1630 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001631 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001632
1633 if (ACnt) {
1634 Out << " [ARC +" << ACnt << ']';
1635 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001636}
Ted Kremenek0d721572008-03-11 17:48:22 +00001637
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001638} // end anonymous namespace
1639
1640//===----------------------------------------------------------------------===//
1641// RefBindings - State used to track object reference counts.
1642//===----------------------------------------------------------------------===//
1643
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001644typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001645static int RefBIndex = 0;
1646
1647namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001648 template<>
1649 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1650 static inline void* GDMIndex() { return &RefBIndex; }
1651 };
1652}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001653
1654//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001655// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001656//===----------------------------------------------------------------------===//
1657
Ted Kremenekb6578942009-02-24 19:15:11 +00001658typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1659typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1660typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001661
Ted Kremenekb6578942009-02-24 19:15:11 +00001662static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001663static int AutoRBIndex = 0;
1664
Ted Kremenekb6578942009-02-24 19:15:11 +00001665namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001666namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001667
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001668namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001669template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001670 : public GRStatePartialTrait<ARStack> {
1671 static inline void* GDMIndex() { return &AutoRBIndex; }
1672};
1673
1674template<> struct GRStateTrait<AutoreleasePoolContents>
1675 : public GRStatePartialTrait<ARPoolContents> {
1676 static inline void* GDMIndex() { return &AutoRCIndex; }
1677};
1678} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001679
Ted Kremenek681fb352009-03-20 17:34:15 +00001680static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1681 ARStack stack = state->get<AutoreleaseStack>();
1682 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1683}
1684
1685static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1686 SymbolRef sym) {
1687
1688 SymbolRef pool = GetCurrentAutoreleasePool(state);
1689 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1690 ARCounts newCnts(0);
1691
1692 if (cnts) {
1693 const unsigned *cnt = (*cnts).lookup(sym);
1694 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1695 }
1696 else
1697 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1698
1699 return state.set<AutoreleasePoolContents>(pool, newCnts);
1700}
1701
Ted Kremenek7aef4842008-04-16 20:40:59 +00001702//===----------------------------------------------------------------------===//
1703// Transfer functions.
1704//===----------------------------------------------------------------------===//
1705
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001706namespace {
1707
Ted Kremenek7d421f32008-04-09 23:49:11 +00001708class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001709public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001710 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001711 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001712 virtual void Print(std::ostream& Out, const GRState* state,
1713 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001714 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001715
1716private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001717 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1718 SummaryLogTy;
1719
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001720 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001721 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001722 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001723 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001724
Ted Kremenek708af042009-02-05 06:50:21 +00001725 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001726 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001727 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001728 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001729 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001730 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001731
Ted Kremenekb6578942009-02-24 19:15:11 +00001732 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1733 RefVal::Kind& hasErr);
1734
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001735 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1736 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001737 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001738 ExplodedNode<GRState>* Pred,
1739 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001740 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001741
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001742 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1743 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1744
1745 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1746 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1747 GenericNodeBuilder &Builder,
1748 GRExprEngine &Eng,
1749 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001750
Ted Kremenekb6578942009-02-24 19:15:11 +00001751public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001752 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001753 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001754 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1755 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001756 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1757 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001758
Ted Kremenek708af042009-02-05 06:50:21 +00001759 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001760
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001761 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001762
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001763 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1764 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001765 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001766
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001767 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001768 const LangOptions& getLangOptions() const { return LOpts; }
1769
Ted Kremenekc26c4692009-02-18 03:48:14 +00001770 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1771 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1772 return I == SummaryLog.end() ? 0 : I->second;
1773 }
1774
Ted Kremeneka7338b42008-03-11 06:39:11 +00001775 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001776
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001777 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001778 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001779 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001780 Expr* Ex,
1781 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001782 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001783 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001784 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001785
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001786 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001787 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001788 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001789 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001790 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001791
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001792
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001793 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001794 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001795 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001796 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001797 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001798
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001799 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001800 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001801 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001802 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001803 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001804
Ted Kremeneka42be302009-02-14 01:43:44 +00001805 // Stores.
1806 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1807
Ted Kremenekffefc352008-04-11 22:25:11 +00001808 // End-of-path.
1809
1810 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001811 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001812
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001813 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001814 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001815 GRStmtNodeBuilder<GRState>& Builder,
1816 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001817 Stmt* S, const GRState* state,
1818 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001819
1820 std::pair<ExplodedNode<GRState>*, GRStateRef>
1821 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001822 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1823 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001824 // Return statements.
1825
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001826 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001827 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001828 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001829 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001830 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001831
1832 // Assumptions.
1833
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001834 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001835 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001836 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001837};
1838
1839} // end anonymous namespace
1840
Ted Kremenek681fb352009-03-20 17:34:15 +00001841static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1842 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001843 if (Sym)
1844 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001845 else
1846 Out << "<pool>";
1847 Out << ":{";
1848
1849 // Get the contents of the pool.
1850 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1851 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1852 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1853
1854 Out << '}';
1855}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001856
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001857void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1858 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001859
1860
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001861
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001862 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001863
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001864 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001865 Out << sep << nl;
1866
1867 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1868 Out << (*I).first << " : ";
1869 (*I).second.print(Out);
1870 Out << nl;
1871 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001872
1873 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001874 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001875 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001876
Ted Kremenek681fb352009-03-20 17:34:15 +00001877 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1878 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1879 PrintPool(Out, *I, state);
1880
1881 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001882}
1883
Ted Kremenek47a72422009-04-29 18:50:19 +00001884//===----------------------------------------------------------------------===//
1885// Error reporting.
1886//===----------------------------------------------------------------------===//
1887
1888namespace {
1889
1890 //===-------------===//
1891 // Bug Descriptions. //
1892 //===-------------===//
1893
1894 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1895 protected:
1896 CFRefCount& TF;
1897
1898 CFRefBug(CFRefCount* tf, const char* name)
1899 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1900 public:
1901
1902 CFRefCount& getTF() { return TF; }
1903 const CFRefCount& getTF() const { return TF; }
1904
1905 // FIXME: Eventually remove.
1906 virtual const char* getDescription() const = 0;
1907
1908 virtual bool isLeak() const { return false; }
1909 };
1910
1911 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1912 public:
1913 UseAfterRelease(CFRefCount* tf)
1914 : CFRefBug(tf, "Use-after-release") {}
1915
1916 const char* getDescription() const {
1917 return "Reference-counted object is used after it is released";
1918 }
1919 };
1920
1921 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1922 public:
1923 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1924
1925 const char* getDescription() const {
1926 return "Incorrect decrement of the reference count of an "
1927 "object is not owned at this point by the caller";
1928 }
1929 };
1930
1931 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1932 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001933 DeallocGC(CFRefCount *tf)
1934 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001935
1936 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001937 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001938 }
1939 };
1940
1941 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1942 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001943 DeallocNotOwned(CFRefCount *tf)
1944 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001945
1946 const char *getDescription() const {
1947 return "-dealloc sent to object that may be referenced elsewhere";
1948 }
1949 };
1950
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001951 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1952 public:
1953 OverAutorelease(CFRefCount *tf) :
1954 CFRefBug(tf, "Object sent -autorelease too many times") {}
1955
1956 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001957 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001958 }
1959 };
1960
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001961 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1962 public:
1963 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1964 CFRefBug(tf, "Method should return an owned object") {}
1965
1966 const char *getDescription() const {
1967 return "Object with +0 retain counts returned to caller where a +1 "
1968 "(owning) retain count is expected";
1969 }
1970 };
1971
Ted Kremenek47a72422009-04-29 18:50:19 +00001972 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1973 const bool isReturn;
1974 protected:
1975 Leak(CFRefCount* tf, const char* name, bool isRet)
1976 : CFRefBug(tf, name), isReturn(isRet) {}
1977 public:
1978
1979 const char* getDescription() const { return ""; }
1980
1981 bool isLeak() const { return true; }
1982 };
1983
1984 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1985 public:
1986 LeakAtReturn(CFRefCount* tf, const char* name)
1987 : Leak(tf, name, true) {}
1988 };
1989
1990 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1991 public:
1992 LeakWithinFunction(CFRefCount* tf, const char* name)
1993 : Leak(tf, name, false) {}
1994 };
1995
1996 //===---------===//
1997 // Bug Reports. //
1998 //===---------===//
1999
2000 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2001 protected:
2002 SymbolRef Sym;
2003 const CFRefCount &TF;
2004 public:
2005 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2006 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002007 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2008
2009 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2010 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002011 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002012
2013 virtual ~CFRefReport() {}
2014
2015 CFRefBug& getBugType() {
2016 return (CFRefBug&) RangedBugReport::getBugType();
2017 }
2018 const CFRefBug& getBugType() const {
2019 return (const CFRefBug&) RangedBugReport::getBugType();
2020 }
2021
2022 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2023 const SourceRange*& end) {
2024
2025 if (!getBugType().isLeak())
2026 RangedBugReport::getRanges(BR, beg, end);
2027 else
2028 beg = end = 0;
2029 }
2030
2031 SymbolRef getSymbol() const { return Sym; }
2032
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002033 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002034 const ExplodedNode<GRState>* N);
2035
2036 std::pair<const char**,const char**> getExtraDescriptiveText();
2037
2038 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2039 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002040 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002041 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002042
Ted Kremenek47a72422009-04-29 18:50:19 +00002043 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2044 SourceLocation AllocSite;
2045 const MemRegion* AllocBinding;
2046 public:
2047 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2048 ExplodedNode<GRState> *n, SymbolRef sym,
2049 GRExprEngine& Eng);
2050
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002051 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002052 const ExplodedNode<GRState>* N);
2053
2054 SourceLocation getLocation() const { return AllocSite; }
2055 };
2056} // end anonymous namespace
2057
2058void CFRefCount::RegisterChecks(BugReporter& BR) {
2059 useAfterRelease = new UseAfterRelease(this);
2060 BR.Register(useAfterRelease);
2061
2062 releaseNotOwned = new BadRelease(this);
2063 BR.Register(releaseNotOwned);
2064
2065 deallocGC = new DeallocGC(this);
2066 BR.Register(deallocGC);
2067
2068 deallocNotOwned = new DeallocNotOwned(this);
2069 BR.Register(deallocNotOwned);
2070
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002071 overAutorelease = new OverAutorelease(this);
2072 BR.Register(overAutorelease);
2073
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002074 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2075 BR.Register(returnNotOwnedForOwned);
2076
Ted Kremenek47a72422009-04-29 18:50:19 +00002077 // First register "return" leaks.
2078 const char* name = 0;
2079
2080 if (isGCEnabled())
2081 name = "Leak of returned object when using garbage collection";
2082 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2083 name = "Leak of returned object when not using garbage collection (GC) in "
2084 "dual GC/non-GC code";
2085 else {
2086 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2087 name = "Leak of returned object";
2088 }
2089
2090 leakAtReturn = new LeakAtReturn(this, name);
2091 BR.Register(leakAtReturn);
2092
2093 // Second, register leaks within a function/method.
2094 if (isGCEnabled())
2095 name = "Leak of object when using garbage collection";
2096 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2097 name = "Leak of object when not using garbage collection (GC) in "
2098 "dual GC/non-GC code";
2099 else {
2100 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2101 name = "Leak";
2102 }
2103
2104 leakWithinFunction = new LeakWithinFunction(this, name);
2105 BR.Register(leakWithinFunction);
2106
2107 // Save the reference to the BugReporter.
2108 this->BR = &BR;
2109}
2110
2111static const char* Msgs[] = {
2112 // GC only
2113 "Code is compiled to only use garbage collection",
2114 // No GC.
2115 "Code is compiled to use reference counts",
2116 // Hybrid, with GC.
2117 "Code is compiled to use either garbage collection (GC) or reference counts"
2118 " (non-GC). The bug occurs with GC enabled",
2119 // Hybrid, without GC
2120 "Code is compiled to use either garbage collection (GC) or reference counts"
2121 " (non-GC). The bug occurs in non-GC mode"
2122};
2123
2124std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2125 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2126
2127 switch (TF.getLangOptions().getGCMode()) {
2128 default:
2129 assert(false);
2130
2131 case LangOptions::GCOnly:
2132 assert (TF.isGCEnabled());
2133 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2134
2135 case LangOptions::NonGC:
2136 assert (!TF.isGCEnabled());
2137 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2138
2139 case LangOptions::HybridGC:
2140 if (TF.isGCEnabled())
2141 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2142 else
2143 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2144 }
2145}
2146
2147static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2148 ArgEffect X) {
2149 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2150 I!=E; ++I)
2151 if (*I == X) return true;
2152
2153 return false;
2154}
2155
2156PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2157 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002158 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002159
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002160 if (!isa<PostStmt>(N->getLocation()))
2161 return NULL;
2162
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002163 // Check if the type state has changed.
2164 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002165 GRStateRef PrevSt(PrevN->getState(), StMgr);
2166 GRStateRef CurrSt(N->getState(), StMgr);
2167
2168 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2169 if (!CurrT) return NULL;
2170
2171 const RefVal& CurrV = *CurrT;
2172 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2173
2174 // Create a string buffer to constain all the useful things we want
2175 // to tell the user.
2176 std::string sbuf;
2177 llvm::raw_string_ostream os(sbuf);
2178
2179 // This is the allocation site since the previous node had no bindings
2180 // for this symbol.
2181 if (!PrevT) {
2182 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2183
2184 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2185 // Get the name of the callee (if it is available).
2186 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2187 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2188 os << "Call to function '" << FD->getNameAsString() <<'\'';
2189 else
2190 os << "function call";
2191 }
2192 else {
2193 assert (isa<ObjCMessageExpr>(S));
2194 os << "Method";
2195 }
2196
2197 if (CurrV.getObjKind() == RetEffect::CF) {
2198 os << " returns a Core Foundation object with a ";
2199 }
2200 else {
2201 assert (CurrV.getObjKind() == RetEffect::ObjC);
2202 os << " returns an Objective-C object with a ";
2203 }
2204
2205 if (CurrV.isOwned()) {
2206 os << "+1 retain count (owning reference).";
2207
2208 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2209 assert(CurrV.getObjKind() == RetEffect::CF);
2210 os << " "
2211 "Core Foundation objects are not automatically garbage collected.";
2212 }
2213 }
2214 else {
2215 assert (CurrV.isNotOwned());
2216 os << "+0 retain count (non-owning reference).";
2217 }
2218
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002219 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002220 return new PathDiagnosticEventPiece(Pos, os.str());
2221 }
2222
2223 // Gather up the effects that were performed on the object at this
2224 // program point
2225 llvm::SmallVector<ArgEffect, 2> AEffects;
2226
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002227 if (const RetainSummary *Summ =
2228 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002229 // We only have summaries attached to nodes after evaluating CallExpr and
2230 // ObjCMessageExprs.
2231 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2232
2233 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2234 // Iterate through the parameter expressions and see if the symbol
2235 // was ever passed as an argument.
2236 unsigned i = 0;
2237
2238 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2239 AI!=AE; ++AI, ++i) {
2240
2241 // Retrieve the value of the argument. Is it the symbol
2242 // we are interested in?
2243 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2244 continue;
2245
2246 // We have an argument. Get the effect!
2247 AEffects.push_back(Summ->getArg(i));
2248 }
2249 }
2250 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2251 if (Expr *receiver = ME->getReceiver())
2252 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2253 // The symbol we are tracking is the receiver.
2254 AEffects.push_back(Summ->getReceiverEffect());
2255 }
2256 }
2257 }
2258
2259 do {
2260 // Get the previous type state.
2261 RefVal PrevV = *PrevT;
2262
2263 // Specially handle -dealloc.
2264 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2265 // Determine if the object's reference count was pushed to zero.
2266 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2267 // We may not have transitioned to 'release' if we hit an error.
2268 // This case is handled elsewhere.
2269 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002270 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002271 os << "Object released by directly sending the '-dealloc' message";
2272 break;
2273 }
2274 }
2275
2276 // Specially handle CFMakeCollectable and friends.
2277 if (contains(AEffects, MakeCollectable)) {
2278 // Get the name of the function.
2279 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2280 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2281 const FunctionDecl* FD = X.getAsFunctionDecl();
2282 const std::string& FName = FD->getNameAsString();
2283
2284 if (TF.isGCEnabled()) {
2285 // Determine if the object's reference count was pushed to zero.
2286 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2287
2288 os << "In GC mode a call to '" << FName
2289 << "' decrements an object's retain count and registers the "
2290 "object with the garbage collector. ";
2291
2292 if (CurrV.getKind() == RefVal::Released) {
2293 assert(CurrV.getCount() == 0);
2294 os << "Since it now has a 0 retain count the object can be "
2295 "automatically collected by the garbage collector.";
2296 }
2297 else
2298 os << "An object must have a 0 retain count to be garbage collected. "
2299 "After this call its retain count is +" << CurrV.getCount()
2300 << '.';
2301 }
2302 else
2303 os << "When GC is not enabled a call to '" << FName
2304 << "' has no effect on its argument.";
2305
2306 // Nothing more to say.
2307 break;
2308 }
2309
2310 // Determine if the typestate has changed.
2311 if (!(PrevV == CurrV))
2312 switch (CurrV.getKind()) {
2313 case RefVal::Owned:
2314 case RefVal::NotOwned:
2315
Ted Kremenek4d99d342009-05-08 20:01:42 +00002316 if (PrevV.getCount() == CurrV.getCount()) {
2317 // Did an autorelease message get sent?
2318 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2319 return 0;
2320
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002321 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002322 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002323 break;
2324 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002325
2326 if (PrevV.getCount() > CurrV.getCount())
2327 os << "Reference count decremented.";
2328 else
2329 os << "Reference count incremented.";
2330
2331 if (unsigned Count = CurrV.getCount())
2332 os << " The object now has a +" << Count << " retain count.";
2333
2334 if (PrevV.getKind() == RefVal::Released) {
2335 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2336 os << " The object is not eligible for garbage collection until the "
2337 "retain count reaches 0 again.";
2338 }
2339
2340 break;
2341
2342 case RefVal::Released:
2343 os << "Object released.";
2344 break;
2345
2346 case RefVal::ReturnedOwned:
2347 os << "Object returned to caller as an owning reference (single retain "
2348 "count transferred to caller).";
2349 break;
2350
2351 case RefVal::ReturnedNotOwned:
2352 os << "Object returned to caller with a +0 (non-owning) retain count.";
2353 break;
2354
2355 default:
2356 return NULL;
2357 }
2358
2359 // Emit any remaining diagnostics for the argument effects (if any).
2360 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2361 E=AEffects.end(); I != E; ++I) {
2362
2363 // A bunch of things have alternate behavior under GC.
2364 if (TF.isGCEnabled())
2365 switch (*I) {
2366 default: break;
2367 case Autorelease:
2368 os << "In GC mode an 'autorelease' has no effect.";
2369 continue;
2370 case IncRefMsg:
2371 os << "In GC mode the 'retain' message has no effect.";
2372 continue;
2373 case DecRefMsg:
2374 os << "In GC mode the 'release' message has no effect.";
2375 continue;
2376 }
2377 }
2378 } while(0);
2379
2380 if (os.str().empty())
2381 return 0; // We have nothing to say!
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002382
2383 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002384 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002385 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2386
2387 // Add the range by scanning the children of the statement for any bindings
2388 // to Sym.
2389 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2390 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2391 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2392 P->addRange(Exp->getSourceRange());
2393 break;
2394 }
2395
2396 return P;
2397}
2398
2399namespace {
2400 class VISIBILITY_HIDDEN FindUniqueBinding :
2401 public StoreManager::BindingsHandler {
2402 SymbolRef Sym;
2403 const MemRegion* Binding;
2404 bool First;
2405
2406 public:
2407 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2408
2409 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2410 SVal val) {
2411
2412 SymbolRef SymV = val.getAsSymbol();
2413 if (!SymV || SymV != Sym)
2414 return true;
2415
2416 if (Binding) {
2417 First = false;
2418 return false;
2419 }
2420 else
2421 Binding = R;
2422
2423 return true;
2424 }
2425
2426 operator bool() { return First && Binding; }
2427 const MemRegion* getRegion() { return Binding; }
2428 };
2429}
2430
2431static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2432GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2433 SymbolRef Sym) {
2434
2435 // Find both first node that referred to the tracked symbol and the
2436 // memory location that value was store to.
2437 const ExplodedNode<GRState>* Last = N;
2438 const MemRegion* FirstBinding = 0;
2439
2440 while (N) {
2441 const GRState* St = N->getState();
2442 RefBindings B = St->get<RefBindings>();
2443
2444 if (!B.lookup(Sym))
2445 break;
2446
2447 FindUniqueBinding FB(Sym);
2448 StateMgr.iterBindings(St, FB);
2449 if (FB) FirstBinding = FB.getRegion();
2450
2451 Last = N;
2452 N = N->pred_empty() ? NULL : *(N->pred_begin());
2453 }
2454
2455 return std::make_pair(Last, FirstBinding);
2456}
2457
2458PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002459CFRefReport::getEndPath(BugReporterContext& BRC,
2460 const ExplodedNode<GRState>* EndN) {
2461 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002462 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002463 BRC.addNotableSymbol(Sym);
2464 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002465}
2466
2467PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002468CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2469 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002470
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002471 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002472 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002473 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002474
2475 // We are reporting a leak. Walk up the graph to get to the first node where
2476 // the symbol appeared, and also get the first VarDecl that tracked object
2477 // is stored to.
2478 const ExplodedNode<GRState>* AllocNode = 0;
2479 const MemRegion* FirstBinding = 0;
2480
2481 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002482 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002483
2484 // Get the allocate site.
2485 assert(AllocNode);
2486 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2487
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002488 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002489 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2490
2491 // Compute an actual location for the leak. Sometimes a leak doesn't
2492 // occur at an actual statement (e.g., transition between blocks; end
2493 // of function) so we need to walk the graph and compute a real location.
2494 const ExplodedNode<GRState>* LeakN = EndN;
2495 PathDiagnosticLocation L;
2496
2497 while (LeakN) {
2498 ProgramPoint P = LeakN->getLocation();
2499
2500 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2501 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2502 break;
2503 }
2504 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2505 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2506 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2507 break;
2508 }
2509 }
2510
2511 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2512 }
2513
2514 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002515 const Decl &D = BRC.getCodeDecl();
2516 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002517 }
2518
2519 std::string sbuf;
2520 llvm::raw_string_ostream os(sbuf);
2521
2522 os << "Object allocated on line " << AllocLine;
2523
2524 if (FirstBinding)
2525 os << " and stored into '" << FirstBinding->getString() << '\'';
2526
2527 // Get the retain count.
2528 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2529
2530 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2531 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2532 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2533 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002534 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002535 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002536 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002537 << "') does not contain 'copy' or otherwise starts with"
2538 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002539 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002540 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002541 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2542 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2543 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002544 << "' is potentially leaked when using garbage collection. Callers "
2545 "of this method do not expect a returned object with a +1 retain "
2546 "count since they expect the object to be managed by the garbage "
2547 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002548 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002549 else
2550 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002551 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002552
2553 return new PathDiagnosticEventPiece(L, os.str());
2554}
2555
Ted Kremenek47a72422009-04-29 18:50:19 +00002556CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2557 ExplodedNode<GRState> *n,
2558 SymbolRef sym, GRExprEngine& Eng)
2559: CFRefReport(D, tf, n, sym)
2560{
2561
2562 // Most bug reports are cached at the location where they occured.
2563 // With leaks, we want to unique them by the location where they were
2564 // allocated, and only report a single path. To do this, we need to find
2565 // the allocation site of a piece of tracked memory, which we do via a
2566 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2567 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2568 // that all ancestor nodes that represent the allocation site have the
2569 // same SourceLocation.
2570 const ExplodedNode<GRState>* AllocNode = 0;
2571
2572 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002573 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002574
2575 // Get the SourceLocation for the allocation site.
2576 ProgramPoint P = AllocNode->getLocation();
2577 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2578
2579 // Fill in the description of the bug.
2580 Description.clear();
2581 llvm::raw_string_ostream os(Description);
2582 SourceManager& SMgr = Eng.getContext().getSourceManager();
2583 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002584 os << "Potential leak ";
2585 if (tf.isGCEnabled()) {
2586 os << "(when using garbage collection) ";
2587 }
2588 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002589
2590 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2591 if (AllocBinding)
2592 os << " and stored into '" << AllocBinding->getString() << '\'';
2593}
2594
2595//===----------------------------------------------------------------------===//
2596// Main checker logic.
2597//===----------------------------------------------------------------------===//
2598
Ted Kremenek272aa852008-06-25 21:21:56 +00002599/// GetReturnType - Used to get the return type of a message expression or
2600/// function call with the intention of affixing that type to a tracked symbol.
2601/// While the the return type can be queried directly from RetEx, when
2602/// invoking class methods we augment to the return type to be that of
2603/// a pointer to the class (as opposed it just being id).
2604static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2605
2606 QualType RetTy = RetE->getType();
2607
2608 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002609 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002610 if (!PT)
2611 return RetTy;
2612
2613 // If RetEx is not a message expression just return its type.
2614 // If RetEx is a message expression, return its types if it is something
2615 /// more specific than id.
2616
2617 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2618
Steve Naroff17c03822009-02-12 17:52:19 +00002619 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002620 return RetTy;
2621
2622 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2623
2624 // At this point we know the return type of the message expression is id.
2625 // If we have an ObjCInterceDecl, we know this is a call to a class method
2626 // whose type we can resolve. In such cases, promote the return type to
2627 // Class*.
2628 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2629}
2630
2631
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002632void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002633 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002634 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002635 Expr* Ex,
2636 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002637 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002638 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002639 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002640
Ted Kremeneka7338b42008-03-11 06:39:11 +00002641 // Get the state.
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002642 GRStateManager& StateMgr = Eng.getStateManager();
2643 GRStateRef state(Builder.GetState(Pred), StateMgr);
2644 ASTContext& Ctx = StateMgr.getContext();
2645 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek227c5372008-05-06 02:41:27 +00002646
2647 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002648 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002649 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002650 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002651 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002652
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002653 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002654 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002655 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002656
Ted Kremenek74556a12009-03-26 03:35:11 +00002657 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002658 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002659 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002660 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002661 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002662 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002663 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002664 }
2665 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002666 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002667
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002668 if (isa<Loc>(V)) {
2669 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002670 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002671 continue;
2672
2673 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002674
2675 // FIXME: Either this logic should also be replicated in GRSimpleVals
2676 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002677
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002678 // FIXME: We can have collisions on the conjured symbol if the
2679 // expression *I also creates conjured symbols. We probably want
2680 // to identify conjured symbols by an expression pair: the enclosing
2681 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002682 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002683
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002684 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002685
Ted Kremenek73ec7732009-05-06 18:19:24 +00002686 if (R) {
2687 // Are we dealing with an ElementRegion? If the element type is
2688 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xuea6851b2009-05-11 14:28:14 +00002689 // is a variable region then strip off the ElementRegion.
Ted Kremenek73ec7732009-05-06 18:19:24 +00002690 // FIXME: We really need to think about this for the general case
2691 // as sometimes we are reasoning about arrays and other times
2692 // about (char*), etc., is just a form of passing raw bytes.
2693 // e.g., void *p = alloca(); foo((char*)p);
2694 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2695 // Checking for 'integral type' is probably too promiscuous, but
2696 // we'll leave it in for now until we have a systematic way of
2697 // handling all of these cases. Eventually we need to come up
2698 // with an interface to StoreManager so that this logic can be
2699 // approriately delegated to the respective StoreManagers while
2700 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002701 // invalidating reference counts), probably via callbacks.
Ted Kremenek1cba5772009-05-11 22:55:17 +00002702 if (ER->getElementType()->isIntegralType()) {
2703 const MemRegion *superReg = ER->getSuperRegion();
2704 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2705 isa<ObjCIvarRegion>(superReg))
2706 R = cast<TypedRegion>(superReg);
2707 }
2708
Ted Kremenek73ec7732009-05-06 18:19:24 +00002709 // FIXME: What about layers of ElementRegions?
2710 }
2711
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002712 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002713 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002714
Ted Kremenek53b24182009-03-04 22:56:43 +00002715 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002716 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002717
Ted Kremenek53b24182009-03-04 22:56:43 +00002718 if (R->isBoundable(Ctx)) {
2719 // Set the value of the variable to be a conjured symbol.
2720 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002721 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002722
Zhongxing Xu079dc352009-04-09 06:03:54 +00002723 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002724 ValueManager &ValMgr = Eng.getValueManager();
2725 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002726 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002727 }
2728 else if (const RecordType *RT = T->getAsStructureType()) {
2729 // Handle structs in a not so awesome way. Here we just
2730 // eagerly bind new symbols to the fields. In reality we
2731 // should have the store manager handle this. The idea is just
2732 // to prototype some basic functionality here. All of this logic
2733 // should one day soon just go away.
2734 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2735
2736 // No record definition. There is nothing we can do.
2737 if (!RD)
2738 continue;
2739
2740 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2741
2742 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002743 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2744 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002745
2746 // For now just handle scalar fields.
2747 FieldDecl *FD = *FI;
2748 QualType FT = FD->getType();
2749
2750 if (Loc::IsLocType(FT) ||
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002751 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002752 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002753
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002754 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002755 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002756 }
2757 }
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002758 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2759 // Set the default value of the array to conjured symbol.
2760 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2761 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2762 Count);
2763 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2764 StateMgr);
2765 } else {
Ted Kremenek53b24182009-03-04 22:56:43 +00002766 // Just blast away other values.
2767 state = state.BindLoc(*MR, UnknownVal());
2768 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002769 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002770 }
2771 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002772 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002773 }
2774 else {
2775 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002776 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002777 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002778 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002779 else if (isa<nonloc::LocAsInteger>(V))
2780 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002781 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002782
Ted Kremenek272aa852008-06-25 21:21:56 +00002783 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002784 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002785 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002786 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002787 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002788 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002789 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002790 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002791 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002792 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002793 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002794 }
2795 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002796
Ted Kremenek272aa852008-06-25 21:21:56 +00002797 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002798 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002799 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002800 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002801 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002802 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002803
Ted Kremenekf2717b02008-07-18 17:24:20 +00002804 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002805 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002806
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002807 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2808 assert(Receiver);
2809 SVal V = state.GetSValAsScalarOrLoc(Receiver);
2810 bool found = false;
2811 if (SymbolRef Sym = V.getAsLocSymbol())
2812 if (state.get<RefBindings>(Sym)) {
2813 found = true;
2814 RE = Summaries.getObjAllocRetEffect();
2815 }
2816
2817 if (!found)
2818 RE = RetEffect::MakeNoRet();
2819 }
2820
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002821 switch (RE.getKind()) {
2822 default:
2823 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002824
Ted Kremenek8f90e712008-10-17 22:23:12 +00002825 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002826
Ted Kremenek455dd862008-04-11 20:23:24 +00002827 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002828 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2829 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002830
Ted Kremenek8f90e712008-10-17 22:23:12 +00002831 // FIXME: We eventually should handle structs and other compound types
2832 // that are returned by value.
2833
2834 QualType T = Ex->getType();
2835
Ted Kremenek79413a52008-11-13 06:10:40 +00002836 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002837 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002838 ValueManager &ValMgr = Eng.getValueManager();
2839 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002840 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002841 }
2842
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002843 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002844 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002845
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002846 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002847 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002848 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002849 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002850 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002851 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002852 break;
2853 }
2854
Ted Kremenek227c5372008-05-06 02:41:27 +00002855 case RetEffect::ReceiverAlias: {
2856 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002857 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002858 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002859 break;
2860 }
2861
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002862 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002863 case RetEffect::OwnedSymbol: {
2864 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002865 ValueManager &ValMgr = Eng.getValueManager();
2866 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2867 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2868 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2869 RetT));
2870 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002871
2872 // FIXME: Add a flag to the checker where allocations are assumed to
2873 // *not fail.
2874#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002875 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2876 bool isFeasible;
2877 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2878 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2879 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002880#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002881
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002882 break;
2883 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002884
2885 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002886 case RetEffect::NotOwnedSymbol: {
2887 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002888 ValueManager &ValMgr = Eng.getValueManager();
2889 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2890 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2891 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2892 RetT));
2893 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002894 break;
2895 }
2896 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002897
Ted Kremenek0dd65012009-02-18 02:00:25 +00002898 // Generate a sink node if we are at the end of a path.
2899 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002900 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2901 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002902
2903 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002904 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002905}
2906
2907
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002908void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002909 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002910 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002911 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002912 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002913 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002914 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002915 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002916
Ted Kremenek286e9852009-05-04 04:57:00 +00002917 assert(Summ);
2918 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002919 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002920}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002921
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002922void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002923 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002924 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002925 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002926 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002927 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002928
Ted Kremenek272aa852008-06-25 21:21:56 +00002929 if (Expr* Receiver = ME->getReceiver()) {
2930 // We need the type-information of the tracked receiver object
2931 // Retrieve it from the state.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002932 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek272aa852008-06-25 21:21:56 +00002933
2934 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2935 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002936 // FIXME: Is this really working as expected? There are cases where
2937 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002938 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002939 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002940
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002941 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002942 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002943 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002944 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002945
2946 if (const PointerType* PT = Ty->getAsPointerType()) {
2947 QualType PointeeTy = PT->getPointeeType();
2948
2949 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2950 ID = IT->getDecl();
2951 }
2952 }
2953 }
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002954
2955 // FIXME: this is a hack. This may or may not be the actual method
2956 // that is called.
2957 if (!ID) {
2958 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
2959 if (const ObjCInterfaceType *p =
2960 PT->getPointeeType()->getAsObjCInterfaceType())
2961 ID = p->getDecl();
2962 }
2963
Ted Kremenek04e00302009-04-29 17:09:14 +00002964 // FIXME: The receiver could be a reference to a class, meaning that
2965 // we should use the class method.
2966 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002967
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002968 // Special-case: are we sending a mesage to "self"?
2969 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002970 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2971 if (Expr* Receiver = ME->getReceiver()) {
2972 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2973 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2974 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2975 // Update the summary to make the default argument effect
2976 // 'StopTracking'.
2977 Summ = Summaries.copySummary(Summ);
2978 Summ->setDefaultArgEffect(StopTracking);
2979 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002980 }
2981 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002982 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002983 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002984 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002985
Ted Kremenek286e9852009-05-04 04:57:00 +00002986 if (!Summ)
2987 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002988
Ted Kremenek286e9852009-05-04 04:57:00 +00002989 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002990 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002991}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002992
2993namespace {
2994class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2995 GRStateRef state;
2996public:
2997 StopTrackingCallback(GRStateRef st) : state(st) {}
2998 GRStateRef getState() { return state; }
2999
3000 bool VisitSymbol(SymbolRef sym) {
3001 state = state.remove<RefBindings>(sym);
3002 return true;
3003 }
Ted Kremenek926abf22008-05-06 04:20:12 +00003004
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003005 const GRState* getState() const { return state.getState(); }
3006};
3007} // end anonymous namespace
3008
3009
Ted Kremeneka42be302009-02-14 01:43:44 +00003010void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00003011 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00003012 bool escapes = false;
3013
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003014 // A value escapes in three possible cases (this may change):
3015 //
3016 // (1) we are binding to something that is not a memory region.
3017 // (2) we are binding to a memregion that does not have stack storage
3018 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003019 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00003020 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003021
Ted Kremeneka42be302009-02-14 01:43:44 +00003022 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003023 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003024 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003025 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3026 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003027
3028 if (!escapes) {
3029 // To test (3), generate a new state with the binding removed. If it is
3030 // the same state, then it escapes (since the store cannot represent
3031 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00003032 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003033 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003034 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003035
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003036 // If our store can represent the binding and we aren't storing to something
3037 // that doesn't have local storage then just return and have the simulation
3038 // state continue as is.
3039 if (!escapes)
3040 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003041
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003042 // Otherwise, find all symbols referenced by 'val' that we are tracking
3043 // and stop tracking them.
3044 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003045}
3046
Ted Kremenek541db372008-04-24 23:57:27 +00003047
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003048 // Return statements.
3049
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003050void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003051 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003052 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003053 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003054 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003055
3056 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003057 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003058 return;
3059
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003060 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00003061 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003062
Ted Kremenek74556a12009-03-26 03:35:11 +00003063 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003064 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003065
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003066 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003067 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003068
3069 if (!T)
3070 return;
3071
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003072 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003073 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003074
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003075 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003076 case RefVal::Owned: {
3077 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003078 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003079 X.setCount(cnt - 1);
3080 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003081 break;
3082 }
3083
3084 case RefVal::NotOwned: {
3085 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003086 if (cnt) {
3087 X.setCount(cnt - 1);
3088 X = X ^ RefVal::ReturnedOwned;
3089 }
3090 else {
3091 X = X ^ RefVal::ReturnedNotOwned;
3092 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003093 break;
3094 }
3095
3096 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003097 return;
3098 }
3099
3100 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003101 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003102 Pred = Builder.MakeNode(Dst, S, Pred, state);
3103
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003104 // Did we cache out?
3105 if (!Pred)
3106 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003107
3108 // Update the autorelease counts.
3109 static unsigned autoreleasetag = 0;
3110 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3111 bool stop = false;
3112 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3113 X, stop);
3114
3115 // Did we cache out?
3116 if (!Pred || stop)
3117 return;
3118
3119 // Get the updated binding.
3120 T = state.get<RefBindings>(Sym);
3121 assert(T);
3122 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003123
Ted Kremenek47a72422009-04-29 18:50:19 +00003124 // Any leaks or other errors?
3125 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003126 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003127 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003128 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003129 RetEffect RE = Summ.getRetEffect();
3130 bool hasError = false;
3131
3132 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3133 // Things are more complicated with garbage collection. If the
3134 // returned object is suppose to be an Objective-C object, we have
Ted Kremenekeaea6582009-05-10 16:52:15 +00003135 // a leak (as the caller expects a GC'ed object) because no
3136 // method should return ownership unless it returns a CF object.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003137 X = X ^ RefVal::ErrorGCLeakReturned;
3138
3139 // Keep this false until this is properly tested.
Ted Kremenekeaea6582009-05-10 16:52:15 +00003140 hasError = true;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003141 }
3142 else if (!RE.isOwned()) {
3143 // Either we are using GC and the returned object is a CF type
3144 // or we aren't using GC. In either case, we expect that the
3145 // enclosing method is expected to return ownership.
3146 hasError = true;
3147 X = X ^ RefVal::ErrorLeakReturned;
3148 }
3149
3150 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003151 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003152 static int ReturnOwnLeakTag = 0;
3153 state = state.set<RefBindings>(Sym, X);
3154 ExplodedNode<GRState> *N =
3155 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3156 if (N) {
3157 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003158 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3159 N, Sym, Eng);
3160 BR->EmitReport(report);
3161 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003162 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003163 }
3164 }
3165 else if (X.isReturnedNotOwned()) {
3166 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3167 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3168 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3169 if (Summ.getRetEffect().isOwned()) {
3170 // Trying to return a not owned object to a caller expecting an
3171 // owned object.
3172
3173 static int ReturnNotOwnedForOwnedTag = 0;
3174 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3175 if (ExplodedNode<GRState> *N =
3176 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3177 state, Pred)) {
3178 CFRefReport *report =
3179 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3180 *this, N, Sym);
3181 BR->EmitReport(report);
3182 }
3183 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003184 }
3185 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003186}
3187
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003188// Assumptions.
3189
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003190const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3191 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003192 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003193 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003194
3195 // FIXME: We may add to the interface of EvalAssume the list of symbols
3196 // whose assumptions have changed. For now we just iterate through the
3197 // bindings and check if any of the tracked symbols are NULL. This isn't
3198 // too bad since the number of symbols we will track in practice are
3199 // probably small and EvalAssume is only called at branches and a few
3200 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003201 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003202
3203 if (B.isEmpty())
3204 return St;
3205
3206 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003207
3208 GRStateRef state(St, VMgr);
3209 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003210
3211 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003212 // Check if the symbol is null (or equal to any constant).
3213 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003214 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003215 changed = true;
3216 B = RefBFactory.Remove(B, I.getKey());
3217 }
3218 }
3219
Ted Kremenek91781202008-08-17 03:20:02 +00003220 if (changed)
3221 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003222
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003223 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003224}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003225
Ted Kremenekb6578942009-02-24 19:15:11 +00003226GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3227 RefVal V, ArgEffect E,
3228 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003229
3230 // In GC mode [... release] and [... retain] do nothing.
3231 switch (E) {
3232 default: break;
3233 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3234 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003235 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003236 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3237 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003238 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003239
Ted Kremenek6537a642009-03-17 19:42:23 +00003240 // Handle all use-after-releases.
3241 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3242 V = V ^ RefVal::ErrorUseAfterRelease;
3243 hasErr = V.getKind();
3244 return state.set<RefBindings>(sym, V);
3245 }
3246
Ted Kremenek0d721572008-03-11 17:48:22 +00003247 switch (E) {
3248 default:
3249 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003250
3251 case Dealloc:
3252 // Any use of -dealloc in GC is *bad*.
3253 if (isGCEnabled()) {
3254 V = V ^ RefVal::ErrorDeallocGC;
3255 hasErr = V.getKind();
3256 break;
3257 }
3258
3259 switch (V.getKind()) {
3260 default:
3261 assert(false && "Invalid case.");
3262 case RefVal::Owned:
3263 // The object immediately transitions to the released state.
3264 V = V ^ RefVal::Released;
3265 V.clearCounts();
3266 return state.set<RefBindings>(sym, V);
3267 case RefVal::NotOwned:
3268 V = V ^ RefVal::ErrorDeallocNotOwned;
3269 hasErr = V.getKind();
3270 break;
3271 }
3272 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003273
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003274 case NewAutoreleasePool:
3275 assert(!isGCEnabled());
3276 return state.add<AutoreleaseStack>(sym);
3277
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003278 case MayEscape:
3279 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003280 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003281 break;
3282 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003283
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003284 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003285
Ted Kremenekede40b72008-07-09 18:11:16 +00003286 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003287 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003288 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003289
Ted Kremenek9b112d22009-01-28 21:44:40 +00003290 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003291 if (isGCEnabled())
3292 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003293
3294 // Update the autorelease counts.
3295 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003296 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003297 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003298
Ted Kremenek227c5372008-05-06 02:41:27 +00003299 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003300 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003301
Ted Kremenek0d721572008-03-11 17:48:22 +00003302 case IncRef:
3303 switch (V.getKind()) {
3304 default:
3305 assert(false);
3306
3307 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003308 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003309 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003310 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003311 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003312 // Non-GC cases are handled above.
3313 assert(isGCEnabled());
3314 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003315 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003316 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003317 break;
3318
Ted Kremenek272aa852008-06-25 21:21:56 +00003319 case SelfOwn:
3320 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003321 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003322 case DecRef:
3323 switch (V.getKind()) {
3324 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003325 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003326 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003327
Ted Kremenek272aa852008-06-25 21:21:56 +00003328 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003329 assert(V.getCount() > 0);
3330 if (V.getCount() == 1) V = V ^ RefVal::Released;
3331 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003332 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003333
Ted Kremenek272aa852008-06-25 21:21:56 +00003334 case RefVal::NotOwned:
3335 if (V.getCount() > 0)
3336 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003337 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003338 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003339 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003340 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003341 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003342
Ted Kremenek0d721572008-03-11 17:48:22 +00003343 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003344 // Non-GC cases are handled above.
3345 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003346 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003347 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003348 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003349 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003350 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003351 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003352 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003353}
3354
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003355//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003356// Handle dead symbols and end-of-path.
3357//===----------------------------------------------------------------------===//
3358
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003359std::pair<ExplodedNode<GRState>*, GRStateRef>
3360CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3361 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003362 GRExprEngine &Eng,
3363 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003364
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003365 unsigned ACnt = V.getAutoreleaseCount();
3366 stop = false;
3367
3368 // No autorelease counts? Nothing to be done.
3369 if (!ACnt)
3370 return std::make_pair(Pred, state);
3371
3372 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3373 unsigned Cnt = V.getCount();
3374
Ted Kremenek0603cf52009-05-11 15:26:06 +00003375 // FIXME: Handle sending 'autorelease' to already released object.
3376
3377 if (V.getKind() == RefVal::ReturnedOwned)
3378 ++Cnt;
3379
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003380 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003381 if (ACnt == Cnt) {
3382 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003383 if (V.getKind() == RefVal::ReturnedOwned)
3384 V = V ^ RefVal::ReturnedNotOwned;
3385 else
3386 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003387 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003388 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003389 V.setCount(Cnt - ACnt);
3390 V.setAutoreleaseCount(0);
3391 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003392 state = state.set<RefBindings>(Sym, V);
3393 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3394 stop = (N == 0);
3395 return std::make_pair(N, state);
3396 }
3397
3398 // Woah! More autorelease counts then retain counts left.
3399 // Emit hard error.
3400 stop = true;
3401 V = V ^ RefVal::ErrorOverAutorelease;
3402 state = state.set<RefBindings>(Sym, V);
3403
3404 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003405 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003406
3407 std::string sbuf;
3408 llvm::raw_string_ostream os(sbuf);
3409 os << "Object over-autoreleased: object was sent -autorelease " ;
3410 if (V.getAutoreleaseCount() > 1)
3411 os << V.getAutoreleaseCount() << " times";
3412 os << " but the object has ";
3413 if (V.getCount() == 0)
3414 os << "zero (locally visible)";
3415 else
3416 os << "+" << V.getCount();
3417 os << " retain counts";
3418
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003419 CFRefReport *report =
3420 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003421 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003422 BR->EmitReport(report);
3423 }
3424
3425 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003426}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003427
3428GRStateRef
3429CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3430 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3431
3432 bool hasLeak = V.isOwned() ||
3433 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3434
3435 if (!hasLeak)
3436 return state.remove<RefBindings>(sid);
3437
3438 Leaked.push_back(sid);
3439 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3440}
3441
3442ExplodedNode<GRState>*
3443CFRefCount::ProcessLeaks(GRStateRef state,
3444 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3445 GenericNodeBuilder &Builder,
3446 GRExprEngine& Eng,
3447 ExplodedNode<GRState> *Pred) {
3448
3449 if (Leaked.empty())
3450 return Pred;
3451
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003452 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003453 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003454
3455 if (N) {
3456 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3457 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3458
3459 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3460 : leakAtReturn);
3461 assert(BT && "BugType not initialized.");
3462 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3463 BR->EmitReport(report);
3464 }
3465 }
3466
3467 return N;
3468}
3469
Ted Kremenek708af042009-02-05 06:50:21 +00003470void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3471 GREndPathNodeBuilder<GRState>& Builder) {
3472
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003473 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003474 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003475 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003476 ExplodedNode<GRState> *Pred = 0;
3477
3478 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003479 bool stop = false;
3480 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3481 (*I).first,
3482 (*I).second, stop);
3483
3484 if (stop)
3485 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003486 }
3487
3488 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003489 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003490
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003491 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3492 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3493
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003494 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003495}
3496
3497void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3498 GRExprEngine& Eng,
3499 GRStmtNodeBuilder<GRState>& Builder,
3500 ExplodedNode<GRState>* Pred,
3501 Stmt* S,
3502 const GRState* St,
3503 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003504
3505 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003506 RefBindings B = state.get<RefBindings>();
3507
3508 // Update counts from autorelease pools
3509 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3510 E = SymReaper.dead_end(); I != E; ++I) {
3511 SymbolRef Sym = *I;
3512 if (const RefVal* T = B.lookup(Sym)){
3513 // Use the symbol as the tag.
3514 // FIXME: This might not be as unique as we would like.
3515 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003516 bool stop = false;
3517 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3518 Sym, *T, stop);
3519 if (stop)
3520 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003521 }
3522 }
3523
3524 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003525 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003526
3527 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003528 E = SymReaper.dead_end(); I != E; ++I) {
3529 if (const RefVal* T = B.lookup(*I))
3530 state = HandleSymbolDeath(state, *I, *T, Leaked);
3531 }
Ted Kremenek708af042009-02-05 06:50:21 +00003532
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003533 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003534 {
3535 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3536 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3537 }
Ted Kremenek708af042009-02-05 06:50:21 +00003538
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003539 // Did we cache out?
3540 if (!Pred)
3541 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003542
3543 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003544 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003545
Ted Kremenek876d8df2009-02-19 23:47:02 +00003546 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003547 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3548
Ted Kremenek876d8df2009-02-19 23:47:02 +00003549 state = state.set<RefBindings>(B);
3550 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003551}
3552
3553void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3554 GRStmtNodeBuilder<GRState>& Builder,
3555 Expr* NodeExpr, Expr* ErrorExpr,
3556 ExplodedNode<GRState>* Pred,
3557 const GRState* St,
3558 RefVal::Kind hasErr, SymbolRef Sym) {
3559 Builder.BuildSinks = true;
3560 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3561
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003562 if (!N)
3563 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003564
3565 CFRefBug *BT = 0;
3566
Ted Kremenek6537a642009-03-17 19:42:23 +00003567 switch (hasErr) {
3568 default:
3569 assert(false && "Unhandled error.");
3570 return;
3571 case RefVal::ErrorUseAfterRelease:
3572 BT = static_cast<CFRefBug*>(useAfterRelease);
3573 break;
3574 case RefVal::ErrorReleaseNotOwned:
3575 BT = static_cast<CFRefBug*>(releaseNotOwned);
3576 break;
3577 case RefVal::ErrorDeallocGC:
3578 BT = static_cast<CFRefBug*>(deallocGC);
3579 break;
3580 case RefVal::ErrorDeallocNotOwned:
3581 BT = static_cast<CFRefBug*>(deallocNotOwned);
3582 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003583 }
3584
Ted Kremenekc26c4692009-02-18 03:48:14 +00003585 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003586 report->addRange(ErrorExpr->getSourceRange());
3587 BR->EmitReport(report);
3588}
3589
3590//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003591// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003592//===----------------------------------------------------------------------===//
3593
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003594GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3595 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003596 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003597}