blob: c31a8cd53d9fe8346d8dae2e5581c0f9d0f6a9ea [file] [log] [blame]
Chris Lattnerbda0b622008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek2fff37e2008-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 Greif843e9342008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek2fff37e2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenek072192b2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekc9fa2f72008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek41573eb2009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenekb9d17f92008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenek4dc41cc2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek5216ad72009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenek8966bc12009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek900a2d72008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenekf3948042008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek98530452008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenek5c74d502008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenek5c74d502008-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 Kremenekb80976c2009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenek39868cd2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenekb80976c2009-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 Kremenek39868cd2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenekb80976c2009-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 Kremenek8be2a672009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek8be2a672009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenekb80976c2009-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 Kremenek5c74d502008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000150}
151
Ted Kremeneka8833552009-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 Kremenek4c79e552008-11-05 16:54:44 +0000160}
Ted Kremenek5c74d502008-10-24 21:18:08 +0000161
Ted Kremenek9d9d3a62009-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 Kremenek6b62ec92009-05-09 01:50:57 +0000178 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000179
180 assert(ENB);
Ted Kremenek80c24182009-05-09 00:44:07 +0000181 return ENB->generateNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000182 }
183};
184} // end anonymous namespace
185
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000186//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000187// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000188//===----------------------------------------------------------------------===//
189
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000190static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000191 IdentifierInfo* II = &Ctx.Idents.get(name);
192 return Ctx.Selectors.getSelector(0, &II);
193}
194
Ted Kremenek9c32d082008-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 Kremenek553cf182008-06-25 21:21:56 +0000200//===----------------------------------------------------------------------===//
201// Type querying functions.
202//===----------------------------------------------------------------------===//
203
Ted Kremenek12619382009-01-12 21:45:02 +0000204static bool hasPrefix(const char* s, const char* prefix) {
205 if (!prefix)
206 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000207
Ted Kremenek12619382009-01-12 21:45:02 +0000208 char c = *s;
209 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000210
Ted Kremenek12619382009-01-12 21:45:02 +0000211 while (c != '\0' && cP != '\0') {
212 if (c != cP) break;
213 c = *(++s);
214 cP = *(++prefix);
215 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000216
Ted Kremenek12619382009-01-12 21:45:02 +0000217 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000218}
219
Ted Kremenek12619382009-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 Kremenek37d785b2008-07-15 16:50:12 +0000227
Ted Kremenek6738b732009-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 Kremenek12619382009-01-12 21:45:02 +0000239 }
240
241 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000242 return false;
Ted Kremenek12619382009-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 Kremenek37d785b2008-07-15 16:50:12 +0000247 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000248
249 // Does the name start with the prefix?
250 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000251}
252
Ted Kremenek4fd88972008-04-17 18:12:53 +0000253//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000254// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000255//===----------------------------------------------------------------------===//
256
Ted Kremenek553cf182008-06-25 21:21:56 +0000257/// ArgEffect is used to summarize a function/method call's effect on a
258/// particular argument.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +0000259enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
260 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
261 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +0000262
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000263namespace llvm {
Ted Kremenekb77449c2009-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 Kremenek553cf182008-06-25 21:21:56 +0000268};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000269} // end llvm namespace
270
Ted Kremenekb77449c2009-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000275namespace {
Ted Kremenek553cf182008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000280public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000281 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +0000282 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
283 OwnedWhenTrackedReceiver };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000284
285 enum ObjKind { CF, ObjC, AnyObj };
286
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000287private:
Ted Kremenek2d1652e2009-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 Kremenek2fff37e2008-03-06 00:08:09 +0000294
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000295public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000296 Kind getKind() const { return K; }
297
298 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000299
300 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000301 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000302 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000303 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000304
Ted Kremeneka8833552009-04-29 23:03:22 +0000305 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000306 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
307 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000308 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +0000309
Ted Kremenek78a35a32009-05-12 20:06:54 +0000310 static RetEffect MakeOwnedWhenTrackedReceiver() {
311 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
312 }
313
Ted Kremenek553cf182008-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 Kremenek2d1652e2009-01-28 05:56:51 +0000320 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
321 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000322 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000323 static RetEffect MakeNotOwned(ObjKind o) {
324 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000325 }
326 static RetEffect MakeGCNotOwned() {
327 return RetEffect(GCNotOwnedSymbol, ObjC);
328 }
329
Ted Kremenek553cf182008-06-25 21:21:56 +0000330 static RetEffect MakeNoRet() {
331 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000332 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000333
Ted Kremenek553cf182008-06-25 21:21:56 +0000334 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000335 ID.AddInteger((unsigned)K);
336 ID.AddInteger((unsigned)O);
337 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000338 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000339};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000340
Ted Kremenek553cf182008-06-25 21:21:56 +0000341
Ted Kremenek885c27b2009-05-04 05:31:22 +0000342class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenek1bffd742008-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 Kremenekb77449c2009-05-03 05:20:50 +0000346 ArgEffects Args;
Ted Kremenek1bffd742008-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 Kremenek553cf182008-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 Kremenek3c0cea32008-05-06 02:26:56 +0000354 ArgEffect Receiver;
Ted Kremenek553cf182008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000359 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000360
Ted Kremenek70a733e2008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000365public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000366 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000367 ArgEffect ReceiverEff, bool endpath = false)
368 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
369 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000370
Ted Kremenek553cf182008-06-25 21:21:56 +0000371 /// getArg - Return the argument effect on the argument specified by
372 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000373 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000374 if (const ArgEffect *AE = Args.lookup(idx))
375 return *AE;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000376
Ted Kremenek1bffd742008-05-06 15:44:25 +0000377 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000378 }
379
Ted Kremenek885c27b2009-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 Kremenek553cf182008-06-25 21:21:56 +0000390 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000391 RetEffect getRetEffect() const { return Ret; }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000392
Ted Kremenek885c27b2009-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 Kremenek70a733e2008-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 Kremenek553cf182008-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 Kremenekb77449c2009-05-03 05:20:50 +0000402 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000403
Ted Kremenek885c27b2009-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 Kremenekb77449c2009-05-03 05:20:50 +0000407 typedef ArgEffects::iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000408
Ted Kremenekb77449c2009-05-03 05:20:50 +0000409 ExprIterator begin_args() const { return Args.begin(); }
410 ExprIterator end_args() const { return Args.end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000411
Ted Kremenekb77449c2009-05-03 05:20:50 +0000412 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000413 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000414 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000415 ID.Add(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000416 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000417 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000418 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000419 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000420 }
421
422 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000423 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000424 }
425};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000426} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000427
Ted Kremenek553cf182008-06-25 21:21:56 +0000428//===----------------------------------------------------------------------===//
429// Data structures for constructing summaries.
430//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000431
Ted Kremenek553cf182008-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 Kremeneka8833552009-04-29 23:03:22 +0000440 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000441 : II(d ? d->getIdentifier() : 0), S(s) {}
442
443 ObjCSummaryKey(Selector s)
444 : II(0), S(s) {}
445
446 IdentifierInfo* getIdentifier() const { return II; }
447 Selector getSelector() const { return S; }
448};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000449}
450
451namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000452template <> struct DenseMapInfo<ObjCSummaryKey> {
453 static inline ObjCSummaryKey getEmptyKey() {
454 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
455 DenseMapInfo<Selector>::getEmptyKey());
456 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000457
Ted Kremenek553cf182008-06-25 21:21:56 +0000458 static inline ObjCSummaryKey getTombstoneKey() {
459 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
460 DenseMapInfo<Selector>::getTombstoneKey());
461 }
462
463 static unsigned getHashValue(const ObjCSummaryKey &V) {
464 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
465 & 0x88888888)
466 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
467 & 0x55555555);
468 }
469
470 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
471 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
472 RHS.getIdentifier()) &&
473 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
474 RHS.getSelector());
475 }
476
477 static bool isPod() {
478 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
479 DenseMapInfo<Selector>::isPod();
480 }
481};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000482} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000483
Ted Kremenek4f22a782008-06-23 23:30:29 +0000484namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000485class VISIBILITY_HIDDEN ObjCSummaryCache {
486 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
487 MapTy M;
488public:
489 ObjCSummaryCache() {}
490
491 typedef MapTy::iterator iterator;
492
Ted Kremeneka8833552009-04-29 23:03:22 +0000493 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
494 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000495 // Lookup the method using the decl for the class @interface. If we
496 // have no decl, lookup using the class name.
497 return D ? find(D, S) : find(ClsName, S);
498 }
499
Ted Kremeneka8833552009-04-29 23:03:22 +0000500 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000501 // Do a lookup with the (D,S) pair. If we find a match return
502 // the iterator.
503 ObjCSummaryKey K(D, S);
504 MapTy::iterator I = M.find(K);
505
506 if (I != M.end() || !D)
507 return I;
508
509 // Walk the super chain. If we find a hit with a parent, we'll end
510 // up returning that summary. We actually allow that key (null,S), as
511 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
512 // generate initial summaries without having to worry about NSObject
513 // being declared.
514 // FIXME: We may change this at some point.
515 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
516 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
517 break;
518
519 if (!C)
520 return I;
521 }
522
523 // Cache the summary with original key to make the next lookup faster
524 // and return the iterator.
525 M[K] = I->second;
526 return I;
527 }
528
Ted Kremenek98530452008-08-12 20:41:56 +0000529
Ted Kremenek553cf182008-06-25 21:21:56 +0000530 iterator find(Expr* Receiver, Selector S) {
531 return find(getReceiverDecl(Receiver), S);
532 }
533
534 iterator find(IdentifierInfo* II, Selector S) {
535 // FIXME: Class method lookup. Right now we dont' have a good way
536 // of going between IdentifierInfo* and the class hierarchy.
537 iterator I = M.find(ObjCSummaryKey(II, S));
538 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
539 }
540
541 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
542
543 const PointerType* PT = E->getType()->getAsPointerType();
544 if (!PT) return 0;
545
546 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
547 if (!OI) return 0;
548
549 return OI ? OI->getDecl() : 0;
550 }
551
552 iterator end() { return M.end(); }
553
554 RetainSummary*& operator[](ObjCMessageExpr* ME) {
555
556 Selector S = ME->getSelector();
557
558 if (Expr* Receiver = ME->getReceiver()) {
559 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
560 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
561 }
562
563 return M[ObjCSummaryKey(ME->getClassName(), S)];
564 }
565
566 RetainSummary*& operator[](ObjCSummaryKey K) {
567 return M[K];
568 }
569
570 RetainSummary*& operator[](Selector S) {
571 return M[ ObjCSummaryKey(S) ];
572 }
573};
574} // end anonymous namespace
575
576//===----------------------------------------------------------------------===//
577// Data structures for managing collections of summaries.
578//===----------------------------------------------------------------------===//
579
580namespace {
581class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000582
583 //==-----------------------------------------------------------------==//
584 // Typedefs.
585 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000586
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000587 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
588 FuncSummariesTy;
589
Ted Kremenek4f22a782008-06-23 23:30:29 +0000590 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000591
592 //==-----------------------------------------------------------------==//
593 // Data.
594 //==-----------------------------------------------------------------==//
595
Ted Kremenek553cf182008-06-25 21:21:56 +0000596 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000597 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000598
Ted Kremenek070a8252008-07-09 18:11:16 +0000599 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
600 /// "CFDictionaryCreate".
601 IdentifierInfo* CFDictionaryCreateII;
602
Ted Kremenek553cf182008-06-25 21:21:56 +0000603 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000604 const bool GCEnabled;
Ted Kremenek22fe2482009-05-04 04:30:18 +0000605
Ted Kremenek553cf182008-06-25 21:21:56 +0000606 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000607 FuncSummariesTy FuncSummaries;
608
Ted Kremenek553cf182008-06-25 21:21:56 +0000609 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
610 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000611 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000612
Ted Kremenek553cf182008-06-25 21:21:56 +0000613 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000614 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000615
Ted Kremenek553cf182008-06-25 21:21:56 +0000616 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
617 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000618 llvm::BumpPtrAllocator BPAlloc;
619
Ted Kremenekb77449c2009-05-03 05:20:50 +0000620 /// AF - A factory for ArgEffects objects.
621 ArgEffects::Factory AF;
622
Ted Kremenek553cf182008-06-25 21:21:56 +0000623 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000624 ArgEffects ScratchArgs;
625
Ted Kremenekec315332009-05-07 23:40:42 +0000626 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
627 /// objects.
628 RetEffect ObjCAllocRetE;
629
Ted Kremenek7faca822009-05-04 04:57:00 +0000630 RetainSummary DefaultSummary;
Ted Kremenek432af592008-05-06 18:11:36 +0000631 RetainSummary* StopSummary;
632
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000633 //==-----------------------------------------------------------------==//
634 // Methods.
635 //==-----------------------------------------------------------------==//
636
Ted Kremenek553cf182008-06-25 21:21:56 +0000637 /// getArgEffects - Returns a persistent ArgEffects object based on the
638 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000639 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000640
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000641 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000642
643public:
Ted Kremenek78a35a32009-05-12 20:06:54 +0000644 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
645
Ted Kremenek885c27b2009-05-04 05:31:22 +0000646 RetainSummary *getDefaultSummary() {
647 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
648 return new (Summ) RetainSummary(DefaultSummary);
649 }
Ted Kremenek7faca822009-05-04 04:57:00 +0000650
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000651 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000652
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000653 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
654 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000655 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000656
Ted Kremenekb77449c2009-05-03 05:20:50 +0000657 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000658 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000659 ArgEffect DefaultEff = MayEscape,
660 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000661
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000662 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000663 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000664 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000665 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000666 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000667
Ted Kremenek8711c032009-04-29 05:04:30 +0000668 RetainSummary *getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000669 if (StopSummary)
670 return StopSummary;
671
672 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
673 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000674
Ted Kremenek432af592008-05-06 18:11:36 +0000675 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000676 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000677
Ted Kremenek8711c032009-04-29 05:04:30 +0000678 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000679
Ted Kremenek1f180c32008-06-23 22:21:20 +0000680 void InitializeClassMethodSummaries();
681 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000682
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000683 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek92511432009-05-03 06:08:32 +0000684 bool isTrackedCFObjectType(QualType T);
Ted Kremenek234a4c22009-01-07 00:39:56 +0000685
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000686private:
687
Ted Kremenek70a733e2008-07-18 17:24:20 +0000688 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
689 RetainSummary* Summ) {
690 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
691 }
692
Ted Kremenek553cf182008-06-25 21:21:56 +0000693 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
694 ObjCClassMethodSummaries[S] = Summ;
695 }
696
697 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
698 ObjCMethodSummaries[S] = Summ;
699 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000700
701 void addClassMethSummary(const char* Cls, const char* nullaryName,
702 RetainSummary *Summ) {
703 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
704 Selector S = GetNullarySelector(nullaryName, Ctx);
705 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
706 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000707
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000708 void addInstMethSummary(const char* Cls, const char* nullaryName,
709 RetainSummary *Summ) {
710 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
711 Selector S = GetNullarySelector(nullaryName, Ctx);
712 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
713 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000714
715 Selector generateSelector(va_list argp) {
Ted Kremenek9e476de2008-08-12 18:30:56 +0000716 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000717
Ted Kremenek9e476de2008-08-12 18:30:56 +0000718 while (const char* s = va_arg(argp, const char*))
719 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000720
721 return Ctx.Selectors.getSelector(II.size(), &II[0]);
722 }
723
724 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
725 RetainSummary* Summ, va_list argp) {
726 Selector S = generateSelector(argp);
727 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000728 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000729
730 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
731 va_list argp;
732 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000733 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000734 va_end(argp);
735 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000736
737 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
738 va_list argp;
739 va_start(argp, Summ);
740 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
741 va_end(argp);
742 }
743
744 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
745 va_list argp;
746 va_start(argp, Summ);
747 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
748 va_end(argp);
749 }
750
Ted Kremenek9e476de2008-08-12 18:30:56 +0000751 void addPanicSummary(const char* Cls, ...) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000752 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
753 RetEffect::MakeNoRet(),
Ted Kremenek9e476de2008-08-12 18:30:56 +0000754 DoNothing, DoNothing, true);
755 va_list argp;
756 va_start (argp, Cls);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000757 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000758 va_end(argp);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000759 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000760
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000761public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000762
763 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000764 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000765 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000766 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenekec315332009-05-07 23:40:42 +0000767 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
768 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek7faca822009-05-04 04:57:00 +0000769 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
770 RetEffect::MakeNoRet() /* return effect */,
Ted Kremenekebd5a2d2009-05-11 18:30:24 +0000771 MayEscape, /* default argument effect */
772 DoNothing /* receiver effect */),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000773 StopSummary(0) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000774
775 InitializeClassMethodSummaries();
776 InitializeMethodSummaries();
777 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000778
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000779 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000780
Ted Kremenekab592272008-06-24 03:56:45 +0000781 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek8711c032009-04-29 05:04:30 +0000782
Ted Kremeneka8833552009-04-29 23:03:22 +0000783 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
784 const ObjCInterfaceDecl* ID) {
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000785 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremenek8711c032009-04-29 05:04:30 +0000786 ID, ME->getMethodDecl(), ME->getType());
787 }
788
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000789 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000790 const ObjCInterfaceDecl* ID,
791 const ObjCMethodDecl *MD,
792 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000793
794 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000795 const ObjCInterfaceDecl *ID,
796 const ObjCMethodDecl *MD,
797 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000798
799 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
800 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
801 ME->getClassInfo().first,
802 ME->getMethodDecl(), ME->getType());
803 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000804
805 /// getMethodSummary - This version of getMethodSummary is used to query
806 /// the summary for the current method being analyzed.
Ted Kremeneka8833552009-04-29 23:03:22 +0000807 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
808 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000809 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000810 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000811 IdentifierInfo *ClsName = ID->getIdentifier();
812 QualType ResultTy = MD->getResultType();
813
Ted Kremenek76a50e32009-04-30 05:47:23 +0000814 // Resolve the method decl last.
815 if (const ObjCMethodDecl *InterfaceMD =
816 ResolveToInterfaceMethodDecl(MD, Ctx))
817 MD = InterfaceMD;
Ted Kremenek70a65762009-04-30 05:41:14 +0000818
Ted Kremenek552333c2009-04-29 17:17:48 +0000819 if (MD->isInstanceMethod())
820 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
821 else
822 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
823 }
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000824
Ted Kremeneka8833552009-04-29 23:03:22 +0000825 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
826 Selector S, QualType RetTy);
827
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000828 void updateSummaryFromAnnotations(RetainSummary &Summ,
829 const ObjCMethodDecl *MD);
830
831 void updateSummaryFromAnnotations(RetainSummary &Summ,
832 const FunctionDecl *FD);
833
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000834 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek885c27b2009-05-04 05:31:22 +0000835
836 RetainSummary *copySummary(RetainSummary *OldSumm) {
837 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
838 new (Summ) RetainSummary(*OldSumm);
839 return Summ;
840 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000841};
842
843} // end anonymous namespace
844
845//===----------------------------------------------------------------------===//
846// Implementation of checker data structures.
847//===----------------------------------------------------------------------===//
848
Ted Kremenekb77449c2009-05-03 05:20:50 +0000849RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000850
Ted Kremenekb77449c2009-05-03 05:20:50 +0000851ArgEffects RetainSummaryManager::getArgEffects() {
852 ArgEffects AE = ScratchArgs;
853 ScratchArgs = AF.GetEmptyMap();
854 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000855}
856
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000857RetainSummary*
Ted Kremenekb77449c2009-05-03 05:20:50 +0000858RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000859 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000860 ArgEffect DefaultEff,
Ted Kremenek22fe2482009-05-04 04:30:18 +0000861 bool isEndPath) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000862 // Create the summary and return it.
Ted Kremenek22fe2482009-05-04 04:30:18 +0000863 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000864 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000865 return Summ;
866}
867
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000868//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000869// Predicates.
870//===----------------------------------------------------------------------===//
871
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000872bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek97d095f2009-04-23 22:11:07 +0000873 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek234a4c22009-01-07 00:39:56 +0000874 return false;
875
Ted Kremenek97d095f2009-04-23 22:11:07 +0000876 // We assume that id<..>, id, and "Class" all represent tracked objects.
877 const PointerType *PT = Ty->getAsPointerType();
878 if (PT == 0)
879 return true;
880
881 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek234a4c22009-01-07 00:39:56 +0000882
883 // We assume that id<..>, id, and "Class" all represent tracked objects.
884 if (!OT)
885 return true;
Ted Kremenek97d095f2009-04-23 22:11:07 +0000886
887 // Does the interface subclass NSObject?
Ted Kremenek234a4c22009-01-07 00:39:56 +0000888 // FIXME: We can memoize here if this gets too expensive.
889 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
890 ObjCInterfaceDecl* ID = OT->getDecl();
891
892 for ( ; ID ; ID = ID->getSuperClass())
893 if (ID->getIdentifier() == NSObjectII)
894 return true;
895
896 return false;
897}
898
Ted Kremenek92511432009-05-03 06:08:32 +0000899bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
900 return isRefType(T, "CF") || // Core Foundation.
901 isRefType(T, "CG") || // Core Graphics.
902 isRefType(T, "DADisk") || // Disk Arbitration API.
903 isRefType(T, "DADissenter") ||
904 isRefType(T, "DASessionRef");
905}
906
Ted Kremenek234a4c22009-01-07 00:39:56 +0000907//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000908// Summary creation for functions (largely uses of Core Foundation).
909//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000910
Ted Kremenek12619382009-01-12 21:45:02 +0000911static bool isRetain(FunctionDecl* FD, const char* FName) {
912 const char* loc = strstr(FName, "Retain");
913 return loc && loc[sizeof("Retain")-1] == '\0';
914}
915
916static bool isRelease(FunctionDecl* FD, const char* FName) {
917 const char* loc = strstr(FName, "Release");
918 return loc && loc[sizeof("Release")-1] == '\0';
919}
920
Ted Kremenekab592272008-06-24 03:56:45 +0000921RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000922 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000923 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000924 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000925 return I->second;
926
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000927 // No summary? Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000928 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000929
Ted Kremenek37d785b2008-07-15 16:50:12 +0000930 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000931 // We generate "stop" summaries for implicitly defined functions.
932 if (FD->isImplicit()) {
933 S = getPersistentStopSummary();
934 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000935 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000936
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000937 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000938 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000939 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000940 const char* FName = FD->getIdentifier()->getName();
941
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000942 // Strip away preceding '_'. Doing this here will effect all the checks
943 // down below.
944 while (*FName == '_') ++FName;
945
Ted Kremenek12619382009-01-12 21:45:02 +0000946 // Inspect the result type.
947 QualType RetTy = FT->getResultType();
948
949 // FIXME: This should all be refactored into a chain of "summary lookup"
950 // filters.
951 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
952 // FIXES: <rdar://problem/6326900>
953 // This should be addressed using a API table. This strcmp is also
954 // a little gross, but there is no need to super optimize here.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000955 assert (ScratchArgs.isEmpty());
956 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek12619382009-01-12 21:45:02 +0000957 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
958 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000959 }
Ted Kremenek61991902009-03-17 22:43:44 +0000960
961 // Enable this code once the semantics of NSDeallocateObject are resolved
962 // for GC. <rdar://problem/6619988>
963#if 0
964 // Handle: NSDeallocateObject(id anObject);
965 // This method does allow 'nil' (although we don't check it now).
966 if (strcmp(FName, "NSDeallocateObject") == 0) {
967 return RetTy == Ctx.VoidTy
968 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
969 : getPersistentStopSummary();
970 }
971#endif
Ted Kremenek12619382009-01-12 21:45:02 +0000972
973 // Handle: id NSMakeCollectable(CFTypeRef)
974 if (strcmp(FName, "NSMakeCollectable") == 0) {
975 S = (RetTy == Ctx.getObjCIdType())
976 ? getUnarySummary(FT, cfmakecollectable)
977 : getPersistentStopSummary();
978
979 break;
980 }
981
982 if (RetTy->isPointerType()) {
983 // For CoreFoundation ('CF') types.
984 if (isRefType(RetTy, "CF", &Ctx, FName)) {
985 if (isRetain(FD, FName))
986 S = getUnarySummary(FT, cfretain);
987 else if (strstr(FName, "MakeCollectable"))
988 S = getUnarySummary(FT, cfmakecollectable);
989 else
990 S = getCFCreateGetRuleSummary(FD, FName);
991
992 break;
993 }
994
995 // For CoreGraphics ('CG') types.
996 if (isRefType(RetTy, "CG", &Ctx, FName)) {
997 if (isRetain(FD, FName))
998 S = getUnarySummary(FT, cfretain);
999 else
1000 S = getCFCreateGetRuleSummary(FD, FName);
1001
1002 break;
1003 }
1004
1005 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1006 if (isRefType(RetTy, "DADisk") ||
1007 isRefType(RetTy, "DADissenter") ||
1008 isRefType(RetTy, "DASessionRef")) {
1009 S = getCFCreateGetRuleSummary(FD, FName);
1010 break;
1011 }
1012
1013 break;
1014 }
1015
1016 // Check for release functions, the only kind of functions that we care
1017 // about that don't return a pointer type.
1018 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001019 // Test for 'CGCF'.
1020 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1021 FName += 4;
1022 else
1023 FName += 2;
1024
1025 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001026 S = getUnarySummary(FT, cfrelease);
1027 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001028 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001029 // Remaining CoreFoundation and CoreGraphics functions.
1030 // We use to assume that they all strictly followed the ownership idiom
1031 // and that ownership cannot be transferred. While this is technically
1032 // correct, many methods allow a tracked object to escape. For example:
1033 //
1034 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1035 // CFDictionaryAddValue(y, key, x);
1036 // CFRelease(x);
1037 // ... it is okay to use 'x' since 'y' has a reference to it
1038 //
1039 // We handle this and similar cases with the follow heuristic. If the
1040 // function name contains "InsertValue", "SetValue" or "AddValue" then
1041 // we assume that arguments may "escape."
1042 //
1043 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1044 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +00001045 CStrInCStrNoCase(FName, "SetValue") ||
1046 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +00001047 ? MayEscape : DoNothing;
1048
1049 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001050 }
1051 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001052 }
1053 while (0);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001054
1055 if (!S)
1056 S = getDefaultSummary();
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001057
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001058 // Annotations override defaults.
1059 assert(S);
1060 updateSummaryFromAnnotations(*S, FD);
1061
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001062 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001063 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001064}
1065
Ted Kremenek37d785b2008-07-15 16:50:12 +00001066RetainSummary*
1067RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1068 const char* FName) {
1069
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001070 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1071 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +00001072
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001073 if (strstr(FName, "Get"))
1074 return getCFSummaryGetRule(FD);
1075
Ted Kremenek7faca822009-05-04 04:57:00 +00001076 return getDefaultSummary();
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001077}
1078
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001079RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001080RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1081 UnaryFuncKind func) {
1082
Ted Kremenek12619382009-01-12 21:45:02 +00001083 // Sanity check that this is *really* a unary function. This can
1084 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001085 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001086 if (!FTP || FTP->getNumArgs() != 1)
1087 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001088
Ted Kremenekb77449c2009-05-03 05:20:50 +00001089 assert (ScratchArgs.isEmpty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001090
Ted Kremenek377e2302008-04-29 05:33:51 +00001091 switch (func) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001092 case cfretain: {
1093 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001094 return getPersistentSummary(RetEffect::MakeAlias(0),
1095 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001096 }
1097
1098 case cfrelease: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001099 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001100 return getPersistentSummary(RetEffect::MakeNoRet(),
1101 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001102 }
1103
1104 case cfmakecollectable: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001105 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek27019002009-02-18 21:57:45 +00001106 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001107 }
1108
1109 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001110 assert (false && "Not a supported unary function.");
Ted Kremenek7faca822009-05-04 04:57:00 +00001111 return getDefaultSummary();
Ted Kremenek940b1d82008-04-10 23:44:06 +00001112 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001113}
1114
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001115RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001116 assert (ScratchArgs.isEmpty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001117
1118 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001119 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1120 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenek070a8252008-07-09 18:11:16 +00001121 }
1122
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001123 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001124}
1125
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001126RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001127 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001128 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1129 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001130}
1131
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001132//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001133// Summary creation for Selectors.
1134//===----------------------------------------------------------------------===//
1135
Ted Kremenek1bffd742008-05-06 15:44:25 +00001136RetainSummary*
Ted Kremenek8711c032009-04-29 05:04:30 +00001137RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek78a35a32009-05-12 20:06:54 +00001138 assert(ScratchArgs.isEmpty());
1139 // 'init' methods conceptually return a newly allocated object and claim
1140 // the receiver.
1141 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
1142 return getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1143 DecRefMsg);
1144
1145 return getDefaultSummary();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001146}
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001147
1148void
1149RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1150 const FunctionDecl *FD) {
1151 if (!FD)
1152 return;
1153
1154 // Determine if there is a special return effect for this method.
1155 if (isTrackedObjCObjectType(FD->getResultType())) {
1156 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1157 Summ.setRetEffect(ObjCAllocRetE);
1158 }
1159 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1160 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1161 }
1162 }
1163}
1164
1165void
1166RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1167 const ObjCMethodDecl *MD) {
1168 if (!MD)
1169 return;
1170
1171 // Determine if there is a special return effect for this method.
1172 if (isTrackedObjCObjectType(MD->getResultType())) {
1173 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1174 Summ.setRetEffect(ObjCAllocRetE);
1175 }
1176 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1177 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1178 }
1179 }
1180}
1181
Ted Kremenek1bffd742008-05-06 15:44:25 +00001182RetainSummary*
Ted Kremeneka8833552009-04-29 23:03:22 +00001183RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1184 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001185
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001186 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001187 // Scan the method decl for 'void*' arguments. These should be treated
1188 // as 'StopTracking' because they are often used with delegates.
1189 // Delegates are a frequent form of false positives with the retain
1190 // count checker.
1191 unsigned i = 0;
1192 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1193 E = MD->param_end(); I != E; ++I, ++i)
1194 if (ParmVarDecl *PD = *I) {
1195 QualType Ty = Ctx.getCanonicalType(PD->getType());
1196 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenekb77449c2009-05-03 05:20:50 +00001197 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001198 }
1199 }
1200
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001201 // Any special effect for the receiver?
1202 ArgEffect ReceiverEff = DoNothing;
1203
1204 // If one of the arguments in the selector has the keyword 'delegate' we
1205 // should stop tracking the reference count for the receiver. This is
1206 // because the reference count is quite possibly handled by a delegate
1207 // method.
1208 if (S.isKeywordSelector()) {
1209 const std::string &str = S.getAsString();
1210 assert(!str.empty());
1211 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1212 }
1213
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001214 // Look for methods that return an owned object.
Ted Kremenek92511432009-05-03 06:08:32 +00001215 if (isTrackedObjCObjectType(RetTy)) {
1216 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1217 // by instance methods.
Ted Kremenek92511432009-05-03 06:08:32 +00001218 RetEffect E =
1219 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenekec315332009-05-07 23:40:42 +00001220 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek92511432009-05-03 06:08:32 +00001221
1222 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001223 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001224
Ted Kremenek92511432009-05-03 06:08:32 +00001225 // Look for methods that return an owned core foundation object.
1226 if (isTrackedCFObjectType(RetTy)) {
1227 RetEffect E =
1228 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1229 ? RetEffect::MakeOwned(RetEffect::CF, true)
1230 : RetEffect::MakeNotOwned(RetEffect::CF);
1231
1232 return getPersistentSummary(E, ReceiverEff, MayEscape);
1233 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001234
Ted Kremenek92511432009-05-03 06:08:32 +00001235 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek7faca822009-05-04 04:57:00 +00001236 return getDefaultSummary();
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001237
Ted Kremenek885c27b2009-05-04 05:31:22 +00001238 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001239}
1240
1241RetainSummary*
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001242RetainSummaryManager::getInstanceMethodSummary(Selector S,
1243 IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001244 const ObjCInterfaceDecl* ID,
1245 const ObjCMethodDecl *MD,
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001246 QualType RetTy) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001247
Ted Kremenek8711c032009-04-29 05:04:30 +00001248 // Look up a summary in our summary cache.
1249 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001250
Ted Kremenek1f180c32008-06-23 22:21:20 +00001251 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001252 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001253
Ted Kremenekb77449c2009-05-03 05:20:50 +00001254 assert(ScratchArgs.isEmpty());
Ted Kremenek885c27b2009-05-04 05:31:22 +00001255 RetainSummary *Summ = 0;
Ted Kremenekaee9e572008-05-06 06:09:09 +00001256
Ted Kremenek885c27b2009-05-04 05:31:22 +00001257 // "initXXX": pass-through for receiver.
1258 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1259 == InitRule)
1260 Summ = getInitMethodSummary(RetTy);
1261 else
1262 Summ = getCommonMethodSummary(MD, S, RetTy);
1263
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001264 // Annotations override defaults.
1265 updateSummaryFromAnnotations(*Summ, MD);
1266
Ted Kremenek885c27b2009-05-04 05:31:22 +00001267 // Memoize the summary.
Ted Kremenek8711c032009-04-29 05:04:30 +00001268 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001269 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001270}
1271
Ted Kremenekc8395602008-05-06 21:26:51 +00001272RetainSummary*
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001273RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001274 const ObjCInterfaceDecl *ID,
1275 const ObjCMethodDecl *MD,
1276 QualType RetTy) {
Ted Kremenekde4d5332009-04-24 17:50:11 +00001277
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001278 assert(ClsName && "Class name must be specified.");
Ted Kremenek8711c032009-04-29 05:04:30 +00001279 ObjCMethodSummariesTy::iterator I =
1280 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001281
Ted Kremenek1f180c32008-06-23 22:21:20 +00001282 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001283 return I->second;
Ted Kremenek885c27b2009-05-04 05:31:22 +00001284
1285 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001286
1287 // Annotations override defaults.
1288 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001289
Ted Kremenek885c27b2009-05-04 05:31:22 +00001290 // Memoize the summary.
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001291 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001292 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001293}
1294
Ted Kremenekec315332009-05-07 23:40:42 +00001295void RetainSummaryManager::InitializeClassMethodSummaries() {
1296 assert(ScratchArgs.isEmpty());
1297 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001298
Ted Kremenek553cf182008-06-25 21:21:56 +00001299 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1300 // NSObject and its derivatives.
1301 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1302 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1303 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001304
1305 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001306 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001307 GetNullarySelector("currentHandler", Ctx),
1308 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001309
1310 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb77449c2009-05-03 05:20:50 +00001311 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenekabf43972009-01-28 21:44:40 +00001312 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1313 GetUnarySelector("addObject", Ctx),
1314 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001315 DoNothing, Autorelease));
Ted Kremenekde4d5332009-04-24 17:50:11 +00001316
1317 // Create the summaries for [NSObject performSelector...]. We treat
1318 // these as 'stop tracking' for the arguments because they are often
1319 // used for delegates that can release the object. When we have better
1320 // inter-procedural analysis we can potentially do something better. This
1321 // workaround is to remove false positives.
1322 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1323 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1324 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1325 "afterDelay", NULL);
1326 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1327 "afterDelay", "inModes", NULL);
1328 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1329 "withObject", "waitUntilDone", NULL);
1330 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1331 "withObject", "waitUntilDone", "modes", NULL);
1332 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1333 "withObject", "waitUntilDone", NULL);
1334 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1335 "withObject", "waitUntilDone", "modes", NULL);
1336 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1337 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001338}
1339
Ted Kremenek1f180c32008-06-23 22:21:20 +00001340void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001341
Ted Kremenekb77449c2009-05-03 05:20:50 +00001342 assert (ScratchArgs.isEmpty());
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001343
Ted Kremenekc8395602008-05-06 21:26:51 +00001344 // Create the "init" selector. It just acts as a pass-through for the
1345 // receiver.
Ted Kremenek78a35a32009-05-12 20:06:54 +00001346 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
1347 getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1348 DecRefMsg));
Ted Kremenekc8395602008-05-06 21:26:51 +00001349
1350 // The next methods are allocators.
Ted Kremenekec315332009-05-07 23:40:42 +00001351 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenekc8395602008-05-06 21:26:51 +00001352
1353 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001354 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1355
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001356 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001357 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001358
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001359 // Create the "retain" selector.
Ted Kremenekec315332009-05-07 23:40:42 +00001360 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001361 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001362 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001363
1364 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001365 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001366 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001367
1368 // Create the "drain" selector.
1369 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001370 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001371
1372 // Create the -dealloc summary.
1373 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1374 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001375
1376 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001377 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001378 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001379
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001380 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001381 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001382 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001383 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001384
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001385 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001386 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1387 // self-own themselves. However, they only do this once they are displayed.
1388 // Thus, we need to track an NSWindow's display status.
1389 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001390 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek78a35a32009-05-12 20:06:54 +00001391 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1392 StopTracking,
1393 StopTracking);
Ted Kremenek99d02692009-04-03 19:02:51 +00001394
1395 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1396
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001397#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001398 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001399 "styleMask", "backing", "defer", NULL);
1400
Ted Kremenek78a35a32009-05-12 20:06:54 +00001401 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001402 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001403#endif
Ted Kremenek78a35a32009-05-12 20:06:54 +00001404
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001405 // For NSPanel (which subclasses NSWindow), allocated objects are not
1406 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001407 // FIXME: For now we don't track NSPanels. object for the same reason
1408 // as for NSWindow objects.
1409 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1410
Ted Kremenek78a35a32009-05-12 20:06:54 +00001411#if 0
1412 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001413 "styleMask", "backing", "defer", NULL);
1414
Ted Kremenek78a35a32009-05-12 20:06:54 +00001415 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001416 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001417#endif
Ted Kremenek553cf182008-06-25 21:21:56 +00001418
Ted Kremenek70a733e2008-07-18 17:24:20 +00001419 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001420 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1421 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001422
Ted Kremenek9e476de2008-08-12 18:30:56 +00001423 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1424 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001425}
1426
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001427//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001428// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001429//===----------------------------------------------------------------------===//
1430
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001431namespace {
1432
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001433class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001434public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001435 enum Kind {
1436 Owned = 0, // Owning reference.
1437 NotOwned, // Reference is not owned by still valid (not freed).
1438 Released, // Object has been released.
1439 ReturnedOwned, // Returned object passes ownership to caller.
1440 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001441 ERROR_START,
1442 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1443 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001444 ErrorUseAfterRelease, // Object used after released.
1445 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001446 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001447 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek369de562009-05-09 00:10:05 +00001448 ErrorLeakReturned, // A memory leak due to the returning method not having
1449 // the correct naming conventions.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001450 ErrorGCLeakReturned,
1451 ErrorOverAutorelease,
1452 ErrorReturnedNotOwned
Ted Kremenek4fd88972008-04-17 18:12:53 +00001453 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001454
1455private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001456 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001457 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001458 unsigned Cnt;
Ted Kremenekf21332e2009-05-08 20:01:42 +00001459 unsigned ACnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001460 QualType T;
1461
Ted Kremenekf21332e2009-05-08 20:01:42 +00001462 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1463 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001464
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001465 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenekf21332e2009-05-08 20:01:42 +00001466 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001467
1468public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001469 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001470
1471 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001472
Ted Kremenekf21332e2009-05-08 20:01:42 +00001473 unsigned getCount() const { return Cnt; }
1474 unsigned getAutoreleaseCount() const { return ACnt; }
1475 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1476 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek369de562009-05-09 00:10:05 +00001477 void setCount(unsigned i) { Cnt = i; }
1478 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001479
Ted Kremenek553cf182008-06-25 21:21:56 +00001480 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001481
1482 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001483
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001484 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001485
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001486 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001487
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001488 bool isOwned() const {
1489 return getKind() == Owned;
1490 }
1491
Ted Kremenekdb863712008-04-16 22:32:20 +00001492 bool isNotOwned() const {
1493 return getKind() == NotOwned;
1494 }
1495
Ted Kremenek4fd88972008-04-17 18:12:53 +00001496 bool isReturnedOwned() const {
1497 return getKind() == ReturnedOwned;
1498 }
1499
1500 bool isReturnedNotOwned() const {
1501 return getKind() == ReturnedNotOwned;
1502 }
1503
1504 bool isNonLeakError() const {
1505 Kind k = getKind();
1506 return isError(k) && !isLeak(k);
1507 }
1508
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001509 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1510 unsigned Count = 1) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001511 return RefVal(Owned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001512 }
1513
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001514 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1515 unsigned Count = 0) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001516 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001517 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001518
Ted Kremenek4fd88972008-04-17 18:12:53 +00001519 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001520
Ted Kremenek4fd88972008-04-17 18:12:53 +00001521 bool operator==(const RefVal& X) const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001522 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001523 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001524
Ted Kremenek553cf182008-06-25 21:21:56 +00001525 RefVal operator-(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001526 return RefVal(getKind(), getObjKind(), getCount() - i,
1527 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001528 }
1529
1530 RefVal operator+(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001531 return RefVal(getKind(), getObjKind(), getCount() + i,
1532 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001533 }
1534
1535 RefVal operator^(Kind k) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001536 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1537 getType());
1538 }
1539
1540 RefVal autorelease() const {
1541 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1542 getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001543 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001544
Ted Kremenek4fd88972008-04-17 18:12:53 +00001545 void Profile(llvm::FoldingSetNodeID& ID) const {
1546 ID.AddInteger((unsigned) kind);
1547 ID.AddInteger(Cnt);
Ted Kremenekf21332e2009-05-08 20:01:42 +00001548 ID.AddInteger(ACnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001549 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001550 }
1551
Ted Kremenekf3948042008-03-11 19:44:10 +00001552 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001553};
Ted Kremenekf3948042008-03-11 19:44:10 +00001554
1555void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001556 if (!T.isNull())
1557 Out << "Tracked Type:" << T.getAsString() << '\n';
1558
Ted Kremenekf3948042008-03-11 19:44:10 +00001559 switch (getKind()) {
1560 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001561 case Owned: {
1562 Out << "Owned";
1563 unsigned cnt = getCount();
1564 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001565 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001566 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001567
Ted Kremenek61b9f872008-04-10 23:09:18 +00001568 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001569 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001570 unsigned cnt = getCount();
1571 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001572 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001573 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001574
Ted Kremenek4fd88972008-04-17 18:12:53 +00001575 case ReturnedOwned: {
1576 Out << "ReturnedOwned";
1577 unsigned cnt = getCount();
1578 if (cnt) Out << " (+ " << cnt << ")";
1579 break;
1580 }
1581
1582 case ReturnedNotOwned: {
1583 Out << "ReturnedNotOwned";
1584 unsigned cnt = getCount();
1585 if (cnt) Out << " (+ " << cnt << ")";
1586 break;
1587 }
1588
Ted Kremenekf3948042008-03-11 19:44:10 +00001589 case Released:
1590 Out << "Released";
1591 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001592
1593 case ErrorDeallocGC:
1594 Out << "-dealloc (GC)";
1595 break;
1596
1597 case ErrorDeallocNotOwned:
1598 Out << "-dealloc (not-owned)";
1599 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001600
Ted Kremenekdb863712008-04-16 22:32:20 +00001601 case ErrorLeak:
1602 Out << "Leaked";
1603 break;
1604
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001605 case ErrorLeakReturned:
1606 Out << "Leaked (Bad naming)";
1607 break;
1608
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001609 case ErrorGCLeakReturned:
1610 Out << "Leaked (GC-ed at return)";
1611 break;
1612
Ted Kremenekf3948042008-03-11 19:44:10 +00001613 case ErrorUseAfterRelease:
1614 Out << "Use-After-Release [ERROR]";
1615 break;
1616
1617 case ErrorReleaseNotOwned:
1618 Out << "Release of Not-Owned [ERROR]";
1619 break;
Ted Kremenek80c24182009-05-09 00:44:07 +00001620
1621 case RefVal::ErrorOverAutorelease:
1622 Out << "Over autoreleased";
1623 break;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001624
1625 case RefVal::ErrorReturnedNotOwned:
1626 Out << "Non-owned object returned instead of owned";
1627 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001628 }
Ted Kremenekf21332e2009-05-08 20:01:42 +00001629
1630 if (ACnt) {
1631 Out << " [ARC +" << ACnt << ']';
1632 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001633}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001634
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001635} // end anonymous namespace
1636
1637//===----------------------------------------------------------------------===//
1638// RefBindings - State used to track object reference counts.
1639//===----------------------------------------------------------------------===//
1640
Ted Kremenek2dabd432008-12-05 02:27:51 +00001641typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001642static int RefBIndex = 0;
1643
1644namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001645 template<>
1646 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1647 static inline void* GDMIndex() { return &RefBIndex; }
1648 };
1649}
Ted Kremenek6d348932008-10-21 15:53:15 +00001650
1651//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001652// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001653//===----------------------------------------------------------------------===//
1654
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001655typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1656typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1657typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001658
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001659static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001660static int AutoRBIndex = 0;
1661
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001662namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001663namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001664
Ted Kremenek6d348932008-10-21 15:53:15 +00001665namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001666template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001667 : public GRStatePartialTrait<ARStack> {
1668 static inline void* GDMIndex() { return &AutoRBIndex; }
1669};
1670
1671template<> struct GRStateTrait<AutoreleasePoolContents>
1672 : public GRStatePartialTrait<ARPoolContents> {
1673 static inline void* GDMIndex() { return &AutoRCIndex; }
1674};
1675} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001676
Ted Kremenek7037ab82009-03-20 17:34:15 +00001677static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1678 ARStack stack = state->get<AutoreleaseStack>();
1679 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1680}
1681
1682static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1683 SymbolRef sym) {
1684
1685 SymbolRef pool = GetCurrentAutoreleasePool(state);
1686 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1687 ARCounts newCnts(0);
1688
1689 if (cnts) {
1690 const unsigned *cnt = (*cnts).lookup(sym);
1691 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1692 }
1693 else
1694 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1695
1696 return state.set<AutoreleasePoolContents>(pool, newCnts);
1697}
1698
Ted Kremenek13922612008-04-16 20:40:59 +00001699//===----------------------------------------------------------------------===//
1700// Transfer functions.
1701//===----------------------------------------------------------------------===//
1702
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001703namespace {
1704
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001705class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001706public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001707 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001708 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001709 virtual void Print(std::ostream& Out, const GRState* state,
1710 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001711 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001712
1713private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001714 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1715 SummaryLogTy;
1716
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001717 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001718 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001719 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001720 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001721
Ted Kremenekcf701772009-02-05 06:50:21 +00001722 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001723 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001724 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek369de562009-05-09 00:10:05 +00001725 BugType *overAutorelease;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001726 BugType *returnNotOwnedForOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001727 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001728
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001729 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1730 RefVal::Kind& hasErr);
1731
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001732 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1733 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu264e9372009-05-12 10:10:00 +00001734 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001735 ExplodedNode<GRState>* Pred,
1736 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001737 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001738
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001739 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1740 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1741
1742 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1743 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1744 GenericNodeBuilder &Builder,
1745 GRExprEngine &Eng,
1746 ExplodedNode<GRState> *Pred = 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001747
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001748public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001749 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001750 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001751 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1752 deallocGC(0), deallocNotOwned(0),
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001753 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1754 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001755
Ted Kremenekcf701772009-02-05 06:50:21 +00001756 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001757
Ted Kremenekcf118d42009-02-04 23:49:09 +00001758 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001759
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001760 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1761 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001762 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001763
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001764 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001765 const LangOptions& getLangOptions() const { return LOpts; }
1766
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001767 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1768 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1769 return I == SummaryLog.end() ? 0 : I->second;
1770 }
1771
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001772 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001773
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001774 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001775 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001776 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001777 Expr* Ex,
1778 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00001779 const RetainSummary& Summ,
Zhongxing Xu264e9372009-05-12 10:10:00 +00001780 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001781 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001782
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001783 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001784 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001785 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001786 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001787 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001788
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001789
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001790 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001791 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001792 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001793 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001794 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001795
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001796 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001797 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001798 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001799 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001800 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001801
Ted Kremenek41573eb2009-02-14 01:43:44 +00001802 // Stores.
1803 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1804
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001805 // End-of-path.
1806
1807 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001808 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001809
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001810 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001811 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001812 GRStmtNodeBuilder<GRState>& Builder,
1813 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001814 Stmt* S, const GRState* state,
1815 SymbolReaper& SymReaper);
Ted Kremenekf04dced2009-05-08 23:32:51 +00001816
1817 std::pair<ExplodedNode<GRState>*, GRStateRef>
1818 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek369de562009-05-09 00:10:05 +00001819 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1820 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001821 // Return statements.
1822
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001823 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001824 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001825 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001826 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001827 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001828
1829 // Assumptions.
1830
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001831 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001832 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001833 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001834};
1835
1836} // end anonymous namespace
1837
Ted Kremenek7037ab82009-03-20 17:34:15 +00001838static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1839 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001840 if (Sym)
1841 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001842 else
1843 Out << "<pool>";
1844 Out << ":{";
1845
1846 // Get the contents of the pool.
1847 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1848 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1849 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1850
1851 Out << '}';
1852}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001853
Ted Kremenekae6814e2008-08-13 21:24:49 +00001854void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1855 const char* nl, const char* sep) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001856
1857
Ted Kremenekae6814e2008-08-13 21:24:49 +00001858
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001859 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001860
Ted Kremenekae6814e2008-08-13 21:24:49 +00001861 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001862 Out << sep << nl;
1863
1864 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1865 Out << (*I).first << " : ";
1866 (*I).second.print(Out);
1867 Out << nl;
1868 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001869
1870 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001871 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001872 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001873
Ted Kremenek7037ab82009-03-20 17:34:15 +00001874 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1875 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1876 PrintPool(Out, *I, state);
1877
1878 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00001879}
1880
Ted Kremenekc887d132009-04-29 18:50:19 +00001881//===----------------------------------------------------------------------===//
1882// Error reporting.
1883//===----------------------------------------------------------------------===//
1884
1885namespace {
1886
1887 //===-------------===//
1888 // Bug Descriptions. //
1889 //===-------------===//
1890
1891 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1892 protected:
1893 CFRefCount& TF;
1894
1895 CFRefBug(CFRefCount* tf, const char* name)
1896 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1897 public:
1898
1899 CFRefCount& getTF() { return TF; }
1900 const CFRefCount& getTF() const { return TF; }
1901
1902 // FIXME: Eventually remove.
1903 virtual const char* getDescription() const = 0;
1904
1905 virtual bool isLeak() const { return false; }
1906 };
1907
1908 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1909 public:
1910 UseAfterRelease(CFRefCount* tf)
1911 : CFRefBug(tf, "Use-after-release") {}
1912
1913 const char* getDescription() const {
1914 return "Reference-counted object is used after it is released";
1915 }
1916 };
1917
1918 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1919 public:
1920 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1921
1922 const char* getDescription() const {
1923 return "Incorrect decrement of the reference count of an "
1924 "object is not owned at this point by the caller";
1925 }
1926 };
1927
1928 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1929 public:
Ted Kremenek369de562009-05-09 00:10:05 +00001930 DeallocGC(CFRefCount *tf)
1931 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001932
1933 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001934 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001935 }
1936 };
1937
1938 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1939 public:
Ted Kremenek369de562009-05-09 00:10:05 +00001940 DeallocNotOwned(CFRefCount *tf)
1941 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001942
1943 const char *getDescription() const {
1944 return "-dealloc sent to object that may be referenced elsewhere";
1945 }
1946 };
1947
Ted Kremenek369de562009-05-09 00:10:05 +00001948 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1949 public:
1950 OverAutorelease(CFRefCount *tf) :
1951 CFRefBug(tf, "Object sent -autorelease too many times") {}
1952
1953 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001954 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001955 }
1956 };
1957
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001958 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1959 public:
1960 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1961 CFRefBug(tf, "Method should return an owned object") {}
1962
1963 const char *getDescription() const {
1964 return "Object with +0 retain counts returned to caller where a +1 "
1965 "(owning) retain count is expected";
1966 }
1967 };
1968
Ted Kremenekc887d132009-04-29 18:50:19 +00001969 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1970 const bool isReturn;
1971 protected:
1972 Leak(CFRefCount* tf, const char* name, bool isRet)
1973 : CFRefBug(tf, name), isReturn(isRet) {}
1974 public:
1975
1976 const char* getDescription() const { return ""; }
1977
1978 bool isLeak() const { return true; }
1979 };
1980
1981 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1982 public:
1983 LeakAtReturn(CFRefCount* tf, const char* name)
1984 : Leak(tf, name, true) {}
1985 };
1986
1987 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1988 public:
1989 LeakWithinFunction(CFRefCount* tf, const char* name)
1990 : Leak(tf, name, false) {}
1991 };
1992
1993 //===---------===//
1994 // Bug Reports. //
1995 //===---------===//
1996
1997 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1998 protected:
1999 SymbolRef Sym;
2000 const CFRefCount &TF;
2001 public:
2002 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2003 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002004 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2005
2006 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2007 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu264e9372009-05-12 10:10:00 +00002008 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002009
2010 virtual ~CFRefReport() {}
2011
2012 CFRefBug& getBugType() {
2013 return (CFRefBug&) RangedBugReport::getBugType();
2014 }
2015 const CFRefBug& getBugType() const {
2016 return (const CFRefBug&) RangedBugReport::getBugType();
2017 }
2018
2019 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2020 const SourceRange*& end) {
2021
2022 if (!getBugType().isLeak())
2023 RangedBugReport::getRanges(BR, beg, end);
2024 else
2025 beg = end = 0;
2026 }
2027
2028 SymbolRef getSymbol() const { return Sym; }
2029
Ted Kremenek8966bc12009-05-06 21:39:49 +00002030 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002031 const ExplodedNode<GRState>* N);
2032
2033 std::pair<const char**,const char**> getExtraDescriptiveText();
2034
2035 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2036 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002037 BugReporterContext& BRC);
Ted Kremenekc887d132009-04-29 18:50:19 +00002038 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002039
Ted Kremenekc887d132009-04-29 18:50:19 +00002040 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2041 SourceLocation AllocSite;
2042 const MemRegion* AllocBinding;
2043 public:
2044 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2045 ExplodedNode<GRState> *n, SymbolRef sym,
2046 GRExprEngine& Eng);
2047
Ted Kremenek8966bc12009-05-06 21:39:49 +00002048 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002049 const ExplodedNode<GRState>* N);
2050
2051 SourceLocation getLocation() const { return AllocSite; }
2052 };
2053} // end anonymous namespace
2054
2055void CFRefCount::RegisterChecks(BugReporter& BR) {
2056 useAfterRelease = new UseAfterRelease(this);
2057 BR.Register(useAfterRelease);
2058
2059 releaseNotOwned = new BadRelease(this);
2060 BR.Register(releaseNotOwned);
2061
2062 deallocGC = new DeallocGC(this);
2063 BR.Register(deallocGC);
2064
2065 deallocNotOwned = new DeallocNotOwned(this);
2066 BR.Register(deallocNotOwned);
2067
Ted Kremenek369de562009-05-09 00:10:05 +00002068 overAutorelease = new OverAutorelease(this);
2069 BR.Register(overAutorelease);
2070
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002071 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2072 BR.Register(returnNotOwnedForOwned);
2073
Ted Kremenekc887d132009-04-29 18:50:19 +00002074 // First register "return" leaks.
2075 const char* name = 0;
2076
2077 if (isGCEnabled())
2078 name = "Leak of returned object when using garbage collection";
2079 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2080 name = "Leak of returned object when not using garbage collection (GC) in "
2081 "dual GC/non-GC code";
2082 else {
2083 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2084 name = "Leak of returned object";
2085 }
2086
2087 leakAtReturn = new LeakAtReturn(this, name);
2088 BR.Register(leakAtReturn);
2089
2090 // Second, register leaks within a function/method.
2091 if (isGCEnabled())
2092 name = "Leak of object when using garbage collection";
2093 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2094 name = "Leak of object when not using garbage collection (GC) in "
2095 "dual GC/non-GC code";
2096 else {
2097 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2098 name = "Leak";
2099 }
2100
2101 leakWithinFunction = new LeakWithinFunction(this, name);
2102 BR.Register(leakWithinFunction);
2103
2104 // Save the reference to the BugReporter.
2105 this->BR = &BR;
2106}
2107
2108static const char* Msgs[] = {
2109 // GC only
2110 "Code is compiled to only use garbage collection",
2111 // No GC.
2112 "Code is compiled to use reference counts",
2113 // Hybrid, with GC.
2114 "Code is compiled to use either garbage collection (GC) or reference counts"
2115 " (non-GC). The bug occurs with GC enabled",
2116 // Hybrid, without GC
2117 "Code is compiled to use either garbage collection (GC) or reference counts"
2118 " (non-GC). The bug occurs in non-GC mode"
2119};
2120
2121std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2122 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2123
2124 switch (TF.getLangOptions().getGCMode()) {
2125 default:
2126 assert(false);
2127
2128 case LangOptions::GCOnly:
2129 assert (TF.isGCEnabled());
2130 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2131
2132 case LangOptions::NonGC:
2133 assert (!TF.isGCEnabled());
2134 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2135
2136 case LangOptions::HybridGC:
2137 if (TF.isGCEnabled())
2138 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2139 else
2140 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2141 }
2142}
2143
2144static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2145 ArgEffect X) {
2146 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2147 I!=E; ++I)
2148 if (*I == X) return true;
2149
2150 return false;
2151}
2152
2153PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2154 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002155 BugReporterContext& BRC) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002156
Ted Kremenek2033a952009-05-13 07:12:33 +00002157 if (!isa<PostStmt>(N->getLocation()))
2158 return NULL;
2159
Ted Kremenek8966bc12009-05-06 21:39:49 +00002160 // Check if the type state has changed.
2161 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002162 GRStateRef PrevSt(PrevN->getState(), StMgr);
2163 GRStateRef CurrSt(N->getState(), StMgr);
2164
2165 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2166 if (!CurrT) return NULL;
2167
2168 const RefVal& CurrV = *CurrT;
2169 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2170
2171 // Create a string buffer to constain all the useful things we want
2172 // to tell the user.
2173 std::string sbuf;
2174 llvm::raw_string_ostream os(sbuf);
2175
2176 // This is the allocation site since the previous node had no bindings
2177 // for this symbol.
2178 if (!PrevT) {
2179 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2180
2181 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2182 // Get the name of the callee (if it is available).
2183 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2184 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2185 os << "Call to function '" << FD->getNameAsString() <<'\'';
2186 else
2187 os << "function call";
2188 }
2189 else {
2190 assert (isa<ObjCMessageExpr>(S));
2191 os << "Method";
2192 }
2193
2194 if (CurrV.getObjKind() == RetEffect::CF) {
2195 os << " returns a Core Foundation object with a ";
2196 }
2197 else {
2198 assert (CurrV.getObjKind() == RetEffect::ObjC);
2199 os << " returns an Objective-C object with a ";
2200 }
2201
2202 if (CurrV.isOwned()) {
2203 os << "+1 retain count (owning reference).";
2204
2205 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2206 assert(CurrV.getObjKind() == RetEffect::CF);
2207 os << " "
2208 "Core Foundation objects are not automatically garbage collected.";
2209 }
2210 }
2211 else {
2212 assert (CurrV.isNotOwned());
2213 os << "+0 retain count (non-owning reference).";
2214 }
2215
Ted Kremenek8966bc12009-05-06 21:39:49 +00002216 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002217 return new PathDiagnosticEventPiece(Pos, os.str());
2218 }
2219
2220 // Gather up the effects that were performed on the object at this
2221 // program point
2222 llvm::SmallVector<ArgEffect, 2> AEffects;
2223
Ted Kremenek8966bc12009-05-06 21:39:49 +00002224 if (const RetainSummary *Summ =
2225 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002226 // We only have summaries attached to nodes after evaluating CallExpr and
2227 // ObjCMessageExprs.
2228 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2229
2230 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2231 // Iterate through the parameter expressions and see if the symbol
2232 // was ever passed as an argument.
2233 unsigned i = 0;
2234
2235 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2236 AI!=AE; ++AI, ++i) {
2237
2238 // Retrieve the value of the argument. Is it the symbol
2239 // we are interested in?
2240 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2241 continue;
2242
2243 // We have an argument. Get the effect!
2244 AEffects.push_back(Summ->getArg(i));
2245 }
2246 }
2247 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2248 if (Expr *receiver = ME->getReceiver())
2249 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2250 // The symbol we are tracking is the receiver.
2251 AEffects.push_back(Summ->getReceiverEffect());
2252 }
2253 }
2254 }
2255
2256 do {
2257 // Get the previous type state.
2258 RefVal PrevV = *PrevT;
2259
2260 // Specially handle -dealloc.
2261 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2262 // Determine if the object's reference count was pushed to zero.
2263 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2264 // We may not have transitioned to 'release' if we hit an error.
2265 // This case is handled elsewhere.
2266 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002267 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002268 os << "Object released by directly sending the '-dealloc' message";
2269 break;
2270 }
2271 }
2272
2273 // Specially handle CFMakeCollectable and friends.
2274 if (contains(AEffects, MakeCollectable)) {
2275 // Get the name of the function.
2276 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2277 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2278 const FunctionDecl* FD = X.getAsFunctionDecl();
2279 const std::string& FName = FD->getNameAsString();
2280
2281 if (TF.isGCEnabled()) {
2282 // Determine if the object's reference count was pushed to zero.
2283 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2284
2285 os << "In GC mode a call to '" << FName
2286 << "' decrements an object's retain count and registers the "
2287 "object with the garbage collector. ";
2288
2289 if (CurrV.getKind() == RefVal::Released) {
2290 assert(CurrV.getCount() == 0);
2291 os << "Since it now has a 0 retain count the object can be "
2292 "automatically collected by the garbage collector.";
2293 }
2294 else
2295 os << "An object must have a 0 retain count to be garbage collected. "
2296 "After this call its retain count is +" << CurrV.getCount()
2297 << '.';
2298 }
2299 else
2300 os << "When GC is not enabled a call to '" << FName
2301 << "' has no effect on its argument.";
2302
2303 // Nothing more to say.
2304 break;
2305 }
2306
2307 // Determine if the typestate has changed.
2308 if (!(PrevV == CurrV))
2309 switch (CurrV.getKind()) {
2310 case RefVal::Owned:
2311 case RefVal::NotOwned:
2312
Ted Kremenekf21332e2009-05-08 20:01:42 +00002313 if (PrevV.getCount() == CurrV.getCount()) {
2314 // Did an autorelease message get sent?
2315 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2316 return 0;
2317
Zhongxing Xu264e9372009-05-12 10:10:00 +00002318 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002319 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002320 break;
2321 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002322
2323 if (PrevV.getCount() > CurrV.getCount())
2324 os << "Reference count decremented.";
2325 else
2326 os << "Reference count incremented.";
2327
2328 if (unsigned Count = CurrV.getCount())
2329 os << " The object now has a +" << Count << " retain count.";
2330
2331 if (PrevV.getKind() == RefVal::Released) {
2332 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2333 os << " The object is not eligible for garbage collection until the "
2334 "retain count reaches 0 again.";
2335 }
2336
2337 break;
2338
2339 case RefVal::Released:
2340 os << "Object released.";
2341 break;
2342
2343 case RefVal::ReturnedOwned:
2344 os << "Object returned to caller as an owning reference (single retain "
2345 "count transferred to caller).";
2346 break;
2347
2348 case RefVal::ReturnedNotOwned:
2349 os << "Object returned to caller with a +0 (non-owning) retain count.";
2350 break;
2351
2352 default:
2353 return NULL;
2354 }
2355
2356 // Emit any remaining diagnostics for the argument effects (if any).
2357 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2358 E=AEffects.end(); I != E; ++I) {
2359
2360 // A bunch of things have alternate behavior under GC.
2361 if (TF.isGCEnabled())
2362 switch (*I) {
2363 default: break;
2364 case Autorelease:
2365 os << "In GC mode an 'autorelease' has no effect.";
2366 continue;
2367 case IncRefMsg:
2368 os << "In GC mode the 'retain' message has no effect.";
2369 continue;
2370 case DecRefMsg:
2371 os << "In GC mode the 'release' message has no effect.";
2372 continue;
2373 }
2374 }
2375 } while(0);
2376
2377 if (os.str().empty())
2378 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002379
2380 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek8966bc12009-05-06 21:39:49 +00002381 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002382 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2383
2384 // Add the range by scanning the children of the statement for any bindings
2385 // to Sym.
2386 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2387 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2388 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2389 P->addRange(Exp->getSourceRange());
2390 break;
2391 }
2392
2393 return P;
2394}
2395
2396namespace {
2397 class VISIBILITY_HIDDEN FindUniqueBinding :
2398 public StoreManager::BindingsHandler {
2399 SymbolRef Sym;
2400 const MemRegion* Binding;
2401 bool First;
2402
2403 public:
2404 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2405
2406 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2407 SVal val) {
2408
2409 SymbolRef SymV = val.getAsSymbol();
2410 if (!SymV || SymV != Sym)
2411 return true;
2412
2413 if (Binding) {
2414 First = false;
2415 return false;
2416 }
2417 else
2418 Binding = R;
2419
2420 return true;
2421 }
2422
2423 operator bool() { return First && Binding; }
2424 const MemRegion* getRegion() { return Binding; }
2425 };
2426}
2427
2428static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2429GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2430 SymbolRef Sym) {
2431
2432 // Find both first node that referred to the tracked symbol and the
2433 // memory location that value was store to.
2434 const ExplodedNode<GRState>* Last = N;
2435 const MemRegion* FirstBinding = 0;
2436
2437 while (N) {
2438 const GRState* St = N->getState();
2439 RefBindings B = St->get<RefBindings>();
2440
2441 if (!B.lookup(Sym))
2442 break;
2443
2444 FindUniqueBinding FB(Sym);
2445 StateMgr.iterBindings(St, FB);
2446 if (FB) FirstBinding = FB.getRegion();
2447
2448 Last = N;
2449 N = N->pred_empty() ? NULL : *(N->pred_begin());
2450 }
2451
2452 return std::make_pair(Last, FirstBinding);
2453}
2454
2455PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002456CFRefReport::getEndPath(BugReporterContext& BRC,
2457 const ExplodedNode<GRState>* EndN) {
2458 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002459 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002460 BRC.addNotableSymbol(Sym);
2461 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenekc887d132009-04-29 18:50:19 +00002462}
2463
2464PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002465CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2466 const ExplodedNode<GRState>* EndN){
Ted Kremenekc887d132009-04-29 18:50:19 +00002467
Ted Kremenek8966bc12009-05-06 21:39:49 +00002468 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002469 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002470 BRC.addNotableSymbol(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002471
2472 // We are reporting a leak. Walk up the graph to get to the first node where
2473 // the symbol appeared, and also get the first VarDecl that tracked object
2474 // is stored to.
2475 const ExplodedNode<GRState>* AllocNode = 0;
2476 const MemRegion* FirstBinding = 0;
2477
2478 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002479 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002480
2481 // Get the allocate site.
2482 assert(AllocNode);
2483 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2484
Ted Kremenek8966bc12009-05-06 21:39:49 +00002485 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002486 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2487
2488 // Compute an actual location for the leak. Sometimes a leak doesn't
2489 // occur at an actual statement (e.g., transition between blocks; end
2490 // of function) so we need to walk the graph and compute a real location.
2491 const ExplodedNode<GRState>* LeakN = EndN;
2492 PathDiagnosticLocation L;
2493
2494 while (LeakN) {
2495 ProgramPoint P = LeakN->getLocation();
2496
2497 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2498 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2499 break;
2500 }
2501 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2502 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2503 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2504 break;
2505 }
2506 }
2507
2508 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2509 }
2510
2511 if (!L.isValid()) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00002512 const Decl &D = BRC.getCodeDecl();
2513 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenekc887d132009-04-29 18:50:19 +00002514 }
2515
2516 std::string sbuf;
2517 llvm::raw_string_ostream os(sbuf);
2518
2519 os << "Object allocated on line " << AllocLine;
2520
2521 if (FirstBinding)
2522 os << " and stored into '" << FirstBinding->getString() << '\'';
2523
2524 // Get the retain count.
2525 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2526
2527 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2528 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2529 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2530 // to the caller for NS objects.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002531 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenekc887d132009-04-29 18:50:19 +00002532 os << " is returned from a method whose name ('"
Ted Kremeneka8833552009-04-29 23:03:22 +00002533 << MD.getSelector().getAsString()
Ted Kremenekc887d132009-04-29 18:50:19 +00002534 << "') does not contain 'copy' or otherwise starts with"
2535 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek8987a022009-04-29 22:25:52 +00002536 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002537 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002538 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2539 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2540 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002541 << "' is potentially leaked when using garbage collection. Callers "
2542 "of this method do not expect a returned object with a +1 retain "
2543 "count since they expect the object to be managed by the garbage "
2544 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002545 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002546 else
2547 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek8987a022009-04-29 22:25:52 +00002548 " +" << RV->getCount() << " (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002549
2550 return new PathDiagnosticEventPiece(L, os.str());
2551}
2552
Ted Kremenekc887d132009-04-29 18:50:19 +00002553CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2554 ExplodedNode<GRState> *n,
2555 SymbolRef sym, GRExprEngine& Eng)
2556: CFRefReport(D, tf, n, sym)
2557{
2558
2559 // Most bug reports are cached at the location where they occured.
2560 // With leaks, we want to unique them by the location where they were
2561 // allocated, and only report a single path. To do this, we need to find
2562 // the allocation site of a piece of tracked memory, which we do via a
2563 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2564 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2565 // that all ancestor nodes that represent the allocation site have the
2566 // same SourceLocation.
2567 const ExplodedNode<GRState>* AllocNode = 0;
2568
2569 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekf04dced2009-05-08 23:32:51 +00002570 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenekc887d132009-04-29 18:50:19 +00002571
2572 // Get the SourceLocation for the allocation site.
2573 ProgramPoint P = AllocNode->getLocation();
2574 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2575
2576 // Fill in the description of the bug.
2577 Description.clear();
2578 llvm::raw_string_ostream os(Description);
2579 SourceManager& SMgr = Eng.getContext().getSourceManager();
2580 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002581 os << "Potential leak ";
2582 if (tf.isGCEnabled()) {
2583 os << "(when using garbage collection) ";
2584 }
2585 os << "of an object allocated on line " << AllocLine;
Ted Kremenekc887d132009-04-29 18:50:19 +00002586
2587 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2588 if (AllocBinding)
2589 os << " and stored into '" << AllocBinding->getString() << '\'';
2590}
2591
2592//===----------------------------------------------------------------------===//
2593// Main checker logic.
2594//===----------------------------------------------------------------------===//
2595
Ted Kremenek553cf182008-06-25 21:21:56 +00002596/// GetReturnType - Used to get the return type of a message expression or
2597/// function call with the intention of affixing that type to a tracked symbol.
2598/// While the the return type can be queried directly from RetEx, when
2599/// invoking class methods we augment to the return type to be that of
2600/// a pointer to the class (as opposed it just being id).
2601static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2602
2603 QualType RetTy = RetE->getType();
2604
2605 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00002606 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002607 if (!PT)
2608 return RetTy;
2609
2610 // If RetEx is not a message expression just return its type.
2611 // If RetEx is a message expression, return its types if it is something
2612 /// more specific than id.
2613
2614 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2615
Steve Naroff389bf462009-02-12 17:52:19 +00002616 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00002617 return RetTy;
2618
2619 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2620
2621 // At this point we know the return type of the message expression is id.
2622 // If we have an ObjCInterceDecl, we know this is a call to a class method
2623 // whose type we can resolve. In such cases, promote the return type to
2624 // Class*.
2625 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2626}
2627
2628
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002629void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002630 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002631 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002632 Expr* Ex,
2633 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00002634 const RetainSummary& Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00002635 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002636 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002637
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002638 // Get the state.
Zhongxing Xu264e9372009-05-12 10:10:00 +00002639 GRStateManager& StateMgr = Eng.getStateManager();
2640 GRStateRef state(Builder.GetState(Pred), StateMgr);
2641 ASTContext& Ctx = StateMgr.getContext();
2642 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek14993892008-05-06 02:41:27 +00002643
2644 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002645 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002646 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002647 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00002648 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002649
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002650 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002651 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00002652 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002653
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002654 if (Sym)
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002655 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002656 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002657 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002658 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002659 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002660 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00002661 }
2662 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002663 }
Ted Kremenek070a8252008-07-09 18:11:16 +00002664
Ted Kremenek94c96982009-03-03 22:06:47 +00002665 if (isa<Loc>(V)) {
2666 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002667 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenek070a8252008-07-09 18:11:16 +00002668 continue;
2669
2670 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002671
2672 // FIXME: Either this logic should also be replicated in GRSimpleVals
2673 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00002674
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002675 // FIXME: We can have collisions on the conjured symbol if the
2676 // expression *I also creates conjured symbols. We probably want
2677 // to identify conjured symbols by an expression pair: the enclosing
2678 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00002679 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00002680
Ted Kremenek993f1c72008-10-17 20:28:54 +00002681 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xuf82af1e2009-04-29 02:30:09 +00002682
Ted Kremenek42530512009-05-06 18:19:24 +00002683 if (R) {
2684 // Are we dealing with an ElementRegion? If the element type is
2685 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xu2e7c6782009-05-11 14:28:14 +00002686 // is a variable region then strip off the ElementRegion.
Ted Kremenek42530512009-05-06 18:19:24 +00002687 // FIXME: We really need to think about this for the general case
2688 // as sometimes we are reasoning about arrays and other times
2689 // about (char*), etc., is just a form of passing raw bytes.
2690 // e.g., void *p = alloca(); foo((char*)p);
2691 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2692 // Checking for 'integral type' is probably too promiscuous, but
2693 // we'll leave it in for now until we have a systematic way of
2694 // handling all of these cases. Eventually we need to come up
2695 // with an interface to StoreManager so that this logic can be
2696 // approriately delegated to the respective StoreManagers while
2697 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu264e9372009-05-12 10:10:00 +00002698 // invalidating reference counts), probably via callbacks.
Ted Kremenek109bf472009-05-11 22:55:17 +00002699 if (ER->getElementType()->isIntegralType()) {
2700 const MemRegion *superReg = ER->getSuperRegion();
2701 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2702 isa<ObjCIvarRegion>(superReg))
2703 R = cast<TypedRegion>(superReg);
2704 }
2705
Ted Kremenek42530512009-05-06 18:19:24 +00002706 // FIXME: What about layers of ElementRegions?
2707 }
2708
Ted Kremenek40e86d92008-12-18 23:34:57 +00002709 // Is the invalidated variable something that we were tracking?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002710 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00002711
Ted Kremenekd104a092009-03-04 22:56:43 +00002712 // Remove any existing reference-count binding.
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002713 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00002714
Ted Kremenekd104a092009-03-04 22:56:43 +00002715 if (R->isBoundable(Ctx)) {
2716 // Set the value of the variable to be a conjured symbol.
2717 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xua82d8aa2009-05-09 03:57:34 +00002718 QualType T = R->getValueType(Ctx);
Ted Kremenekd104a092009-03-04 22:56:43 +00002719
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002720 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002721 ValueManager &ValMgr = Eng.getValueManager();
2722 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002723 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002724 }
2725 else if (const RecordType *RT = T->getAsStructureType()) {
2726 // Handle structs in a not so awesome way. Here we just
2727 // eagerly bind new symbols to the fields. In reality we
2728 // should have the store manager handle this. The idea is just
2729 // to prototype some basic functionality here. All of this logic
2730 // should one day soon just go away.
2731 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2732
2733 // No record definition. There is nothing we can do.
2734 if (!RD)
2735 continue;
2736
2737 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2738
2739 // Iterate through the fields and construct new symbols.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002740 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2741 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002742
2743 // For now just handle scalar fields.
2744 FieldDecl *FD = *FI;
2745 QualType FT = FD->getType();
2746
2747 if (Loc::IsLocType(FT) ||
Zhongxing Xu264e9372009-05-12 10:10:00 +00002748 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002749 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu264e9372009-05-12 10:10:00 +00002750
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002751 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xu6782f752009-04-09 06:32:20 +00002752 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002753 }
2754 }
Zhongxing Xu264e9372009-05-12 10:10:00 +00002755 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2756 // Set the default value of the array to conjured symbol.
2757 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2758 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2759 Count);
2760 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2761 StateMgr);
2762 } else {
Ted Kremenekd104a092009-03-04 22:56:43 +00002763 // Just blast away other values.
2764 state = state.BindLoc(*MR, UnknownVal());
2765 }
Ted Kremenekfd301942008-10-17 22:23:12 +00002766 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002767 }
2768 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002769 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002770 }
2771 else {
2772 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002773 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002774 }
Ted Kremenekb8873552008-04-11 20:51:02 +00002775 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002776 else if (isa<nonloc::LocAsInteger>(V))
2777 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002778 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002779
Ted Kremenek553cf182008-06-25 21:21:56 +00002780 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00002781 if (!ErrorExpr && Receiver) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002782 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002783 if (Sym) {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002784 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002785 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002786 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00002787 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002788 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00002789 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002790 }
Ted Kremenek14993892008-05-06 02:41:27 +00002791 }
2792 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002793
Ted Kremenek553cf182008-06-25 21:21:56 +00002794 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002795 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002796 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002797 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002798 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002799 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002800
Ted Kremenek70a733e2008-07-18 17:24:20 +00002801 // Consult the summary for the return value.
Ted Kremenek7faca822009-05-04 04:57:00 +00002802 RetEffect RE = Summ.getRetEffect();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002803
Ted Kremenek78a35a32009-05-12 20:06:54 +00002804 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2805 assert(Receiver);
2806 SVal V = state.GetSValAsScalarOrLoc(Receiver);
2807 bool found = false;
2808 if (SymbolRef Sym = V.getAsLocSymbol())
2809 if (state.get<RefBindings>(Sym)) {
2810 found = true;
2811 RE = Summaries.getObjAllocRetEffect();
2812 }
2813
2814 if (!found)
2815 RE = RetEffect::MakeNoRet();
2816 }
2817
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002818 switch (RE.getKind()) {
2819 default:
2820 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002821
Ted Kremenekfd301942008-10-17 22:23:12 +00002822 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002823
Ted Kremenekf9561e52008-04-11 20:23:24 +00002824 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00002825 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2826 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00002827
Ted Kremenekfd301942008-10-17 22:23:12 +00002828 // FIXME: We eventually should handle structs and other compound types
2829 // that are returned by value.
2830
2831 QualType T = Ex->getType();
2832
Ted Kremenek062e2f92008-11-13 06:10:40 +00002833 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002834 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002835 ValueManager &ValMgr = Eng.getValueManager();
2836 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002837 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00002838 }
2839
Ted Kremenek940b1d82008-04-10 23:44:06 +00002840 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00002841 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002842
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002843 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00002844 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00002845 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002846 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002847 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002848 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002849 break;
2850 }
2851
Ted Kremenek14993892008-05-06 02:41:27 +00002852 case RetEffect::ReceiverAlias: {
2853 assert (Receiver);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002854 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002855 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00002856 break;
2857 }
2858
Ted Kremeneka7344702008-06-23 18:02:52 +00002859 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002860 case RetEffect::OwnedSymbol: {
2861 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002862 ValueManager &ValMgr = Eng.getValueManager();
2863 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2864 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2865 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2866 RetT));
2867 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002868
2869 // FIXME: Add a flag to the checker where allocations are assumed to
2870 // *not fail.
2871#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00002872 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2873 bool isFeasible;
2874 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2875 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2876 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002877#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00002878
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002879 break;
2880 }
Ted Kremeneke798e7c2009-04-27 19:14:45 +00002881
2882 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002883 case RetEffect::NotOwnedSymbol: {
2884 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002885 ValueManager &ValMgr = Eng.getValueManager();
2886 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2887 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2888 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2889 RetT));
2890 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002891 break;
2892 }
2893 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002894
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002895 // Generate a sink node if we are at the end of a path.
2896 GRExprEngine::NodeTy *NewNode =
Ted Kremenek7faca822009-05-04 04:57:00 +00002897 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2898 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002899
2900 // Annotate the edge with summary we used.
Ted Kremenek7faca822009-05-04 04:57:00 +00002901 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002902}
2903
2904
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002905void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002906 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002907 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002908 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002909 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00002910 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek7faca822009-05-04 04:57:00 +00002911 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xu369f4472009-04-20 05:24:46 +00002912 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002913
Ted Kremenek7faca822009-05-04 04:57:00 +00002914 assert(Summ);
2915 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002916 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002917}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002918
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002919void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00002920 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002921 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00002922 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002923 ExplodedNode<GRState>* Pred) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002924 RetainSummary* Summ = 0;
Ted Kremenek9040c652008-05-01 21:31:50 +00002925
Ted Kremenek553cf182008-06-25 21:21:56 +00002926 if (Expr* Receiver = ME->getReceiver()) {
2927 // We need the type-information of the tracked receiver object
2928 // Retrieve it from the state.
2929 ObjCInterfaceDecl* ID = 0;
2930
2931 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2932 // a chain of lookups.
Ted Kremenek8711c032009-04-29 05:04:30 +00002933 // FIXME: Is this really working as expected? There are cases where
2934 // we just use the 'ID' from the message expression.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002935 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002936 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00002937
Ted Kremenek94c96982009-03-03 22:06:47 +00002938 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002939 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002940 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002941 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002942
2943 if (const PointerType* PT = Ty->getAsPointerType()) {
2944 QualType PointeeTy = PT->getPointeeType();
2945
2946 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2947 ID = IT->getDecl();
2948 }
2949 }
2950 }
2951
Ted Kremenekce8a41d2009-04-29 17:09:14 +00002952 // FIXME: The receiver could be a reference to a class, meaning that
2953 // we should use the class method.
2954 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002955
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002956 // Special-case: are we sending a mesage to "self"?
2957 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek885c27b2009-05-04 05:31:22 +00002958 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2959 if (Expr* Receiver = ME->getReceiver()) {
2960 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2961 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2962 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2963 // Update the summary to make the default argument effect
2964 // 'StopTracking'.
2965 Summ = Summaries.copySummary(Summ);
2966 Summ->setDefaultArgEffect(StopTracking);
2967 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002968 }
2969 }
Ted Kremenek553cf182008-06-25 21:21:56 +00002970 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002971 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00002972 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002973
Ted Kremenek7faca822009-05-04 04:57:00 +00002974 if (!Summ)
2975 Summ = Summaries.getDefaultSummary();
Ted Kremenekde4d5332009-04-24 17:50:11 +00002976
Ted Kremenek7faca822009-05-04 04:57:00 +00002977 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenekb3095252008-05-06 04:20:12 +00002978 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00002979}
Ted Kremenek5216ad72009-02-14 03:16:10 +00002980
2981namespace {
2982class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2983 GRStateRef state;
2984public:
2985 StopTrackingCallback(GRStateRef st) : state(st) {}
2986 GRStateRef getState() { return state; }
2987
2988 bool VisitSymbol(SymbolRef sym) {
2989 state = state.remove<RefBindings>(sym);
2990 return true;
2991 }
Ted Kremenekb3095252008-05-06 04:20:12 +00002992
Ted Kremenek5216ad72009-02-14 03:16:10 +00002993 const GRState* getState() const { return state.getState(); }
2994};
2995} // end anonymous namespace
2996
2997
Ted Kremenek41573eb2009-02-14 01:43:44 +00002998void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002999 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00003000 bool escapes = false;
3001
Ted Kremeneka496d162008-10-18 03:49:51 +00003002 // A value escapes in three possible cases (this may change):
3003 //
3004 // (1) we are binding to something that is not a memory region.
3005 // (2) we are binding to a memregion that does not have stack storage
3006 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00003007 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00003008 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00003009
Ted Kremenek41573eb2009-02-14 01:43:44 +00003010 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00003011 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00003012 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00003013 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3014 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00003015
3016 if (!escapes) {
3017 // To test (3), generate a new state with the binding removed. If it is
3018 // the same state, then it escapes (since the store cannot represent
3019 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00003020 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00003021 }
Ted Kremenek9e240492008-10-04 05:50:14 +00003022 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00003023
Ted Kremenek5216ad72009-02-14 03:16:10 +00003024 // If our store can represent the binding and we aren't storing to something
3025 // that doesn't have local storage then just return and have the simulation
3026 // state continue as is.
3027 if (!escapes)
3028 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00003029
Ted Kremenek5216ad72009-02-14 03:16:10 +00003030 // Otherwise, find all symbols referenced by 'val' that we are tracking
3031 // and stop tracking them.
3032 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00003033}
3034
Ted Kremenek652adc62008-04-24 23:57:27 +00003035
Ted Kremenek4fd88972008-04-17 18:12:53 +00003036 // Return statements.
3037
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003038void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00003039 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003040 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00003041 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003042 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003043
3044 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00003045 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00003046 return;
3047
Ted Kremenek94c96982009-03-03 22:06:47 +00003048 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00003049 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00003050
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00003051 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00003052 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003053
Ted Kremenek4fd88972008-04-17 18:12:53 +00003054 // Get the reference count binding (if any).
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003055 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00003056
3057 if (!T)
3058 return;
3059
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003060 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00003061 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003062
Ted Kremenek78a35a32009-05-12 20:06:54 +00003063 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003064 case RefVal::Owned: {
3065 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003066 assert (cnt > 0);
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003067 X.setCount(cnt - 1);
3068 X = X ^ RefVal::ReturnedOwned;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003069 break;
3070 }
3071
3072 case RefVal::NotOwned: {
3073 unsigned cnt = X.getCount();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003074 if (cnt) {
3075 X.setCount(cnt - 1);
3076 X = X ^ RefVal::ReturnedOwned;
3077 }
3078 else {
3079 X = X ^ RefVal::ReturnedNotOwned;
3080 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003081 break;
3082 }
3083
3084 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00003085 return;
3086 }
3087
3088 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003089 state = state.set<RefBindings>(Sym, X);
Ted Kremenekc887d132009-04-29 18:50:19 +00003090 Pred = Builder.MakeNode(Dst, S, Pred, state);
3091
Ted Kremenek9f246b62009-04-30 05:51:50 +00003092 // Did we cache out?
3093 if (!Pred)
3094 return;
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003095
3096 // Update the autorelease counts.
3097 static unsigned autoreleasetag = 0;
3098 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3099 bool stop = false;
3100 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3101 X, stop);
3102
3103 // Did we cache out?
3104 if (!Pred || stop)
3105 return;
3106
3107 // Get the updated binding.
3108 T = state.get<RefBindings>(Sym);
3109 assert(T);
3110 X = *T;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003111
Ted Kremenekc887d132009-04-29 18:50:19 +00003112 // Any leaks or other errors?
3113 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003114 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremeneka8833552009-04-29 23:03:22 +00003115 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00003116 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003117 RetEffect RE = Summ.getRetEffect();
3118 bool hasError = false;
3119
3120 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3121 // Things are more complicated with garbage collection. If the
3122 // returned object is suppose to be an Objective-C object, we have
Ted Kremenek82f2be52009-05-10 16:52:15 +00003123 // a leak (as the caller expects a GC'ed object) because no
3124 // method should return ownership unless it returns a CF object.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003125 X = X ^ RefVal::ErrorGCLeakReturned;
3126
3127 // Keep this false until this is properly tested.
Ted Kremenek82f2be52009-05-10 16:52:15 +00003128 hasError = true;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003129 }
3130 else if (!RE.isOwned()) {
3131 // Either we are using GC and the returned object is a CF type
3132 // or we aren't using GC. In either case, we expect that the
3133 // enclosing method is expected to return ownership.
3134 hasError = true;
3135 X = X ^ RefVal::ErrorLeakReturned;
3136 }
3137
3138 if (hasError) {
Ted Kremenekc887d132009-04-29 18:50:19 +00003139 // Generate an error node.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003140 static int ReturnOwnLeakTag = 0;
3141 state = state.set<RefBindings>(Sym, X);
3142 ExplodedNode<GRState> *N =
3143 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3144 if (N) {
3145 CFRefReport *report =
Ted Kremenek9f246b62009-04-30 05:51:50 +00003146 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3147 N, Sym, Eng);
3148 BR->EmitReport(report);
3149 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003150 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003151 }
3152 }
3153 else if (X.isReturnedNotOwned()) {
3154 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3155 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3156 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3157 if (Summ.getRetEffect().isOwned()) {
3158 // Trying to return a not owned object to a caller expecting an
3159 // owned object.
3160
3161 static int ReturnNotOwnedForOwnedTag = 0;
3162 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3163 if (ExplodedNode<GRState> *N =
3164 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3165 state, Pred)) {
3166 CFRefReport *report =
3167 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3168 *this, N, Sym);
3169 BR->EmitReport(report);
3170 }
3171 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003172 }
3173 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003174}
3175
Ted Kremenekcb612922008-04-18 19:23:43 +00003176// Assumptions.
3177
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003178const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3179 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00003180 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00003181 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003182
3183 // FIXME: We may add to the interface of EvalAssume the list of symbols
3184 // whose assumptions have changed. For now we just iterate through the
3185 // bindings and check if any of the tracked symbols are NULL. This isn't
3186 // too bad since the number of symbols we will track in practice are
3187 // probably small and EvalAssume is only called at branches and a few
3188 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003189 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003190
3191 if (B.isEmpty())
3192 return St;
3193
3194 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003195
3196 GRStateRef state(St, VMgr);
3197 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003198
3199 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003200 // Check if the symbol is null (or equal to any constant).
3201 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00003202 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003203 changed = true;
3204 B = RefBFactory.Remove(B, I.getKey());
3205 }
3206 }
3207
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003208 if (changed)
3209 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00003210
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003211 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003212}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003213
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003214GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3215 RefVal V, ArgEffect E,
3216 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00003217
3218 // In GC mode [... release] and [... retain] do nothing.
3219 switch (E) {
3220 default: break;
3221 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3222 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00003223 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00003224 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3225 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003226 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003227
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003228 // Handle all use-after-releases.
3229 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3230 V = V ^ RefVal::ErrorUseAfterRelease;
3231 hasErr = V.getKind();
3232 return state.set<RefBindings>(sym, V);
3233 }
3234
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003235 switch (E) {
3236 default:
3237 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003238
3239 case Dealloc:
3240 // Any use of -dealloc in GC is *bad*.
3241 if (isGCEnabled()) {
3242 V = V ^ RefVal::ErrorDeallocGC;
3243 hasErr = V.getKind();
3244 break;
3245 }
3246
3247 switch (V.getKind()) {
3248 default:
3249 assert(false && "Invalid case.");
3250 case RefVal::Owned:
3251 // The object immediately transitions to the released state.
3252 V = V ^ RefVal::Released;
3253 V.clearCounts();
3254 return state.set<RefBindings>(sym, V);
3255 case RefVal::NotOwned:
3256 V = V ^ RefVal::ErrorDeallocNotOwned;
3257 hasErr = V.getKind();
3258 break;
3259 }
3260 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003261
Ted Kremenek35790732009-02-25 23:11:49 +00003262 case NewAutoreleasePool:
3263 assert(!isGCEnabled());
3264 return state.add<AutoreleaseStack>(sym);
3265
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003266 case MayEscape:
3267 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00003268 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003269 break;
3270 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003271
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003272 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00003273
Ted Kremenek070a8252008-07-09 18:11:16 +00003274 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003275 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003276 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00003277
Ted Kremenekabf43972009-01-28 21:44:40 +00003278 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003279 if (isGCEnabled())
3280 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00003281
3282 // Update the autorelease counts.
3283 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf21332e2009-05-08 20:01:42 +00003284 V = V.autorelease();
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003285 break;
Ted Kremenek369de562009-05-09 00:10:05 +00003286
Ted Kremenek14993892008-05-06 02:41:27 +00003287 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003288 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003289
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003290 case IncRef:
3291 switch (V.getKind()) {
3292 default:
3293 assert(false);
3294
3295 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003296 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00003297 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003298 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003299 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003300 // Non-GC cases are handled above.
3301 assert(isGCEnabled());
3302 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003303 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003304 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003305 break;
3306
Ted Kremenek553cf182008-06-25 21:21:56 +00003307 case SelfOwn:
3308 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003309 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003310 case DecRef:
3311 switch (V.getKind()) {
3312 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003313 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003314 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003315
Ted Kremenek553cf182008-06-25 21:21:56 +00003316 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00003317 assert(V.getCount() > 0);
3318 if (V.getCount() == 1) V = V ^ RefVal::Released;
3319 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003320 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003321
Ted Kremenek553cf182008-06-25 21:21:56 +00003322 case RefVal::NotOwned:
3323 if (V.getCount() > 0)
3324 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00003325 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00003326 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003327 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00003328 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003329 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003330
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003331 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003332 // Non-GC cases are handled above.
3333 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00003334 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003335 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003336 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003337 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003338 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003339 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003340 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003341}
3342
Ted Kremenekfa34b332008-04-09 01:10:13 +00003343//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003344// Handle dead symbols and end-of-path.
3345//===----------------------------------------------------------------------===//
3346
Ted Kremenekf04dced2009-05-08 23:32:51 +00003347std::pair<ExplodedNode<GRState>*, GRStateRef>
3348CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3349 ExplodedNode<GRState>* Pred,
Ted Kremenek369de562009-05-09 00:10:05 +00003350 GRExprEngine &Eng,
3351 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekf04dced2009-05-08 23:32:51 +00003352
Ted Kremenek369de562009-05-09 00:10:05 +00003353 unsigned ACnt = V.getAutoreleaseCount();
3354 stop = false;
3355
3356 // No autorelease counts? Nothing to be done.
3357 if (!ACnt)
3358 return std::make_pair(Pred, state);
3359
3360 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3361 unsigned Cnt = V.getCount();
3362
Ted Kremenek95d3b902009-05-11 15:26:06 +00003363 // FIXME: Handle sending 'autorelease' to already released object.
3364
3365 if (V.getKind() == RefVal::ReturnedOwned)
3366 ++Cnt;
3367
Ted Kremenek369de562009-05-09 00:10:05 +00003368 if (ACnt <= Cnt) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003369 if (ACnt == Cnt) {
3370 V.clearCounts();
Ted Kremenek95d3b902009-05-11 15:26:06 +00003371 if (V.getKind() == RefVal::ReturnedOwned)
3372 V = V ^ RefVal::ReturnedNotOwned;
3373 else
3374 V = V ^ RefVal::NotOwned;
Ted Kremenek80c24182009-05-09 00:44:07 +00003375 }
Ted Kremenek95d3b902009-05-11 15:26:06 +00003376 else {
Ted Kremenek80c24182009-05-09 00:44:07 +00003377 V.setCount(Cnt - ACnt);
3378 V.setAutoreleaseCount(0);
3379 }
Ted Kremenek369de562009-05-09 00:10:05 +00003380 state = state.set<RefBindings>(Sym, V);
3381 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3382 stop = (N == 0);
3383 return std::make_pair(N, state);
3384 }
3385
3386 // Woah! More autorelease counts then retain counts left.
3387 // Emit hard error.
3388 stop = true;
3389 V = V ^ RefVal::ErrorOverAutorelease;
3390 state = state.set<RefBindings>(Sym, V);
3391
3392 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003393 N->markAsSink();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003394
3395 std::string sbuf;
3396 llvm::raw_string_ostream os(sbuf);
3397 os << "Object over-autoreleased: object was sent -autorelease " ;
3398 if (V.getAutoreleaseCount() > 1)
3399 os << V.getAutoreleaseCount() << " times";
3400 os << " but the object has ";
3401 if (V.getCount() == 0)
3402 os << "zero (locally visible)";
3403 else
3404 os << "+" << V.getCount();
3405 os << " retain counts";
3406
Ted Kremenek369de562009-05-09 00:10:05 +00003407 CFRefReport *report =
3408 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003409 *this, N, Sym, os.str().c_str());
Ted Kremenek369de562009-05-09 00:10:05 +00003410 BR->EmitReport(report);
3411 }
3412
3413 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekf04dced2009-05-08 23:32:51 +00003414}
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003415
3416GRStateRef
3417CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3418 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3419
3420 bool hasLeak = V.isOwned() ||
3421 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3422
3423 if (!hasLeak)
3424 return state.remove<RefBindings>(sid);
3425
3426 Leaked.push_back(sid);
3427 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3428}
3429
3430ExplodedNode<GRState>*
3431CFRefCount::ProcessLeaks(GRStateRef state,
3432 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3433 GenericNodeBuilder &Builder,
3434 GRExprEngine& Eng,
3435 ExplodedNode<GRState> *Pred) {
3436
3437 if (Leaked.empty())
3438 return Pred;
3439
Ted Kremenekf04dced2009-05-08 23:32:51 +00003440 // Generate an intermediate node representing the leak point.
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003441 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003442
3443 if (N) {
3444 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3445 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3446
3447 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3448 : leakAtReturn);
3449 assert(BT && "BugType not initialized.");
3450 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3451 BR->EmitReport(report);
3452 }
3453 }
3454
3455 return N;
3456}
3457
Ted Kremenekcf701772009-02-05 06:50:21 +00003458void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3459 GREndPathNodeBuilder<GRState>& Builder) {
3460
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003461 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003462 GenericNodeBuilder Bd(Builder);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003463 RefBindings B = state.get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003464 ExplodedNode<GRState> *Pred = 0;
3465
3466 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek369de562009-05-09 00:10:05 +00003467 bool stop = false;
3468 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3469 (*I).first,
3470 (*I).second, stop);
3471
3472 if (stop)
3473 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003474 }
3475
3476 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003477 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003478
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003479 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3480 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3481
Ted Kremenekf04dced2009-05-08 23:32:51 +00003482 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003483}
3484
3485void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3486 GRExprEngine& Eng,
3487 GRStmtNodeBuilder<GRState>& Builder,
3488 ExplodedNode<GRState>* Pred,
3489 Stmt* S,
3490 const GRState* St,
3491 SymbolReaper& SymReaper) {
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003492
3493 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003494 RefBindings B = state.get<RefBindings>();
3495
3496 // Update counts from autorelease pools
3497 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3498 E = SymReaper.dead_end(); I != E; ++I) {
3499 SymbolRef Sym = *I;
3500 if (const RefVal* T = B.lookup(Sym)){
3501 // Use the symbol as the tag.
3502 // FIXME: This might not be as unique as we would like.
3503 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek369de562009-05-09 00:10:05 +00003504 bool stop = false;
3505 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3506 Sym, *T, stop);
3507 if (stop)
3508 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003509 }
3510 }
3511
3512 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003513 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003514
3515 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003516 E = SymReaper.dead_end(); I != E; ++I) {
3517 if (const RefVal* T = B.lookup(*I))
3518 state = HandleSymbolDeath(state, *I, *T, Leaked);
3519 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003520
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003521 static unsigned LeakPPTag = 0;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003522 {
3523 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3524 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3525 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003526
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003527 // Did we cache out?
3528 if (!Pred)
3529 return;
Ted Kremenek33b6f632009-02-19 23:47:02 +00003530
3531 // Now generate a new node that nukes the old bindings.
Ted Kremenek33b6f632009-02-19 23:47:02 +00003532 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003533
Ted Kremenek33b6f632009-02-19 23:47:02 +00003534 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003535 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3536
Ted Kremenek33b6f632009-02-19 23:47:02 +00003537 state = state.set<RefBindings>(B);
3538 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003539}
3540
3541void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3542 GRStmtNodeBuilder<GRState>& Builder,
3543 Expr* NodeExpr, Expr* ErrorExpr,
3544 ExplodedNode<GRState>* Pred,
3545 const GRState* St,
3546 RefVal::Kind hasErr, SymbolRef Sym) {
3547 Builder.BuildSinks = true;
3548 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3549
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003550 if (!N)
3551 return;
Ted Kremenekcf701772009-02-05 06:50:21 +00003552
3553 CFRefBug *BT = 0;
3554
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003555 switch (hasErr) {
3556 default:
3557 assert(false && "Unhandled error.");
3558 return;
3559 case RefVal::ErrorUseAfterRelease:
3560 BT = static_cast<CFRefBug*>(useAfterRelease);
3561 break;
3562 case RefVal::ErrorReleaseNotOwned:
3563 BT = static_cast<CFRefBug*>(releaseNotOwned);
3564 break;
3565 case RefVal::ErrorDeallocGC:
3566 BT = static_cast<CFRefBug*>(deallocGC);
3567 break;
3568 case RefVal::ErrorDeallocNotOwned:
3569 BT = static_cast<CFRefBug*>(deallocNotOwned);
3570 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003571 }
3572
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003573 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003574 report->addRange(ErrorExpr->getSourceRange());
3575 BR->EmitReport(report);
3576}
3577
3578//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003579// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003580//===----------------------------------------------------------------------===//
3581
Ted Kremenek072192b2008-04-30 23:47:44 +00003582GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3583 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003584 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003585}