blob: 23482ca4afd04446be417700935aa3bfa867dbc9 [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 Kremenek072192b2008-04-30 23:47:44 +000015#include "clang/Basic/LangOptions.h"
Ted Kremenekc9fa2f72008-05-01 23:13:35 +000016#include "clang/Basic/SourceManager.h"
Ted Kremenek41573eb2009-02-14 01:43:44 +000017#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenekb9d17f92008-08-17 03:20:02 +000018#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenek4dc41cc2008-03-31 18:26:32 +000019#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000020#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek5216ad72009-02-14 03:16:10 +000023#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenek6c07bdb2009-06-26 00:05:51 +000024#include "clang/Analysis/PathSensitive/GRTransferFuncs.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 Kremenek98530452008-08-12 20:41:56 +000033#include <stdarg.h>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000034
35using namespace clang;
Ted Kremenek5c74d502008-10-24 21:18:08 +000036
37//===----------------------------------------------------------------------===//
38// Utility functions.
39//===----------------------------------------------------------------------===//
40
Ted Kremenek5c74d502008-10-24 21:18:08 +000041// The "fundamental rule" for naming conventions of methods:
42// (url broken into two lines)
43// http://developer.apple.com/documentation/Cocoa/Conceptual/
44// MemoryMgmt/Tasks/MemoryManagementRules.html
45//
46// "You take ownership of an object if you create it using a method whose name
Eli Friedman33a31382009-08-05 19:21:58 +000047// begins with "alloc" or "new" or contains "copy" (for example, alloc,
Ted Kremenek5c74d502008-10-24 21:18:08 +000048// newObject, or mutableCopy), or if you send it a retain message. You are
49// responsible for relinquishing ownership of objects you own using release
50// or autorelease. Any other time you receive an object, you must
51// not release it."
52//
Ted Kremenekb80976c2009-02-21 05:13:43 +000053
54using llvm::CStrInCStrNoCase;
Ted Kremenek39868cd2009-02-21 18:26:02 +000055using llvm::StringsEqualNoCase;
Ted Kremenekb80976c2009-02-21 05:13:43 +000056
57enum NamingConvention { NoConvention, CreateRule, InitRule };
58
59static inline bool isWordEnd(char ch, char prev, char next) {
60 return ch == '\0'
61 || (islower(prev) && isupper(ch)) // xxxC
62 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
63 || !isalpha(ch);
64}
65
66static inline const char* parseWord(const char* s) {
67 char ch = *s, prev = '\0';
68 assert(ch != '\0');
69 char next = *(s+1);
70 while (!isWordEnd(ch, prev, next)) {
71 prev = ch;
72 ch = next;
73 next = *((++s)+1);
74 }
75 return s;
76}
77
Ted Kremenek7db16042009-05-15 15:49:00 +000078static NamingConvention deriveNamingConvention(Selector S) {
79 IdentifierInfo *II = S.getIdentifierInfoForSlot(0);
80
81 if (!II)
82 return NoConvention;
83
84 const char *s = II->getName();
85
Ted Kremenekb80976c2009-02-21 05:13:43 +000086 // A method/function name may contain a prefix. We don't know it is there,
87 // however, until we encounter the first '_'.
88 bool InPossiblePrefix = true;
89 bool AtBeginning = true;
90 NamingConvention C = NoConvention;
91
92 while (*s != '\0') {
93 // Skip '_'.
94 if (*s == '_') {
95 if (InPossiblePrefix) {
96 InPossiblePrefix = false;
97 AtBeginning = true;
98 // Discard whatever 'convention' we
99 // had already derived since it occurs
100 // in the prefix.
101 C = NoConvention;
102 }
103 ++s;
104 continue;
105 }
106
107 // Skip numbers, ':', etc.
108 if (!isalpha(*s)) {
109 ++s;
110 continue;
111 }
112
113 const char *wordEnd = parseWord(s);
114 assert(wordEnd > s);
115 unsigned len = wordEnd - s;
116
117 switch (len) {
118 default:
119 break;
120 case 3:
121 // Methods starting with 'new' follow the create rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000122 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000123 C = CreateRule;
124 break;
125 case 4:
126 // Methods starting with 'alloc' or contain 'copy' follow the
127 // create rule
Ted Kremenek8be2a672009-03-13 20:27:06 +0000128 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000129 C = CreateRule;
130 else // Methods starting with 'init' follow the init rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000131 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek8be2a672009-03-13 20:27:06 +0000132 C = InitRule;
133 break;
134 case 5:
135 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
136 C = CreateRule;
Ted Kremenekb80976c2009-02-21 05:13:43 +0000137 break;
138 }
139
140 // If we aren't in the prefix and have a derived convention then just
141 // return it now.
142 if (!InPossiblePrefix && C != NoConvention)
143 return C;
144
145 AtBeginning = false;
146 s = wordEnd;
147 }
148
149 // We will get here if there wasn't more than one word
150 // after the prefix.
151 return C;
152}
153
Ted Kremenek7db16042009-05-15 15:49:00 +0000154static bool followsFundamentalRule(Selector S) {
155 return deriveNamingConvention(S) == CreateRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000156}
157
Ted Kremeneka8833552009-04-29 23:03:22 +0000158static const ObjCMethodDecl*
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000159ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000160 ObjCInterfaceDecl *ID =
161 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
162
163 return MD->isInstanceMethod()
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000164 ? ID->lookupInstanceMethod(MD->getSelector())
165 : ID->lookupClassMethod(MD->getSelector());
Ted Kremenek4c79e552008-11-05 16:54:44 +0000166}
Ted Kremenek5c74d502008-10-24 21:18:08 +0000167
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000168namespace {
169class VISIBILITY_HIDDEN GenericNodeBuilder {
170 GRStmtNodeBuilder<GRState> *SNB;
171 Stmt *S;
172 const void *tag;
173 GREndPathNodeBuilder<GRState> *ENB;
174public:
175 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
176 const void *t)
177 : SNB(&snb), S(s), tag(t), ENB(0) {}
178 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
179 : SNB(0), S(0), tag(0), ENB(&enb) {}
180
181 ExplodedNode<GRState> *MakeNode(const GRState *state,
182 ExplodedNode<GRState> *Pred) {
183 if (SNB)
Ted Kremenek6b62ec92009-05-09 01:50:57 +0000184 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000185
186 assert(ENB);
Ted Kremenek80c24182009-05-09 00:44:07 +0000187 return ENB->generateNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000188 }
189};
190} // end anonymous namespace
191
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000192//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000193// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000194//===----------------------------------------------------------------------===//
195
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000196static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000197 IdentifierInfo* II = &Ctx.Idents.get(name);
198 return Ctx.Selectors.getSelector(0, &II);
199}
200
Ted Kremenek9c32d082008-05-06 00:30:21 +0000201static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
202 IdentifierInfo* II = &Ctx.Idents.get(name);
203 return Ctx.Selectors.getSelector(1, &II);
204}
205
Ted Kremenek553cf182008-06-25 21:21:56 +0000206//===----------------------------------------------------------------------===//
207// Type querying functions.
208//===----------------------------------------------------------------------===//
209
Ted Kremenek12619382009-01-12 21:45:02 +0000210static bool hasPrefix(const char* s, const char* prefix) {
211 if (!prefix)
212 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000213
Ted Kremenek12619382009-01-12 21:45:02 +0000214 char c = *s;
215 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000216
Ted Kremenek12619382009-01-12 21:45:02 +0000217 while (c != '\0' && cP != '\0') {
218 if (c != cP) break;
219 c = *(++s);
220 cP = *(++prefix);
221 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000222
Ted Kremenek12619382009-01-12 21:45:02 +0000223 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000224}
225
Ted Kremenek12619382009-01-12 21:45:02 +0000226static bool hasSuffix(const char* s, const char* suffix) {
227 const char* loc = strstr(s, suffix);
228 return loc && strcmp(suffix, loc) == 0;
229}
230
231static bool isRefType(QualType RetTy, const char* prefix,
232 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek37d785b2008-07-15 16:50:12 +0000233
Ted Kremenek6738b732009-05-12 04:53:03 +0000234 // Recursively walk the typedef stack, allowing typedefs of reference types.
235 while (1) {
236 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
237 const char* TDName = TD->getDecl()->getIdentifier()->getName();
238 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
239 return true;
240
241 RetTy = TD->getDecl()->getUnderlyingType();
242 continue;
243 }
244 break;
Ted Kremenek12619382009-01-12 21:45:02 +0000245 }
246
247 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000248 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000249
250 // Is the type void*?
Ted Kremenek6217b802009-07-29 21:53:49 +0000251 const PointerType* PT = RetTy->getAs<PointerType>();
Ted Kremenek12619382009-01-12 21:45:02 +0000252 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000253 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000254
255 // Does the name start with the prefix?
256 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000257}
258
Ted Kremenek4fd88972008-04-17 18:12:53 +0000259//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000260// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000261//===----------------------------------------------------------------------===//
262
Ted Kremenek553cf182008-06-25 21:21:56 +0000263/// ArgEffect is used to summarize a function/method call's effect on a
264/// particular argument.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +0000265enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
266 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
267 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +0000268
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000269namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000270template <> struct FoldingSetTrait<ArgEffect> {
271static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
272 ID.AddInteger((unsigned) X);
273}
Ted Kremenek553cf182008-06-25 21:21:56 +0000274};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000275} // end llvm namespace
276
Ted Kremenekb77449c2009-05-03 05:20:50 +0000277/// ArgEffects summarizes the effects of a function/method call on all of
278/// its arguments.
279typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
280
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000281namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000282
283/// RetEffect is used to summarize a function/method call's behavior with
284/// respect to its return value.
285class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000286public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000287 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +0000288 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
289 OwnedWhenTrackedReceiver };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000290
291 enum ObjKind { CF, ObjC, AnyObj };
292
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000293private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000294 Kind K;
295 ObjKind O;
296 unsigned index;
297
298 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
299 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000300
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000301public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000302 Kind getKind() const { return K; }
303
304 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000305
306 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000307 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000308 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000309 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000310
Ted Kremeneka8833552009-04-29 23:03:22 +0000311 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000312 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
313 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000314 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +0000315
Ted Kremenek78a35a32009-05-12 20:06:54 +0000316 static RetEffect MakeOwnedWhenTrackedReceiver() {
317 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
318 }
319
Ted Kremenek553cf182008-06-25 21:21:56 +0000320 static RetEffect MakeAlias(unsigned Idx) {
321 return RetEffect(Alias, Idx);
322 }
323 static RetEffect MakeReceiverAlias() {
324 return RetEffect(ReceiverAlias);
325 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000326 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
327 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000328 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000329 static RetEffect MakeNotOwned(ObjKind o) {
330 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000331 }
332 static RetEffect MakeGCNotOwned() {
333 return RetEffect(GCNotOwnedSymbol, ObjC);
334 }
335
Ted Kremenek553cf182008-06-25 21:21:56 +0000336 static RetEffect MakeNoRet() {
337 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000338 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000339
Ted Kremenek553cf182008-06-25 21:21:56 +0000340 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000341 ID.AddInteger((unsigned)K);
342 ID.AddInteger((unsigned)O);
343 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000344 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000345};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000346
Ted Kremenek553cf182008-06-25 21:21:56 +0000347
Ted Kremenek885c27b2009-05-04 05:31:22 +0000348class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000349 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
350 /// specifies the argument (starting from 0). This can be sparsely
351 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000352 ArgEffects Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000353
354 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
355 /// do not have an entry in Args.
356 ArgEffect DefaultArgEffect;
357
Ted Kremenek553cf182008-06-25 21:21:56 +0000358 /// Receiver - If this summary applies to an Objective-C message expression,
359 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000360 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000361
362 /// Ret - The effect on the return value. Used to indicate if the
363 /// function/method call returns a new tracked symbol, returns an
364 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000365 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000366
Ted Kremenek70a733e2008-07-18 17:24:20 +0000367 /// EndPath - Indicates that execution of this method/function should
368 /// terminate the simulation of a path.
369 bool EndPath;
370
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000371public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000372 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000373 ArgEffect ReceiverEff, bool endpath = false)
374 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
375 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000376
Ted Kremenek553cf182008-06-25 21:21:56 +0000377 /// getArg - Return the argument effect on the argument specified by
378 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000379 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000380 if (const ArgEffect *AE = Args.lookup(idx))
381 return *AE;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000382
Ted Kremenek1bffd742008-05-06 15:44:25 +0000383 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000384 }
385
Ted Kremenek885c27b2009-05-04 05:31:22 +0000386 /// setDefaultArgEffect - Set the default argument effect.
387 void setDefaultArgEffect(ArgEffect E) {
388 DefaultArgEffect = E;
389 }
390
391 /// setArg - Set the argument effect on the argument specified by idx.
392 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
393 Args = AF.Add(Args, idx, E);
394 }
395
Ted Kremenek553cf182008-06-25 21:21:56 +0000396 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000397 RetEffect getRetEffect() const { return Ret; }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000398
Ted Kremenek885c27b2009-05-04 05:31:22 +0000399 /// setRetEffect - Set the effect of the return value of the call.
400 void setRetEffect(RetEffect E) { Ret = E; }
401
Ted Kremenek70a733e2008-07-18 17:24:20 +0000402 /// isEndPath - Returns true if executing the given method/function should
403 /// terminate the path.
404 bool isEndPath() const { return EndPath; }
405
Ted Kremenek553cf182008-06-25 21:21:56 +0000406 /// getReceiverEffect - Returns the effect on the receiver of the call.
407 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000408 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000409
Ted Kremenek885c27b2009-05-04 05:31:22 +0000410 /// setReceiverEffect - Set the effect on the receiver of the call.
411 void setReceiverEffect(ArgEffect E) { Receiver = E; }
412
Ted Kremenekb77449c2009-05-03 05:20:50 +0000413 typedef ArgEffects::iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000414
Ted Kremenekb77449c2009-05-03 05:20:50 +0000415 ExprIterator begin_args() const { return Args.begin(); }
416 ExprIterator end_args() const { return Args.end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000417
Ted Kremenekb77449c2009-05-03 05:20:50 +0000418 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000419 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000420 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000421 ID.Add(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000422 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000423 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000424 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000425 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000426 }
427
428 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000429 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000430 }
431};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000432} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000433
Ted Kremenek553cf182008-06-25 21:21:56 +0000434//===----------------------------------------------------------------------===//
435// Data structures for constructing summaries.
436//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000437
Ted Kremenek553cf182008-06-25 21:21:56 +0000438namespace {
439class VISIBILITY_HIDDEN ObjCSummaryKey {
440 IdentifierInfo* II;
441 Selector S;
442public:
443 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
444 : II(ii), S(s) {}
445
Ted Kremeneka8833552009-04-29 23:03:22 +0000446 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000447 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000448
449 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
450 : II(d ? d->getIdentifier() : ii), S(s) {}
Ted Kremenek553cf182008-06-25 21:21:56 +0000451
452 ObjCSummaryKey(Selector s)
453 : II(0), S(s) {}
454
455 IdentifierInfo* getIdentifier() const { return II; }
456 Selector getSelector() const { return S; }
457};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000458}
459
460namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000461template <> struct DenseMapInfo<ObjCSummaryKey> {
462 static inline ObjCSummaryKey getEmptyKey() {
463 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
464 DenseMapInfo<Selector>::getEmptyKey());
465 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000466
Ted Kremenek553cf182008-06-25 21:21:56 +0000467 static inline ObjCSummaryKey getTombstoneKey() {
468 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
469 DenseMapInfo<Selector>::getTombstoneKey());
470 }
471
472 static unsigned getHashValue(const ObjCSummaryKey &V) {
473 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
474 & 0x88888888)
475 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
476 & 0x55555555);
477 }
478
479 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
480 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
481 RHS.getIdentifier()) &&
482 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
483 RHS.getSelector());
484 }
485
486 static bool isPod() {
487 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
488 DenseMapInfo<Selector>::isPod();
489 }
490};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000491} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000492
Ted Kremenek4f22a782008-06-23 23:30:29 +0000493namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000494class VISIBILITY_HIDDEN ObjCSummaryCache {
495 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
496 MapTy M;
497public:
498 ObjCSummaryCache() {}
Ted Kremenek614cc542009-07-21 23:27:57 +0000499
500 RetainSummary* find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000501 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000502 // Lookup the method using the decl for the class @interface. If we
503 // have no decl, lookup using the class name.
504 return D ? find(D, S) : find(ClsName, S);
505 }
506
Ted Kremenek614cc542009-07-21 23:27:57 +0000507 RetainSummary* find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000508 // Do a lookup with the (D,S) pair. If we find a match return
509 // the iterator.
510 ObjCSummaryKey K(D, S);
511 MapTy::iterator I = M.find(K);
512
513 if (I != M.end() || !D)
Ted Kremenek614cc542009-07-21 23:27:57 +0000514 return I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000515
516 // Walk the super chain. If we find a hit with a parent, we'll end
517 // up returning that summary. We actually allow that key (null,S), as
518 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
519 // generate initial summaries without having to worry about NSObject
520 // being declared.
521 // FIXME: We may change this at some point.
522 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
523 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
524 break;
525
526 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000527 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000528 }
529
530 // Cache the summary with original key to make the next lookup faster
531 // and return the iterator.
Ted Kremenek614cc542009-07-21 23:27:57 +0000532 RetainSummary *Summ = I->second;
533 M[K] = Summ;
534 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000535 }
536
Ted Kremenek98530452008-08-12 20:41:56 +0000537
Ted Kremenek614cc542009-07-21 23:27:57 +0000538 RetainSummary* find(Expr* Receiver, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000539 return find(getReceiverDecl(Receiver), S);
540 }
541
Ted Kremenek614cc542009-07-21 23:27:57 +0000542 RetainSummary* find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000543 // FIXME: Class method lookup. Right now we dont' have a good way
544 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000545 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
546
547 if (I == M.end())
548 I = M.find(ObjCSummaryKey(S));
549
550 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000551 }
552
Steve Naroff14108da2009-07-10 23:34:53 +0000553 const ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
554 if (const ObjCObjectPointerType* PT =
555 E->getType()->getAsObjCObjectPointerType())
556 return PT->getInterfaceDecl();
557
558 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000559 }
560
Ted Kremenek553cf182008-06-25 21:21:56 +0000561 RetainSummary*& operator[](ObjCMessageExpr* ME) {
562
563 Selector S = ME->getSelector();
564
565 if (Expr* Receiver = ME->getReceiver()) {
Steve Naroff14108da2009-07-10 23:34:53 +0000566 const ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +0000567 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
568 }
569
570 return M[ObjCSummaryKey(ME->getClassName(), S)];
571 }
572
573 RetainSummary*& operator[](ObjCSummaryKey K) {
574 return M[K];
575 }
576
577 RetainSummary*& operator[](Selector S) {
578 return M[ ObjCSummaryKey(S) ];
579 }
580};
581} // end anonymous namespace
582
583//===----------------------------------------------------------------------===//
584// Data structures for managing collections of summaries.
585//===----------------------------------------------------------------------===//
586
587namespace {
588class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000589
590 //==-----------------------------------------------------------------==//
591 // Typedefs.
592 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000593
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000594 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
595 FuncSummariesTy;
596
Ted Kremenek4f22a782008-06-23 23:30:29 +0000597 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000598
599 //==-----------------------------------------------------------------==//
600 // Data.
601 //==-----------------------------------------------------------------==//
602
Ted Kremenek553cf182008-06-25 21:21:56 +0000603 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000604 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000605
Ted Kremenek070a8252008-07-09 18:11:16 +0000606 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
607 /// "CFDictionaryCreate".
608 IdentifierInfo* CFDictionaryCreateII;
609
Ted Kremenek553cf182008-06-25 21:21:56 +0000610 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000611 const bool GCEnabled;
Ted Kremenek22fe2482009-05-04 04:30:18 +0000612
Ted Kremenek553cf182008-06-25 21:21:56 +0000613 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000614 FuncSummariesTy FuncSummaries;
615
Ted Kremenek553cf182008-06-25 21:21:56 +0000616 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
617 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000618 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000619
Ted Kremenek553cf182008-06-25 21:21:56 +0000620 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000621 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000622
Ted Kremenek553cf182008-06-25 21:21:56 +0000623 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
624 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000625 llvm::BumpPtrAllocator BPAlloc;
626
Ted Kremenekb77449c2009-05-03 05:20:50 +0000627 /// AF - A factory for ArgEffects objects.
628 ArgEffects::Factory AF;
629
Ted Kremenek553cf182008-06-25 21:21:56 +0000630 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000631 ArgEffects ScratchArgs;
632
Ted Kremenekec315332009-05-07 23:40:42 +0000633 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
634 /// objects.
635 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000636
Ted Kremenekb04cb592009-06-11 18:17:24 +0000637 /// ObjCInitRetE - Default return effect for init methods returning Objective-C
Ted Kremenek547d4952009-06-05 23:18:01 +0000638 /// objects.
639 RetEffect ObjCInitRetE;
Ted Kremenekb04cb592009-06-11 18:17:24 +0000640
Ted Kremenek7faca822009-05-04 04:57:00 +0000641 RetainSummary DefaultSummary;
Ted Kremenek432af592008-05-06 18:11:36 +0000642 RetainSummary* StopSummary;
643
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000644 //==-----------------------------------------------------------------==//
645 // Methods.
646 //==-----------------------------------------------------------------==//
647
Ted Kremenek553cf182008-06-25 21:21:56 +0000648 /// getArgEffects - Returns a persistent ArgEffects object based on the
649 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000650 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000651
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000652 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000653
654public:
Ted Kremenek78a35a32009-05-12 20:06:54 +0000655 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
656
Ted Kremenek885c27b2009-05-04 05:31:22 +0000657 RetainSummary *getDefaultSummary() {
658 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
659 return new (Summ) RetainSummary(DefaultSummary);
660 }
Ted Kremenek7faca822009-05-04 04:57:00 +0000661
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000662 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000663
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000664 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
665 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000666 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000667
Ted Kremenekb77449c2009-05-03 05:20:50 +0000668 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000669 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000670 ArgEffect DefaultEff = MayEscape,
671 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000672
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000673 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000674 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000675 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000676 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000677 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000678
Ted Kremenek8711c032009-04-29 05:04:30 +0000679 RetainSummary *getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000680 if (StopSummary)
681 return StopSummary;
682
683 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
684 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000685
Ted Kremenek432af592008-05-06 18:11:36 +0000686 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000687 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000688
Ted Kremenek8711c032009-04-29 05:04:30 +0000689 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000690
Ted Kremenek1f180c32008-06-23 22:21:20 +0000691 void InitializeClassMethodSummaries();
692 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000693
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000694 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek92511432009-05-03 06:08:32 +0000695 bool isTrackedCFObjectType(QualType T);
Ted Kremenek234a4c22009-01-07 00:39:56 +0000696
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000697private:
698
Ted Kremenek70a733e2008-07-18 17:24:20 +0000699 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
700 RetainSummary* Summ) {
701 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
702 }
703
Ted Kremenek553cf182008-06-25 21:21:56 +0000704 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
705 ObjCClassMethodSummaries[S] = Summ;
706 }
707
708 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
709 ObjCMethodSummaries[S] = Summ;
710 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000711
712 void addClassMethSummary(const char* Cls, const char* nullaryName,
713 RetainSummary *Summ) {
714 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
715 Selector S = GetNullarySelector(nullaryName, Ctx);
716 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
717 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000718
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000719 void addInstMethSummary(const char* Cls, const char* nullaryName,
720 RetainSummary *Summ) {
721 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
722 Selector S = GetNullarySelector(nullaryName, Ctx);
723 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
724 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000725
726 Selector generateSelector(va_list argp) {
Ted Kremenek9e476de2008-08-12 18:30:56 +0000727 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000728
Ted Kremenek9e476de2008-08-12 18:30:56 +0000729 while (const char* s = va_arg(argp, const char*))
730 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000731
732 return Ctx.Selectors.getSelector(II.size(), &II[0]);
733 }
734
735 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
736 RetainSummary* Summ, va_list argp) {
737 Selector S = generateSelector(argp);
738 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000739 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000740
741 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
742 va_list argp;
743 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000744 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000745 va_end(argp);
746 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000747
748 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
749 va_list argp;
750 va_start(argp, Summ);
751 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
752 va_end(argp);
753 }
754
755 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
756 va_list argp;
757 va_start(argp, Summ);
758 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
759 va_end(argp);
760 }
761
Ted Kremenek9e476de2008-08-12 18:30:56 +0000762 void addPanicSummary(const char* Cls, ...) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000763 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
764 RetEffect::MakeNoRet(),
Ted Kremenek9e476de2008-08-12 18:30:56 +0000765 DoNothing, DoNothing, true);
766 va_list argp;
767 va_start (argp, Cls);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000768 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000769 va_end(argp);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000770 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000771
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000772public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000773
774 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000775 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000776 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000777 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenekec315332009-05-07 23:40:42 +0000778 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
779 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenekb04cb592009-06-11 18:17:24 +0000780 ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned()
781 : RetEffect::MakeOwnedWhenTrackedReceiver()),
Ted Kremenek7faca822009-05-04 04:57:00 +0000782 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
783 RetEffect::MakeNoRet() /* return effect */,
Ted Kremenekebd5a2d2009-05-11 18:30:24 +0000784 MayEscape, /* default argument effect */
785 DoNothing /* receiver effect */),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000786 StopSummary(0) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000787
788 InitializeClassMethodSummaries();
789 InitializeMethodSummaries();
790 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000791
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000792 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000793
Ted Kremenekab592272008-06-24 03:56:45 +0000794 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek8711c032009-04-29 05:04:30 +0000795
Ted Kremeneka8833552009-04-29 23:03:22 +0000796 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
797 const ObjCInterfaceDecl* ID) {
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000798 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremenek8711c032009-04-29 05:04:30 +0000799 ID, ME->getMethodDecl(), ME->getType());
800 }
801
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000802 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000803 const ObjCInterfaceDecl* ID,
804 const ObjCMethodDecl *MD,
805 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000806
807 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000808 const ObjCInterfaceDecl *ID,
809 const ObjCMethodDecl *MD,
810 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000811
812 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
813 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
814 ME->getClassInfo().first,
815 ME->getMethodDecl(), ME->getType());
816 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000817
818 /// getMethodSummary - This version of getMethodSummary is used to query
819 /// the summary for the current method being analyzed.
Ted Kremeneka8833552009-04-29 23:03:22 +0000820 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
821 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000822 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000823 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000824 IdentifierInfo *ClsName = ID->getIdentifier();
825 QualType ResultTy = MD->getResultType();
826
Ted Kremenek76a50e32009-04-30 05:47:23 +0000827 // Resolve the method decl last.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000828 if (const ObjCMethodDecl *InterfaceMD = ResolveToInterfaceMethodDecl(MD))
Ted Kremenek76a50e32009-04-30 05:47:23 +0000829 MD = InterfaceMD;
Ted Kremenek70a65762009-04-30 05:41:14 +0000830
Ted Kremenek552333c2009-04-29 17:17:48 +0000831 if (MD->isInstanceMethod())
832 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
833 else
834 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
835 }
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000836
Ted Kremeneka8833552009-04-29 23:03:22 +0000837 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
838 Selector S, QualType RetTy);
839
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000840 void updateSummaryFromAnnotations(RetainSummary &Summ,
841 const ObjCMethodDecl *MD);
842
843 void updateSummaryFromAnnotations(RetainSummary &Summ,
844 const FunctionDecl *FD);
845
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000846 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek885c27b2009-05-04 05:31:22 +0000847
848 RetainSummary *copySummary(RetainSummary *OldSumm) {
849 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
850 new (Summ) RetainSummary(*OldSumm);
851 return Summ;
852 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000853};
854
855} // end anonymous namespace
856
857//===----------------------------------------------------------------------===//
858// Implementation of checker data structures.
859//===----------------------------------------------------------------------===//
860
Ted Kremenekb77449c2009-05-03 05:20:50 +0000861RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000862
Ted Kremenekb77449c2009-05-03 05:20:50 +0000863ArgEffects RetainSummaryManager::getArgEffects() {
864 ArgEffects AE = ScratchArgs;
865 ScratchArgs = AF.GetEmptyMap();
866 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000867}
868
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000869RetainSummary*
Ted Kremenekb77449c2009-05-03 05:20:50 +0000870RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000871 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000872 ArgEffect DefaultEff,
Ted Kremenek22fe2482009-05-04 04:30:18 +0000873 bool isEndPath) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000874 // Create the summary and return it.
Ted Kremenek22fe2482009-05-04 04:30:18 +0000875 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000876 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000877 return Summ;
878}
879
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000880//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000881// Predicates.
882//===----------------------------------------------------------------------===//
883
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000884bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Steve Narofff4954562009-07-16 15:41:00 +0000885 if (!Ty->isObjCObjectPointerType())
Ted Kremenek234a4c22009-01-07 00:39:56 +0000886 return false;
887
Steve Naroff14108da2009-07-10 23:34:53 +0000888 const ObjCObjectPointerType *PT = Ty->getAsObjCObjectPointerType();
889
890 // Can be true for objects with the 'NSObject' attribute.
891 if (!PT)
Ted Kremenek97d095f2009-04-23 22:11:07 +0000892 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000893
894 // We assume that id<..>, id, and "Class" all represent tracked objects.
895 if (PT->isObjCIdType() || PT->isObjCQualifiedIdType() ||
896 PT->isObjCClassType())
897 return true;
Ted Kremenek234a4c22009-01-07 00:39:56 +0000898
Ted Kremenekfae664a2009-05-16 01:38:01 +0000899 // Does the interface subclass NSObject?
900 // FIXME: We can memoize here if this gets too expensive.
Steve Naroff14108da2009-07-10 23:34:53 +0000901 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
Ted Kremenek234a4c22009-01-07 00:39:56 +0000902
Ted Kremenekfae664a2009-05-16 01:38:01 +0000903 // Assume that anything declared with a forward declaration and no
904 // @interface subclasses NSObject.
905 if (ID->isForwardDecl())
906 return true;
907
908 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
909
Ted Kremenek234a4c22009-01-07 00:39:56 +0000910 for ( ; ID ; ID = ID->getSuperClass())
911 if (ID->getIdentifier() == NSObjectII)
912 return true;
913
914 return false;
915}
916
Ted Kremenek92511432009-05-03 06:08:32 +0000917bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
918 return isRefType(T, "CF") || // Core Foundation.
919 isRefType(T, "CG") || // Core Graphics.
920 isRefType(T, "DADisk") || // Disk Arbitration API.
921 isRefType(T, "DADissenter") ||
922 isRefType(T, "DASessionRef");
923}
924
Ted Kremenek234a4c22009-01-07 00:39:56 +0000925//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000926// Summary creation for functions (largely uses of Core Foundation).
927//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000928
Ted Kremenek12619382009-01-12 21:45:02 +0000929static bool isRetain(FunctionDecl* FD, const char* FName) {
930 const char* loc = strstr(FName, "Retain");
931 return loc && loc[sizeof("Retain")-1] == '\0';
932}
933
934static bool isRelease(FunctionDecl* FD, const char* FName) {
935 const char* loc = strstr(FName, "Release");
936 return loc && loc[sizeof("Release")-1] == '\0';
937}
938
Ted Kremenekab592272008-06-24 03:56:45 +0000939RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000940 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000941 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000942 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000943 return I->second;
944
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000945 // No summary? Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000946 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000947
Ted Kremenek37d785b2008-07-15 16:50:12 +0000948 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000949 // We generate "stop" summaries for implicitly defined functions.
950 if (FD->isImplicit()) {
951 S = getPersistentStopSummary();
952 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000953 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000954
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000955 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000956 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000957 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000958 const char* FName = FD->getIdentifier()->getName();
959
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000960 // Strip away preceding '_'. Doing this here will effect all the checks
961 // down below.
962 while (*FName == '_') ++FName;
963
Ted Kremenek12619382009-01-12 21:45:02 +0000964 // Inspect the result type.
965 QualType RetTy = FT->getResultType();
966
967 // FIXME: This should all be refactored into a chain of "summary lookup"
968 // filters.
Ted Kremenek39d88b02009-06-15 20:36:07 +0000969 assert (ScratchArgs.isEmpty());
970
Ted Kremenekb04cb592009-06-11 18:17:24 +0000971 switch (strlen(FName)) {
972 default: break;
Ted Kremenek39d88b02009-06-15 20:36:07 +0000973
974
Ted Kremenekb04cb592009-06-11 18:17:24 +0000975 case 17:
976 // Handle: id NSMakeCollectable(CFTypeRef)
977 if (!memcmp(FName, "NSMakeCollectable", 17)) {
Steve Naroff14108da2009-07-10 23:34:53 +0000978 S = (RetTy->isObjCIdType())
Ted Kremenekb04cb592009-06-11 18:17:24 +0000979 ? getUnarySummary(FT, cfmakecollectable)
980 : getPersistentStopSummary();
981 }
Ted Kremenek39d88b02009-06-15 20:36:07 +0000982 else if (!memcmp(FName, "IOBSDNameMatching", 17) ||
983 !memcmp(FName, "IOServiceMatching", 17)) {
984 // Part of <rdar://problem/6961230>. (IOKit)
985 // This should be addressed using a API table.
986 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
987 DoNothing, DoNothing);
988 }
Ted Kremenekb04cb592009-06-11 18:17:24 +0000989 break;
Ted Kremenek39d88b02009-06-15 20:36:07 +0000990
991 case 21:
992 if (!memcmp(FName, "IOServiceNameMatching", 21)) {
993 // Part of <rdar://problem/6961230>. (IOKit)
994 // This should be addressed using a API table.
995 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
996 DoNothing, DoNothing);
997 }
998 break;
999
1000 case 24:
1001 if (!memcmp(FName, "IOServiceAddNotification", 24)) {
1002 // Part of <rdar://problem/6961230>. (IOKit)
1003 // This should be addressed using a API table.
1004 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1005 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1006 }
1007 break;
1008
1009 case 25:
1010 if (!memcmp(FName, "IORegistryEntryIDMatching", 25)) {
1011 // Part of <rdar://problem/6961230>. (IOKit)
1012 // This should be addressed using a API table.
1013 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1014 DoNothing, DoNothing);
1015 }
1016 break;
1017
1018 case 26:
1019 if (!memcmp(FName, "IOOpenFirmwarePathMatching", 26)) {
1020 // Part of <rdar://problem/6961230>. (IOKit)
1021 // This should be addressed using a API table.
1022 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1023 DoNothing, DoNothing);
1024 }
1025 break;
1026
Ted Kremenekb04cb592009-06-11 18:17:24 +00001027 case 27:
1028 if (!memcmp(FName, "IOServiceGetMatchingService", 27)) {
1029 // Part of <rdar://problem/6961230>.
1030 // This should be addressed using a API table.
Ted Kremenekb04cb592009-06-11 18:17:24 +00001031 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1032 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1033 }
1034 break;
1035
1036 case 28:
1037 if (!memcmp(FName, "IOServiceGetMatchingServices", 28)) {
1038 // FIXES: <rdar://problem/6326900>
1039 // This should be addressed using a API table. This strcmp is also
1040 // a little gross, but there is no need to super optimize here.
Ted Kremenekb04cb592009-06-11 18:17:24 +00001041 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1042 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1043 }
1044 break;
Ted Kremenek39d88b02009-06-15 20:36:07 +00001045
1046 case 32:
1047 if (!memcmp(FName, "IOServiceAddMatchingNotification", 32)) {
1048 // Part of <rdar://problem/6961230>.
1049 // This should be addressed using a API table.
1050 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1051 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1052 }
1053 break;
Ted Kremenekb04cb592009-06-11 18:17:24 +00001054 }
1055
1056 // Did we get a summary?
1057 if (S)
1058 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001059
1060 // Enable this code once the semantics of NSDeallocateObject are resolved
1061 // for GC. <rdar://problem/6619988>
1062#if 0
1063 // Handle: NSDeallocateObject(id anObject);
1064 // This method does allow 'nil' (although we don't check it now).
1065 if (strcmp(FName, "NSDeallocateObject") == 0) {
1066 return RetTy == Ctx.VoidTy
1067 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1068 : getPersistentStopSummary();
1069 }
1070#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001071
1072 if (RetTy->isPointerType()) {
1073 // For CoreFoundation ('CF') types.
1074 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1075 if (isRetain(FD, FName))
1076 S = getUnarySummary(FT, cfretain);
1077 else if (strstr(FName, "MakeCollectable"))
1078 S = getUnarySummary(FT, cfmakecollectable);
1079 else
1080 S = getCFCreateGetRuleSummary(FD, FName);
1081
1082 break;
1083 }
1084
1085 // For CoreGraphics ('CG') types.
1086 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1087 if (isRetain(FD, FName))
1088 S = getUnarySummary(FT, cfretain);
1089 else
1090 S = getCFCreateGetRuleSummary(FD, FName);
1091
1092 break;
1093 }
1094
1095 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1096 if (isRefType(RetTy, "DADisk") ||
1097 isRefType(RetTy, "DADissenter") ||
1098 isRefType(RetTy, "DASessionRef")) {
1099 S = getCFCreateGetRuleSummary(FD, FName);
1100 break;
1101 }
1102
1103 break;
1104 }
1105
1106 // Check for release functions, the only kind of functions that we care
1107 // about that don't return a pointer type.
1108 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001109 // Test for 'CGCF'.
1110 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1111 FName += 4;
1112 else
1113 FName += 2;
1114
1115 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001116 S = getUnarySummary(FT, cfrelease);
1117 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001118 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001119 // Remaining CoreFoundation and CoreGraphics functions.
1120 // We use to assume that they all strictly followed the ownership idiom
1121 // and that ownership cannot be transferred. While this is technically
1122 // correct, many methods allow a tracked object to escape. For example:
1123 //
1124 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1125 // CFDictionaryAddValue(y, key, x);
1126 // CFRelease(x);
1127 // ... it is okay to use 'x' since 'y' has a reference to it
1128 //
1129 // We handle this and similar cases with the follow heuristic. If the
1130 // function name contains "InsertValue", "SetValue" or "AddValue" then
1131 // we assume that arguments may "escape."
1132 //
1133 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1134 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +00001135 CStrInCStrNoCase(FName, "SetValue") ||
1136 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +00001137 ? MayEscape : DoNothing;
1138
1139 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001140 }
1141 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001142 }
1143 while (0);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001144
1145 if (!S)
1146 S = getDefaultSummary();
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001147
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001148 // Annotations override defaults.
1149 assert(S);
1150 updateSummaryFromAnnotations(*S, FD);
1151
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001152 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001153 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001154}
1155
Ted Kremenek37d785b2008-07-15 16:50:12 +00001156RetainSummary*
1157RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1158 const char* FName) {
1159
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001160 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1161 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +00001162
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001163 if (strstr(FName, "Get"))
1164 return getCFSummaryGetRule(FD);
1165
Ted Kremenek7faca822009-05-04 04:57:00 +00001166 return getDefaultSummary();
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001167}
1168
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001169RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001170RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1171 UnaryFuncKind func) {
1172
Ted Kremenek12619382009-01-12 21:45:02 +00001173 // Sanity check that this is *really* a unary function. This can
1174 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001175 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001176 if (!FTP || FTP->getNumArgs() != 1)
1177 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001178
Ted Kremenekb77449c2009-05-03 05:20:50 +00001179 assert (ScratchArgs.isEmpty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001180
Ted Kremenek377e2302008-04-29 05:33:51 +00001181 switch (func) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001182 case cfretain: {
1183 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001184 return getPersistentSummary(RetEffect::MakeAlias(0),
1185 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001186 }
1187
1188 case cfrelease: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001189 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001190 return getPersistentSummary(RetEffect::MakeNoRet(),
1191 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001192 }
1193
1194 case cfmakecollectable: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001195 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek27019002009-02-18 21:57:45 +00001196 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001197 }
1198
1199 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001200 assert (false && "Not a supported unary function.");
Ted Kremenek7faca822009-05-04 04:57:00 +00001201 return getDefaultSummary();
Ted Kremenek940b1d82008-04-10 23:44:06 +00001202 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001203}
1204
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001205RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001206 assert (ScratchArgs.isEmpty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001207
1208 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001209 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1210 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenek070a8252008-07-09 18:11:16 +00001211 }
1212
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001213 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001214}
1215
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001216RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001217 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001218 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1219 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001220}
1221
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001222//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001223// Summary creation for Selectors.
1224//===----------------------------------------------------------------------===//
1225
Ted Kremenek1bffd742008-05-06 15:44:25 +00001226RetainSummary*
Ted Kremenek8711c032009-04-29 05:04:30 +00001227RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek78a35a32009-05-12 20:06:54 +00001228 assert(ScratchArgs.isEmpty());
1229 // 'init' methods conceptually return a newly allocated object and claim
1230 // the receiver.
1231 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
Ted Kremenek547d4952009-06-05 23:18:01 +00001232 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001233
1234 return getDefaultSummary();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001235}
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001236
1237void
1238RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1239 const FunctionDecl *FD) {
1240 if (!FD)
1241 return;
1242
Ted Kremenekb04cb592009-06-11 18:17:24 +00001243 QualType RetTy = FD->getResultType();
1244
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001245 // Determine if there is a special return effect for this method.
Ted Kremenekb9d8db82009-06-05 23:00:33 +00001246 if (isTrackedObjCObjectType(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001247 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001248 Summ.setRetEffect(ObjCAllocRetE);
1249 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001250 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenekb9d8db82009-06-05 23:00:33 +00001251 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001252 }
1253 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001254 else if (RetTy->getAs<PointerType>()) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001255 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001256 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1257 }
1258 }
1259}
1260
1261void
1262RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1263 const ObjCMethodDecl *MD) {
1264 if (!MD)
1265 return;
1266
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001267 bool isTrackedLoc = false;
1268
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001269 // Determine if there is a special return effect for this method.
1270 if (isTrackedObjCObjectType(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001271 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001272 Summ.setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001273 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001274 }
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001275
1276 isTrackedLoc = true;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001277 }
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001278
1279 if (!isTrackedLoc)
Ted Kremenek6217b802009-07-29 21:53:49 +00001280 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001281
1282 if (isTrackedLoc && MD->getAttr<CFReturnsRetainedAttr>())
1283 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001284}
1285
Ted Kremenek1bffd742008-05-06 15:44:25 +00001286RetainSummary*
Ted Kremeneka8833552009-04-29 23:03:22 +00001287RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1288 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001289
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001290 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001291 // Scan the method decl for 'void*' arguments. These should be treated
1292 // as 'StopTracking' because they are often used with delegates.
1293 // Delegates are a frequent form of false positives with the retain
1294 // count checker.
1295 unsigned i = 0;
1296 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1297 E = MD->param_end(); I != E; ++I, ++i)
1298 if (ParmVarDecl *PD = *I) {
1299 QualType Ty = Ctx.getCanonicalType(PD->getType());
1300 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenekb77449c2009-05-03 05:20:50 +00001301 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001302 }
1303 }
1304
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001305 // Any special effect for the receiver?
1306 ArgEffect ReceiverEff = DoNothing;
1307
1308 // If one of the arguments in the selector has the keyword 'delegate' we
1309 // should stop tracking the reference count for the receiver. This is
1310 // because the reference count is quite possibly handled by a delegate
1311 // method.
1312 if (S.isKeywordSelector()) {
1313 const std::string &str = S.getAsString();
1314 assert(!str.empty());
1315 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1316 }
1317
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001318 // Look for methods that return an owned object.
Ted Kremenek92511432009-05-03 06:08:32 +00001319 if (isTrackedObjCObjectType(RetTy)) {
1320 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1321 // by instance methods.
Ted Kremenek7db16042009-05-15 15:49:00 +00001322 RetEffect E = followsFundamentalRule(S)
1323 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek92511432009-05-03 06:08:32 +00001324
1325 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001326 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001327
Ted Kremenek92511432009-05-03 06:08:32 +00001328 // Look for methods that return an owned core foundation object.
1329 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek7db16042009-05-15 15:49:00 +00001330 RetEffect E = followsFundamentalRule(S)
1331 ? RetEffect::MakeOwned(RetEffect::CF, true)
1332 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremenek92511432009-05-03 06:08:32 +00001333
1334 return getPersistentSummary(E, ReceiverEff, MayEscape);
1335 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001336
Ted Kremenek92511432009-05-03 06:08:32 +00001337 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek7faca822009-05-04 04:57:00 +00001338 return getDefaultSummary();
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001339
Ted Kremenek885c27b2009-05-04 05:31:22 +00001340 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001341}
1342
1343RetainSummary*
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001344RetainSummaryManager::getInstanceMethodSummary(Selector S,
1345 IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001346 const ObjCInterfaceDecl* ID,
1347 const ObjCMethodDecl *MD,
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001348 QualType RetTy) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001349
Ted Kremenek8711c032009-04-29 05:04:30 +00001350 // Look up a summary in our summary cache.
Ted Kremenek614cc542009-07-21 23:27:57 +00001351 RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001352
Ted Kremenek614cc542009-07-21 23:27:57 +00001353 if (!Summ) {
1354 assert(ScratchArgs.isEmpty());
Ted Kremenekaee9e572008-05-06 06:09:09 +00001355
Ted Kremenek614cc542009-07-21 23:27:57 +00001356 // "initXXX": pass-through for receiver.
1357 if (deriveNamingConvention(S) == InitRule)
1358 Summ = getInitMethodSummary(RetTy);
1359 else
1360 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001361
Ted Kremenek614cc542009-07-21 23:27:57 +00001362 // Annotations override defaults.
1363 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001364
Ted Kremenek614cc542009-07-21 23:27:57 +00001365 // Memoize the summary.
1366 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1367 }
1368
Ted Kremeneke87450e2009-04-23 19:11:35 +00001369 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001370}
1371
Ted Kremenekc8395602008-05-06 21:26:51 +00001372RetainSummary*
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001373RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001374 const ObjCInterfaceDecl *ID,
1375 const ObjCMethodDecl *MD,
1376 QualType RetTy) {
Ted Kremenekde4d5332009-04-24 17:50:11 +00001377
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001378 assert(ClsName && "Class name must be specified.");
Ted Kremenek614cc542009-07-21 23:27:57 +00001379 RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001380
Ted Kremenek614cc542009-07-21 23:27:57 +00001381 if (!Summ) {
1382 Summ = getCommonMethodSummary(MD, S, RetTy);
1383 // Annotations override defaults.
1384 updateSummaryFromAnnotations(*Summ, MD);
1385 // Memoize the summary.
1386 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1387 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001388
Ted Kremeneke87450e2009-04-23 19:11:35 +00001389 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001390}
1391
Ted Kremenekec315332009-05-07 23:40:42 +00001392void RetainSummaryManager::InitializeClassMethodSummaries() {
1393 assert(ScratchArgs.isEmpty());
1394 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001395
Ted Kremenek553cf182008-06-25 21:21:56 +00001396 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1397 // NSObject and its derivatives.
1398 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1399 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1400 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001401
1402 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001403 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001404 GetNullarySelector("currentHandler", Ctx),
1405 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001406
1407 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb77449c2009-05-03 05:20:50 +00001408 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenekabf43972009-01-28 21:44:40 +00001409 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1410 GetUnarySelector("addObject", Ctx),
1411 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001412 DoNothing, Autorelease));
Ted Kremenekde4d5332009-04-24 17:50:11 +00001413
1414 // Create the summaries for [NSObject performSelector...]. We treat
1415 // these as 'stop tracking' for the arguments because they are often
1416 // used for delegates that can release the object. When we have better
1417 // inter-procedural analysis we can potentially do something better. This
1418 // workaround is to remove false positives.
1419 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1420 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1421 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1422 "afterDelay", NULL);
1423 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1424 "afterDelay", "inModes", NULL);
1425 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1426 "withObject", "waitUntilDone", NULL);
1427 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1428 "withObject", "waitUntilDone", "modes", NULL);
1429 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1430 "withObject", "waitUntilDone", NULL);
1431 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1432 "withObject", "waitUntilDone", "modes", NULL);
1433 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1434 "withObject", NULL);
Ted Kremenek30437662009-05-14 21:29:16 +00001435
1436 // Specially handle NSData.
1437 RetainSummary *dataWithBytesNoCopySumm =
1438 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1439 DoNothing);
1440 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1441 "dataWithBytesNoCopy", "length", NULL);
1442 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1443 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001444}
1445
Ted Kremenek1f180c32008-06-23 22:21:20 +00001446void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001447
Ted Kremenekb77449c2009-05-03 05:20:50 +00001448 assert (ScratchArgs.isEmpty());
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001449
Ted Kremenekc8395602008-05-06 21:26:51 +00001450 // Create the "init" selector. It just acts as a pass-through for the
1451 // receiver.
Ted Kremenek78a35a32009-05-12 20:06:54 +00001452 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
Ted Kremenekb04cb592009-06-11 18:17:24 +00001453 getPersistentSummary(ObjCInitRetE, DecRefMsg));
Ted Kremenekc8395602008-05-06 21:26:51 +00001454
1455 // The next methods are allocators.
Ted Kremenek767d6492009-05-20 22:39:57 +00001456 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Ted Kremenekc8395602008-05-06 21:26:51 +00001457
1458 // Create the "copy" selector.
Ted Kremenek767d6492009-05-20 22:39:57 +00001459 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek98530452008-08-12 20:41:56 +00001460
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001461 // Create the "mutableCopy" selector.
Ted Kremenek767d6492009-05-20 22:39:57 +00001462 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Ted Kremenek98530452008-08-12 20:41:56 +00001463
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001464 // Create the "retain" selector.
Ted Kremenekec315332009-05-07 23:40:42 +00001465 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek767d6492009-05-20 22:39:57 +00001466 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001467 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001468
1469 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001470 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001471 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001472
1473 // Create the "drain" selector.
1474 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001475 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001476
1477 // Create the -dealloc summary.
1478 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1479 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001480
1481 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001482 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001483 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001484
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001485 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001486 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001487 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001488 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001489
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001490 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001491 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1492 // self-own themselves. However, they only do this once they are displayed.
1493 // Thus, we need to track an NSWindow's display status.
1494 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001495 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek78a35a32009-05-12 20:06:54 +00001496 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1497 StopTracking,
1498 StopTracking);
Ted Kremenek99d02692009-04-03 19:02:51 +00001499
1500 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1501
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001502#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001503 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001504 "styleMask", "backing", "defer", NULL);
1505
Ted Kremenek78a35a32009-05-12 20:06:54 +00001506 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001507 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001508#endif
Ted Kremenek78a35a32009-05-12 20:06:54 +00001509
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001510 // For NSPanel (which subclasses NSWindow), allocated objects are not
1511 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001512 // FIXME: For now we don't track NSPanels. object for the same reason
1513 // as for NSWindow objects.
1514 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1515
Ted Kremenek78a35a32009-05-12 20:06:54 +00001516#if 0
1517 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001518 "styleMask", "backing", "defer", NULL);
1519
Ted Kremenek78a35a32009-05-12 20:06:54 +00001520 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001521 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001522#endif
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001523
1524 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1525 // exit a method.
1526 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001527
Ted Kremenek70a733e2008-07-18 17:24:20 +00001528 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001529 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1530 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001531
Ted Kremenek9e476de2008-08-12 18:30:56 +00001532 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1533 "file", "lineNumber", "description", NULL);
Ted Kremenek767d6492009-05-20 22:39:57 +00001534
1535 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1536 addInstMethSummary("QCRenderer", AllocSumm,
1537 "createSnapshotImageOfType", NULL);
1538 addInstMethSummary("QCView", AllocSumm,
1539 "createSnapshotImageOfType", NULL);
1540
Ted Kremenek211a9c62009-06-15 20:58:58 +00001541 // Create summaries for CIContext, 'createCGImage' and
1542 // 'createCGLayerWithSize'.
Ted Kremenek767d6492009-05-20 22:39:57 +00001543 addInstMethSummary("CIContext", AllocSumm,
1544 "createCGImage", "fromRect", NULL);
1545 addInstMethSummary("CIContext", AllocSumm,
Ted Kremenek211a9c62009-06-15 20:58:58 +00001546 "createCGImage", "fromRect", "format", "colorSpace", NULL);
1547 addInstMethSummary("CIContext", AllocSumm, "createCGLayerWithSize",
1548 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001549}
1550
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001551//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001552// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001553//===----------------------------------------------------------------------===//
1554
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001555namespace {
1556
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001557class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001558public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001559 enum Kind {
1560 Owned = 0, // Owning reference.
1561 NotOwned, // Reference is not owned by still valid (not freed).
1562 Released, // Object has been released.
1563 ReturnedOwned, // Returned object passes ownership to caller.
1564 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001565 ERROR_START,
1566 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1567 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001568 ErrorUseAfterRelease, // Object used after released.
1569 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001570 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001571 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek369de562009-05-09 00:10:05 +00001572 ErrorLeakReturned, // A memory leak due to the returning method not having
1573 // the correct naming conventions.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001574 ErrorGCLeakReturned,
1575 ErrorOverAutorelease,
1576 ErrorReturnedNotOwned
Ted Kremenek4fd88972008-04-17 18:12:53 +00001577 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001578
1579private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001580 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001581 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001582 unsigned Cnt;
Ted Kremenekf21332e2009-05-08 20:01:42 +00001583 unsigned ACnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001584 QualType T;
1585
Ted Kremenekf21332e2009-05-08 20:01:42 +00001586 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1587 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001588
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001589 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenekf21332e2009-05-08 20:01:42 +00001590 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001591
1592public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001593 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001594
1595 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001596
Ted Kremenekf21332e2009-05-08 20:01:42 +00001597 unsigned getCount() const { return Cnt; }
1598 unsigned getAutoreleaseCount() const { return ACnt; }
1599 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1600 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek369de562009-05-09 00:10:05 +00001601 void setCount(unsigned i) { Cnt = i; }
1602 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001603
Ted Kremenek553cf182008-06-25 21:21:56 +00001604 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001605
1606 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001607
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001608 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001609
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001610 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001611
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001612 bool isOwned() const {
1613 return getKind() == Owned;
1614 }
1615
Ted Kremenekdb863712008-04-16 22:32:20 +00001616 bool isNotOwned() const {
1617 return getKind() == NotOwned;
1618 }
1619
Ted Kremenek4fd88972008-04-17 18:12:53 +00001620 bool isReturnedOwned() const {
1621 return getKind() == ReturnedOwned;
1622 }
1623
1624 bool isReturnedNotOwned() const {
1625 return getKind() == ReturnedNotOwned;
1626 }
1627
1628 bool isNonLeakError() const {
1629 Kind k = getKind();
1630 return isError(k) && !isLeak(k);
1631 }
1632
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001633 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1634 unsigned Count = 1) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001635 return RefVal(Owned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001636 }
1637
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001638 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1639 unsigned Count = 0) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001640 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001641 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001642
Ted Kremenek4fd88972008-04-17 18:12:53 +00001643 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001644
Ted Kremenek4fd88972008-04-17 18:12:53 +00001645 bool operator==(const RefVal& X) const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001646 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001647 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001648
Ted Kremenek553cf182008-06-25 21:21:56 +00001649 RefVal operator-(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001650 return RefVal(getKind(), getObjKind(), getCount() - i,
1651 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001652 }
1653
1654 RefVal operator+(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001655 return RefVal(getKind(), getObjKind(), getCount() + i,
1656 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001657 }
1658
1659 RefVal operator^(Kind k) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001660 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1661 getType());
1662 }
1663
1664 RefVal autorelease() const {
1665 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1666 getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001667 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001668
Ted Kremenek4fd88972008-04-17 18:12:53 +00001669 void Profile(llvm::FoldingSetNodeID& ID) const {
1670 ID.AddInteger((unsigned) kind);
1671 ID.AddInteger(Cnt);
Ted Kremenekf21332e2009-05-08 20:01:42 +00001672 ID.AddInteger(ACnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001673 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001674 }
1675
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001676 void print(llvm::raw_ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001677};
Ted Kremenekf3948042008-03-11 19:44:10 +00001678
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001679void RefVal::print(llvm::raw_ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001680 if (!T.isNull())
1681 Out << "Tracked Type:" << T.getAsString() << '\n';
1682
Ted Kremenekf3948042008-03-11 19:44:10 +00001683 switch (getKind()) {
1684 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001685 case Owned: {
1686 Out << "Owned";
1687 unsigned cnt = getCount();
1688 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001689 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001690 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001691
Ted Kremenek61b9f872008-04-10 23:09:18 +00001692 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001693 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001694 unsigned cnt = getCount();
1695 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001696 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001697 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001698
Ted Kremenek4fd88972008-04-17 18:12:53 +00001699 case ReturnedOwned: {
1700 Out << "ReturnedOwned";
1701 unsigned cnt = getCount();
1702 if (cnt) Out << " (+ " << cnt << ")";
1703 break;
1704 }
1705
1706 case ReturnedNotOwned: {
1707 Out << "ReturnedNotOwned";
1708 unsigned cnt = getCount();
1709 if (cnt) Out << " (+ " << cnt << ")";
1710 break;
1711 }
1712
Ted Kremenekf3948042008-03-11 19:44:10 +00001713 case Released:
1714 Out << "Released";
1715 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001716
1717 case ErrorDeallocGC:
1718 Out << "-dealloc (GC)";
1719 break;
1720
1721 case ErrorDeallocNotOwned:
1722 Out << "-dealloc (not-owned)";
1723 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001724
Ted Kremenekdb863712008-04-16 22:32:20 +00001725 case ErrorLeak:
1726 Out << "Leaked";
1727 break;
1728
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001729 case ErrorLeakReturned:
1730 Out << "Leaked (Bad naming)";
1731 break;
1732
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001733 case ErrorGCLeakReturned:
1734 Out << "Leaked (GC-ed at return)";
1735 break;
1736
Ted Kremenekf3948042008-03-11 19:44:10 +00001737 case ErrorUseAfterRelease:
1738 Out << "Use-After-Release [ERROR]";
1739 break;
1740
1741 case ErrorReleaseNotOwned:
1742 Out << "Release of Not-Owned [ERROR]";
1743 break;
Ted Kremenek80c24182009-05-09 00:44:07 +00001744
1745 case RefVal::ErrorOverAutorelease:
1746 Out << "Over autoreleased";
1747 break;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001748
1749 case RefVal::ErrorReturnedNotOwned:
1750 Out << "Non-owned object returned instead of owned";
1751 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001752 }
Ted Kremenekf21332e2009-05-08 20:01:42 +00001753
1754 if (ACnt) {
1755 Out << " [ARC +" << ACnt << ']';
1756 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001757}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001758
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001759} // end anonymous namespace
1760
1761//===----------------------------------------------------------------------===//
1762// RefBindings - State used to track object reference counts.
1763//===----------------------------------------------------------------------===//
1764
Ted Kremenek2dabd432008-12-05 02:27:51 +00001765typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001766static int RefBIndex = 0;
1767
1768namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001769 template<>
1770 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1771 static inline void* GDMIndex() { return &RefBIndex; }
1772 };
1773}
Ted Kremenek6d348932008-10-21 15:53:15 +00001774
1775//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001776// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001777//===----------------------------------------------------------------------===//
1778
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001779typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1780typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1781typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001782
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001783static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001784static int AutoRBIndex = 0;
1785
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001786namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001787namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001788
Ted Kremenek6d348932008-10-21 15:53:15 +00001789namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001790template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001791 : public GRStatePartialTrait<ARStack> {
1792 static inline void* GDMIndex() { return &AutoRBIndex; }
1793};
1794
1795template<> struct GRStateTrait<AutoreleasePoolContents>
1796 : public GRStatePartialTrait<ARPoolContents> {
1797 static inline void* GDMIndex() { return &AutoRCIndex; }
1798};
1799} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001800
Ted Kremenek7037ab82009-03-20 17:34:15 +00001801static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1802 ARStack stack = state->get<AutoreleaseStack>();
1803 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1804}
1805
Ted Kremenekb65be702009-06-18 01:23:53 +00001806static const GRState * SendAutorelease(const GRState *state,
1807 ARCounts::Factory &F, SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001808
1809 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001810 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001811 ARCounts newCnts(0);
1812
1813 if (cnts) {
1814 const unsigned *cnt = (*cnts).lookup(sym);
1815 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1816 }
1817 else
1818 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1819
Ted Kremenekb65be702009-06-18 01:23:53 +00001820 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001821}
1822
Ted Kremenek13922612008-04-16 20:40:59 +00001823//===----------------------------------------------------------------------===//
1824// Transfer functions.
1825//===----------------------------------------------------------------------===//
1826
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001827namespace {
1828
Ted Kremenek6c07bdb2009-06-26 00:05:51 +00001829class VISIBILITY_HIDDEN CFRefCount : public GRTransferFuncs {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001830public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001831 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001832 public:
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001833 virtual void Print(llvm::raw_ostream& Out, const GRState* state,
Ted Kremenekae6814e2008-08-13 21:24:49 +00001834 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001835 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001836
1837private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001838 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1839 SummaryLogTy;
1840
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001841 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001842 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001843 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001844 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001845
Ted Kremenekcf701772009-02-05 06:50:21 +00001846 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001847 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001848 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek369de562009-05-09 00:10:05 +00001849 BugType *overAutorelease;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001850 BugType *returnNotOwnedForOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001851 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001852
Ted Kremenekb65be702009-06-18 01:23:53 +00001853 const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001854 RefVal::Kind& hasErr);
1855
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001856 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1857 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu264e9372009-05-12 10:10:00 +00001858 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001859 ExplodedNode<GRState>* Pred,
1860 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001861 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001862
Ted Kremenekb65be702009-06-18 01:23:53 +00001863 const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001864 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1865
Ted Kremenekb65be702009-06-18 01:23:53 +00001866 ExplodedNode<GRState>* ProcessLeaks(const GRState * state,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001867 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1868 GenericNodeBuilder &Builder,
1869 GRExprEngine &Eng,
1870 ExplodedNode<GRState> *Pred = 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001871
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001872public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001873 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001874 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001875 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1876 deallocGC(0), deallocNotOwned(0),
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001877 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1878 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001879
Ted Kremenekcf701772009-02-05 06:50:21 +00001880 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001881
Ted Kremenekcf118d42009-02-04 23:49:09 +00001882 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001883
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001884 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1885 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001886 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001887
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001888 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001889 const LangOptions& getLangOptions() const { return LOpts; }
1890
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001891 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1892 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1893 return I == SummaryLog.end() ? 0 : I->second;
1894 }
1895
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001896 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001897
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001898 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001899 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001900 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001901 Expr* Ex,
1902 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00001903 const RetainSummary& Summ,
Zhongxing Xu264e9372009-05-12 10:10:00 +00001904 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001905 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001906
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001907 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001908 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001909 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001910 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001911 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001912
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001913
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001914 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001915 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001916 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001917 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001918 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001919
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001920 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001921 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001922 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001923 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001924 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001925
Ted Kremenek41573eb2009-02-14 01:43:44 +00001926 // Stores.
1927 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1928
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001929 // End-of-path.
1930
1931 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001932 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001933
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001934 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001935 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001936 GRStmtNodeBuilder<GRState>& Builder,
1937 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001938 Stmt* S, const GRState* state,
1939 SymbolReaper& SymReaper);
Ted Kremenekf04dced2009-05-08 23:32:51 +00001940
Ted Kremenekb65be702009-06-18 01:23:53 +00001941 std::pair<ExplodedNode<GRState>*, const GRState *>
1942 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Ted Kremenek369de562009-05-09 00:10:05 +00001943 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1944 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001945 // Return statements.
1946
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001947 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001948 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001949 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001950 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001951 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001952
1953 // Assumptions.
1954
Ted Kremeneka591bc02009-06-18 22:57:13 +00001955 virtual const GRState *EvalAssume(const GRState* state, SVal condition,
1956 bool assumption);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001957};
1958
1959} // end anonymous namespace
1960
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001961static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym,
1962 const GRState *state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001963 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001964 if (Sym)
1965 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001966 else
1967 Out << "<pool>";
1968 Out << ":{";
1969
1970 // Get the contents of the pool.
1971 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1972 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1973 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1974
1975 Out << '}';
1976}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001977
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001978void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out,
1979 const GRState* state,
Ted Kremenekae6814e2008-08-13 21:24:49 +00001980 const char* nl, const char* sep) {
1981
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001982 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001983
Ted Kremenekae6814e2008-08-13 21:24:49 +00001984 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001985 Out << sep << nl;
1986
1987 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1988 Out << (*I).first << " : ";
1989 (*I).second.print(Out);
1990 Out << nl;
1991 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001992
1993 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001994 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001995 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001996
Ted Kremenek7037ab82009-03-20 17:34:15 +00001997 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1998 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1999 PrintPool(Out, *I, state);
2000
2001 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00002002}
2003
Ted Kremenekc887d132009-04-29 18:50:19 +00002004//===----------------------------------------------------------------------===//
2005// Error reporting.
2006//===----------------------------------------------------------------------===//
2007
2008namespace {
2009
2010 //===-------------===//
2011 // Bug Descriptions. //
2012 //===-------------===//
2013
2014 class VISIBILITY_HIDDEN CFRefBug : public BugType {
2015 protected:
2016 CFRefCount& TF;
2017
2018 CFRefBug(CFRefCount* tf, const char* name)
2019 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
2020 public:
2021
2022 CFRefCount& getTF() { return TF; }
2023 const CFRefCount& getTF() const { return TF; }
2024
2025 // FIXME: Eventually remove.
2026 virtual const char* getDescription() const = 0;
2027
2028 virtual bool isLeak() const { return false; }
2029 };
2030
2031 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2032 public:
2033 UseAfterRelease(CFRefCount* tf)
2034 : CFRefBug(tf, "Use-after-release") {}
2035
2036 const char* getDescription() const {
2037 return "Reference-counted object is used after it is released";
2038 }
2039 };
2040
2041 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2042 public:
2043 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
2044
2045 const char* getDescription() const {
2046 return "Incorrect decrement of the reference count of an "
2047 "object is not owned at this point by the caller";
2048 }
2049 };
2050
2051 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2052 public:
Ted Kremenek369de562009-05-09 00:10:05 +00002053 DeallocGC(CFRefCount *tf)
2054 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002055
2056 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00002057 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00002058 }
2059 };
2060
2061 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2062 public:
Ted Kremenek369de562009-05-09 00:10:05 +00002063 DeallocNotOwned(CFRefCount *tf)
2064 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002065
2066 const char *getDescription() const {
2067 return "-dealloc sent to object that may be referenced elsewhere";
2068 }
2069 };
2070
Ted Kremenek369de562009-05-09 00:10:05 +00002071 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
2072 public:
2073 OverAutorelease(CFRefCount *tf) :
2074 CFRefBug(tf, "Object sent -autorelease too many times") {}
2075
2076 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002077 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00002078 }
2079 };
2080
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002081 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
2082 public:
2083 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2084 CFRefBug(tf, "Method should return an owned object") {}
2085
2086 const char *getDescription() const {
2087 return "Object with +0 retain counts returned to caller where a +1 "
2088 "(owning) retain count is expected";
2089 }
2090 };
2091
Ted Kremenekc887d132009-04-29 18:50:19 +00002092 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2093 const bool isReturn;
2094 protected:
2095 Leak(CFRefCount* tf, const char* name, bool isRet)
2096 : CFRefBug(tf, name), isReturn(isRet) {}
2097 public:
2098
2099 const char* getDescription() const { return ""; }
2100
2101 bool isLeak() const { return true; }
2102 };
2103
2104 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2105 public:
2106 LeakAtReturn(CFRefCount* tf, const char* name)
2107 : Leak(tf, name, true) {}
2108 };
2109
2110 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2111 public:
2112 LeakWithinFunction(CFRefCount* tf, const char* name)
2113 : Leak(tf, name, false) {}
2114 };
2115
2116 //===---------===//
2117 // Bug Reports. //
2118 //===---------===//
2119
2120 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2121 protected:
2122 SymbolRef Sym;
2123 const CFRefCount &TF;
2124 public:
2125 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2126 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002127 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2128
2129 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2130 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu264e9372009-05-12 10:10:00 +00002131 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002132
2133 virtual ~CFRefReport() {}
2134
2135 CFRefBug& getBugType() {
2136 return (CFRefBug&) RangedBugReport::getBugType();
2137 }
2138 const CFRefBug& getBugType() const {
2139 return (const CFRefBug&) RangedBugReport::getBugType();
2140 }
2141
2142 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2143 const SourceRange*& end) {
2144
2145 if (!getBugType().isLeak())
2146 RangedBugReport::getRanges(BR, beg, end);
2147 else
2148 beg = end = 0;
2149 }
2150
2151 SymbolRef getSymbol() const { return Sym; }
2152
Ted Kremenek8966bc12009-05-06 21:39:49 +00002153 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002154 const ExplodedNode<GRState>* N);
2155
2156 std::pair<const char**,const char**> getExtraDescriptiveText();
2157
2158 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2159 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002160 BugReporterContext& BRC);
Ted Kremenekc887d132009-04-29 18:50:19 +00002161 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002162
Ted Kremenekc887d132009-04-29 18:50:19 +00002163 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2164 SourceLocation AllocSite;
2165 const MemRegion* AllocBinding;
2166 public:
2167 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2168 ExplodedNode<GRState> *n, SymbolRef sym,
2169 GRExprEngine& Eng);
2170
Ted Kremenek8966bc12009-05-06 21:39:49 +00002171 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002172 const ExplodedNode<GRState>* N);
2173
2174 SourceLocation getLocation() const { return AllocSite; }
2175 };
2176} // end anonymous namespace
2177
2178void CFRefCount::RegisterChecks(BugReporter& BR) {
2179 useAfterRelease = new UseAfterRelease(this);
2180 BR.Register(useAfterRelease);
2181
2182 releaseNotOwned = new BadRelease(this);
2183 BR.Register(releaseNotOwned);
2184
2185 deallocGC = new DeallocGC(this);
2186 BR.Register(deallocGC);
2187
2188 deallocNotOwned = new DeallocNotOwned(this);
2189 BR.Register(deallocNotOwned);
2190
Ted Kremenek369de562009-05-09 00:10:05 +00002191 overAutorelease = new OverAutorelease(this);
2192 BR.Register(overAutorelease);
2193
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002194 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2195 BR.Register(returnNotOwnedForOwned);
2196
Ted Kremenekc887d132009-04-29 18:50:19 +00002197 // First register "return" leaks.
2198 const char* name = 0;
2199
2200 if (isGCEnabled())
2201 name = "Leak of returned object when using garbage collection";
2202 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2203 name = "Leak of returned object when not using garbage collection (GC) in "
2204 "dual GC/non-GC code";
2205 else {
2206 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2207 name = "Leak of returned object";
2208 }
2209
2210 leakAtReturn = new LeakAtReturn(this, name);
2211 BR.Register(leakAtReturn);
2212
2213 // Second, register leaks within a function/method.
2214 if (isGCEnabled())
2215 name = "Leak of object when using garbage collection";
2216 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2217 name = "Leak of object when not using garbage collection (GC) in "
2218 "dual GC/non-GC code";
2219 else {
2220 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2221 name = "Leak";
2222 }
2223
2224 leakWithinFunction = new LeakWithinFunction(this, name);
2225 BR.Register(leakWithinFunction);
2226
2227 // Save the reference to the BugReporter.
2228 this->BR = &BR;
2229}
2230
2231static const char* Msgs[] = {
2232 // GC only
2233 "Code is compiled to only use garbage collection",
2234 // No GC.
2235 "Code is compiled to use reference counts",
2236 // Hybrid, with GC.
2237 "Code is compiled to use either garbage collection (GC) or reference counts"
2238 " (non-GC). The bug occurs with GC enabled",
2239 // Hybrid, without GC
2240 "Code is compiled to use either garbage collection (GC) or reference counts"
2241 " (non-GC). The bug occurs in non-GC mode"
2242};
2243
2244std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2245 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2246
2247 switch (TF.getLangOptions().getGCMode()) {
2248 default:
2249 assert(false);
2250
2251 case LangOptions::GCOnly:
2252 assert (TF.isGCEnabled());
2253 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2254
2255 case LangOptions::NonGC:
2256 assert (!TF.isGCEnabled());
2257 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2258
2259 case LangOptions::HybridGC:
2260 if (TF.isGCEnabled())
2261 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2262 else
2263 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2264 }
2265}
2266
2267static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2268 ArgEffect X) {
2269 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2270 I!=E; ++I)
2271 if (*I == X) return true;
2272
2273 return false;
2274}
2275
2276PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2277 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002278 BugReporterContext& BRC) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002279
Ted Kremenek2033a952009-05-13 07:12:33 +00002280 if (!isa<PostStmt>(N->getLocation()))
2281 return NULL;
2282
Ted Kremenek8966bc12009-05-06 21:39:49 +00002283 // Check if the type state has changed.
Ted Kremenekb65be702009-06-18 01:23:53 +00002284 const GRState *PrevSt = PrevN->getState();
2285 const GRState *CurrSt = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002286
Ted Kremenekb65be702009-06-18 01:23:53 +00002287 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002288 if (!CurrT) return NULL;
2289
Ted Kremenekb65be702009-06-18 01:23:53 +00002290 const RefVal &CurrV = *CurrT;
2291 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002292
2293 // Create a string buffer to constain all the useful things we want
2294 // to tell the user.
2295 std::string sbuf;
2296 llvm::raw_string_ostream os(sbuf);
2297
2298 // This is the allocation site since the previous node had no bindings
2299 // for this symbol.
2300 if (!PrevT) {
Ted Kremenek5f85e172009-07-22 22:35:28 +00002301 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc887d132009-04-29 18:50:19 +00002302
Ted Kremenek5f85e172009-07-22 22:35:28 +00002303 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002304 // Get the name of the callee (if it is available).
Ted Kremenekb65be702009-06-18 01:23:53 +00002305 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
Ted Kremenekc887d132009-04-29 18:50:19 +00002306 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2307 os << "Call to function '" << FD->getNameAsString() <<'\'';
2308 else
2309 os << "function call";
2310 }
2311 else {
2312 assert (isa<ObjCMessageExpr>(S));
2313 os << "Method";
2314 }
2315
2316 if (CurrV.getObjKind() == RetEffect::CF) {
2317 os << " returns a Core Foundation object with a ";
2318 }
2319 else {
2320 assert (CurrV.getObjKind() == RetEffect::ObjC);
2321 os << " returns an Objective-C object with a ";
2322 }
2323
2324 if (CurrV.isOwned()) {
2325 os << "+1 retain count (owning reference).";
2326
2327 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2328 assert(CurrV.getObjKind() == RetEffect::CF);
2329 os << " "
2330 "Core Foundation objects are not automatically garbage collected.";
2331 }
2332 }
2333 else {
2334 assert (CurrV.isNotOwned());
2335 os << "+0 retain count (non-owning reference).";
2336 }
2337
Ted Kremenek8966bc12009-05-06 21:39:49 +00002338 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002339 return new PathDiagnosticEventPiece(Pos, os.str());
2340 }
2341
2342 // Gather up the effects that were performed on the object at this
2343 // program point
2344 llvm::SmallVector<ArgEffect, 2> AEffects;
2345
Ted Kremenek8966bc12009-05-06 21:39:49 +00002346 if (const RetainSummary *Summ =
2347 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002348 // We only have summaries attached to nodes after evaluating CallExpr and
2349 // ObjCMessageExprs.
Ted Kremenek5f85e172009-07-22 22:35:28 +00002350 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc887d132009-04-29 18:50:19 +00002351
Ted Kremenek5f85e172009-07-22 22:35:28 +00002352 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002353 // Iterate through the parameter expressions and see if the symbol
2354 // was ever passed as an argument.
2355 unsigned i = 0;
2356
Ted Kremenek5f85e172009-07-22 22:35:28 +00002357 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00002358 AI!=AE; ++AI, ++i) {
2359
2360 // Retrieve the value of the argument. Is it the symbol
2361 // we are interested in?
Ted Kremenekb65be702009-06-18 01:23:53 +00002362 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002363 continue;
2364
2365 // We have an argument. Get the effect!
2366 AEffects.push_back(Summ->getArg(i));
2367 }
2368 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00002369 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2370 if (const Expr *receiver = ME->getReceiver())
Ted Kremenekb65be702009-06-18 01:23:53 +00002371 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002372 // The symbol we are tracking is the receiver.
2373 AEffects.push_back(Summ->getReceiverEffect());
2374 }
2375 }
2376 }
2377
2378 do {
2379 // Get the previous type state.
2380 RefVal PrevV = *PrevT;
2381
2382 // Specially handle -dealloc.
2383 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2384 // Determine if the object's reference count was pushed to zero.
2385 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2386 // We may not have transitioned to 'release' if we hit an error.
2387 // This case is handled elsewhere.
2388 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002389 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002390 os << "Object released by directly sending the '-dealloc' message";
2391 break;
2392 }
2393 }
2394
2395 // Specially handle CFMakeCollectable and friends.
2396 if (contains(AEffects, MakeCollectable)) {
2397 // Get the name of the function.
Ted Kremenek5f85e172009-07-22 22:35:28 +00002398 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekb65be702009-06-18 01:23:53 +00002399 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
Ted Kremenekc887d132009-04-29 18:50:19 +00002400 const FunctionDecl* FD = X.getAsFunctionDecl();
2401 const std::string& FName = FD->getNameAsString();
2402
2403 if (TF.isGCEnabled()) {
2404 // Determine if the object's reference count was pushed to zero.
2405 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2406
2407 os << "In GC mode a call to '" << FName
2408 << "' decrements an object's retain count and registers the "
2409 "object with the garbage collector. ";
2410
2411 if (CurrV.getKind() == RefVal::Released) {
2412 assert(CurrV.getCount() == 0);
2413 os << "Since it now has a 0 retain count the object can be "
2414 "automatically collected by the garbage collector.";
2415 }
2416 else
2417 os << "An object must have a 0 retain count to be garbage collected. "
2418 "After this call its retain count is +" << CurrV.getCount()
2419 << '.';
2420 }
2421 else
2422 os << "When GC is not enabled a call to '" << FName
2423 << "' has no effect on its argument.";
2424
2425 // Nothing more to say.
2426 break;
2427 }
2428
2429 // Determine if the typestate has changed.
2430 if (!(PrevV == CurrV))
2431 switch (CurrV.getKind()) {
2432 case RefVal::Owned:
2433 case RefVal::NotOwned:
2434
Ted Kremenekf21332e2009-05-08 20:01:42 +00002435 if (PrevV.getCount() == CurrV.getCount()) {
2436 // Did an autorelease message get sent?
2437 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2438 return 0;
2439
Zhongxing Xu264e9372009-05-12 10:10:00 +00002440 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002441 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002442 break;
2443 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002444
2445 if (PrevV.getCount() > CurrV.getCount())
2446 os << "Reference count decremented.";
2447 else
2448 os << "Reference count incremented.";
2449
2450 if (unsigned Count = CurrV.getCount())
2451 os << " The object now has a +" << Count << " retain count.";
2452
2453 if (PrevV.getKind() == RefVal::Released) {
2454 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2455 os << " The object is not eligible for garbage collection until the "
2456 "retain count reaches 0 again.";
2457 }
2458
2459 break;
2460
2461 case RefVal::Released:
2462 os << "Object released.";
2463 break;
2464
2465 case RefVal::ReturnedOwned:
2466 os << "Object returned to caller as an owning reference (single retain "
2467 "count transferred to caller).";
2468 break;
2469
2470 case RefVal::ReturnedNotOwned:
2471 os << "Object returned to caller with a +0 (non-owning) retain count.";
2472 break;
2473
2474 default:
2475 return NULL;
2476 }
2477
2478 // Emit any remaining diagnostics for the argument effects (if any).
2479 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2480 E=AEffects.end(); I != E; ++I) {
2481
2482 // A bunch of things have alternate behavior under GC.
2483 if (TF.isGCEnabled())
2484 switch (*I) {
2485 default: break;
2486 case Autorelease:
2487 os << "In GC mode an 'autorelease' has no effect.";
2488 continue;
2489 case IncRefMsg:
2490 os << "In GC mode the 'retain' message has no effect.";
2491 continue;
2492 case DecRefMsg:
2493 os << "In GC mode the 'release' message has no effect.";
2494 continue;
2495 }
2496 }
2497 } while(0);
2498
2499 if (os.str().empty())
2500 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002501
Ted Kremenek5f85e172009-07-22 22:35:28 +00002502 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek8966bc12009-05-06 21:39:49 +00002503 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002504 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2505
2506 // Add the range by scanning the children of the statement for any bindings
2507 // to Sym.
Ted Kremenek5f85e172009-07-22 22:35:28 +00002508 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2509 I!=E; ++I)
2510 if (const Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb65be702009-06-18 01:23:53 +00002511 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002512 P->addRange(Exp->getSourceRange());
2513 break;
2514 }
2515
2516 return P;
2517}
2518
2519namespace {
2520 class VISIBILITY_HIDDEN FindUniqueBinding :
2521 public StoreManager::BindingsHandler {
2522 SymbolRef Sym;
2523 const MemRegion* Binding;
2524 bool First;
2525
2526 public:
2527 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2528
2529 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2530 SVal val) {
2531
2532 SymbolRef SymV = val.getAsSymbol();
2533 if (!SymV || SymV != Sym)
2534 return true;
2535
2536 if (Binding) {
2537 First = false;
2538 return false;
2539 }
2540 else
2541 Binding = R;
2542
2543 return true;
2544 }
2545
2546 operator bool() { return First && Binding; }
2547 const MemRegion* getRegion() { return Binding; }
2548 };
2549}
2550
2551static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2552GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2553 SymbolRef Sym) {
2554
2555 // Find both first node that referred to the tracked symbol and the
2556 // memory location that value was store to.
2557 const ExplodedNode<GRState>* Last = N;
2558 const MemRegion* FirstBinding = 0;
2559
2560 while (N) {
2561 const GRState* St = N->getState();
2562 RefBindings B = St->get<RefBindings>();
2563
2564 if (!B.lookup(Sym))
2565 break;
2566
2567 FindUniqueBinding FB(Sym);
2568 StateMgr.iterBindings(St, FB);
2569 if (FB) FirstBinding = FB.getRegion();
2570
2571 Last = N;
2572 N = N->pred_empty() ? NULL : *(N->pred_begin());
2573 }
2574
2575 return std::make_pair(Last, FirstBinding);
2576}
2577
2578PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002579CFRefReport::getEndPath(BugReporterContext& BRC,
2580 const ExplodedNode<GRState>* EndN) {
2581 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002582 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002583 BRC.addNotableSymbol(Sym);
2584 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenekc887d132009-04-29 18:50:19 +00002585}
2586
2587PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002588CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2589 const ExplodedNode<GRState>* EndN){
Ted Kremenekc887d132009-04-29 18:50:19 +00002590
Ted Kremenek8966bc12009-05-06 21:39:49 +00002591 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002592 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002593 BRC.addNotableSymbol(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002594
2595 // We are reporting a leak. Walk up the graph to get to the first node where
2596 // the symbol appeared, and also get the first VarDecl that tracked object
2597 // is stored to.
2598 const ExplodedNode<GRState>* AllocNode = 0;
2599 const MemRegion* FirstBinding = 0;
2600
2601 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002602 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002603
2604 // Get the allocate site.
2605 assert(AllocNode);
Ted Kremenek5f85e172009-07-22 22:35:28 +00002606 const Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc887d132009-04-29 18:50:19 +00002607
Ted Kremenek8966bc12009-05-06 21:39:49 +00002608 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002609 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2610
2611 // Compute an actual location for the leak. Sometimes a leak doesn't
2612 // occur at an actual statement (e.g., transition between blocks; end
2613 // of function) so we need to walk the graph and compute a real location.
2614 const ExplodedNode<GRState>* LeakN = EndN;
2615 PathDiagnosticLocation L;
2616
2617 while (LeakN) {
2618 ProgramPoint P = LeakN->getLocation();
2619
2620 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2621 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2622 break;
2623 }
2624 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2625 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2626 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2627 break;
2628 }
2629 }
2630
2631 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2632 }
2633
2634 if (!L.isValid()) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00002635 const Decl &D = BRC.getCodeDecl();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002636 L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
Ted Kremenekc887d132009-04-29 18:50:19 +00002637 }
2638
2639 std::string sbuf;
2640 llvm::raw_string_ostream os(sbuf);
2641
2642 os << "Object allocated on line " << AllocLine;
2643
2644 if (FirstBinding)
2645 os << " and stored into '" << FirstBinding->getString() << '\'';
2646
2647 // Get the retain count.
2648 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2649
2650 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2651 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2652 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2653 // to the caller for NS objects.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002654 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenekc887d132009-04-29 18:50:19 +00002655 os << " is returned from a method whose name ('"
Ted Kremeneka8833552009-04-29 23:03:22 +00002656 << MD.getSelector().getAsString()
Ted Kremenekc887d132009-04-29 18:50:19 +00002657 << "') does not contain 'copy' or otherwise starts with"
2658 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek8987a022009-04-29 22:25:52 +00002659 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002660 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002661 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2662 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2663 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002664 << "' is potentially leaked when using garbage collection. Callers "
2665 "of this method do not expect a returned object with a +1 retain "
2666 "count since they expect the object to be managed by the garbage "
2667 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002668 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002669 else
2670 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek8987a022009-04-29 22:25:52 +00002671 " +" << RV->getCount() << " (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002672
2673 return new PathDiagnosticEventPiece(L, os.str());
2674}
2675
Ted Kremenekc887d132009-04-29 18:50:19 +00002676CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2677 ExplodedNode<GRState> *n,
2678 SymbolRef sym, GRExprEngine& Eng)
2679: CFRefReport(D, tf, n, sym)
2680{
2681
2682 // Most bug reports are cached at the location where they occured.
2683 // With leaks, we want to unique them by the location where they were
2684 // allocated, and only report a single path. To do this, we need to find
2685 // the allocation site of a piece of tracked memory, which we do via a
2686 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2687 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2688 // that all ancestor nodes that represent the allocation site have the
2689 // same SourceLocation.
2690 const ExplodedNode<GRState>* AllocNode = 0;
2691
2692 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekf04dced2009-05-08 23:32:51 +00002693 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenekc887d132009-04-29 18:50:19 +00002694
2695 // Get the SourceLocation for the allocation site.
2696 ProgramPoint P = AllocNode->getLocation();
2697 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2698
2699 // Fill in the description of the bug.
2700 Description.clear();
2701 llvm::raw_string_ostream os(Description);
2702 SourceManager& SMgr = Eng.getContext().getSourceManager();
2703 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002704 os << "Potential leak ";
2705 if (tf.isGCEnabled()) {
2706 os << "(when using garbage collection) ";
2707 }
2708 os << "of an object allocated on line " << AllocLine;
Ted Kremenekc887d132009-04-29 18:50:19 +00002709
2710 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2711 if (AllocBinding)
2712 os << " and stored into '" << AllocBinding->getString() << '\'';
2713}
2714
2715//===----------------------------------------------------------------------===//
2716// Main checker logic.
2717//===----------------------------------------------------------------------===//
2718
Ted Kremenek553cf182008-06-25 21:21:56 +00002719/// GetReturnType - Used to get the return type of a message expression or
2720/// function call with the intention of affixing that type to a tracked symbol.
2721/// While the the return type can be queried directly from RetEx, when
2722/// invoking class methods we augment to the return type to be that of
2723/// a pointer to the class (as opposed it just being id).
Steve Naroff14108da2009-07-10 23:34:53 +00002724static QualType GetReturnType(const Expr* RetE, ASTContext& Ctx) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002725 QualType RetTy = RetE->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00002726 // If RetE is not a message expression just return its type.
2727 // If RetE is a message expression, return its types if it is something
Ted Kremenek553cf182008-06-25 21:21:56 +00002728 /// more specific than id.
Steve Naroff14108da2009-07-10 23:34:53 +00002729 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2730 if (const ObjCObjectPointerType *PT = RetTy->getAsObjCObjectPointerType())
2731 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2732 PT->isObjCClassType()) {
2733 // At this point we know the return type of the message expression is
2734 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2735 // is a call to a class method whose type we can resolve. In such
2736 // cases, promote the return type to XXX* (where XXX is the class).
2737 const ObjCInterfaceDecl *D = ME->getClassInfo().first;
2738 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2739 }
Ted Kremenek553cf182008-06-25 21:21:56 +00002740
Steve Naroff14108da2009-07-10 23:34:53 +00002741 return RetTy;
Ted Kremenek553cf182008-06-25 21:21:56 +00002742}
2743
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002744void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002745 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002746 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002747 Expr* Ex,
2748 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00002749 const RetainSummary& Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00002750 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002751 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002752
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002753 // Get the state.
Ted Kremenekb65be702009-06-18 01:23:53 +00002754 const GRState *state = Builder.GetState(Pred);
Ted Kremenek14993892008-05-06 02:41:27 +00002755
2756 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002757 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002758 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002759 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00002760 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002761
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002762 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002763 SVal V = state->getSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00002764 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002765
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002766 if (Sym)
Ted Kremenekb65be702009-06-18 01:23:53 +00002767 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002768 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002769 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002770 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002771 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002772 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00002773 }
2774 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002775 }
Ted Kremenek070a8252008-07-09 18:11:16 +00002776
Ted Kremenek94c96982009-03-03 22:06:47 +00002777 if (isa<Loc>(V)) {
2778 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002779 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenek070a8252008-07-09 18:11:16 +00002780 continue;
2781
Ted Kremenek6c07bdb2009-06-26 00:05:51 +00002782 // Invalidate the value of the variable passed by reference.
Ted Kremenek070a8252008-07-09 18:11:16 +00002783
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002784 // FIXME: We can have collisions on the conjured symbol if the
2785 // expression *I also creates conjured symbols. We probably want
2786 // to identify conjured symbols by an expression pair: the enclosing
2787 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00002788 // disambiguate conjured symbols.
Zhongxing Xua03f1572009-06-29 06:43:40 +00002789 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu313b6da2009-07-06 06:01:24 +00002790 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
Ted Kremenek109bf472009-05-11 22:55:17 +00002791
Zhongxing Xu313b6da2009-07-06 06:01:24 +00002792 const MemRegion *R = MR->getRegion();
2793 // Are we dealing with an ElementRegion? If the element type is
2794 // a basic integer type (e.g., char, int) and the underying region
2795 // is a variable region then strip off the ElementRegion.
2796 // FIXME: We really need to think about this for the general case
2797 // as sometimes we are reasoning about arrays and other times
2798 // about (char*), etc., is just a form of passing raw bytes.
2799 // e.g., void *p = alloca(); foo((char*)p);
2800 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2801 // Checking for 'integral type' is probably too promiscuous, but
2802 // we'll leave it in for now until we have a systematic way of
2803 // handling all of these cases. Eventually we need to come up
2804 // with an interface to StoreManager so that this logic can be
2805 // approriately delegated to the respective StoreManagers while
2806 // still allowing us to do checker-specific logic (e.g.,
2807 // invalidating reference counts), probably via callbacks.
2808 if (ER->getElementType()->isIntegralType()) {
2809 const MemRegion *superReg = ER->getSuperRegion();
2810 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2811 isa<ObjCIvarRegion>(superReg))
2812 R = cast<TypedRegion>(superReg);
Ted Kremenek42530512009-05-06 18:19:24 +00002813 }
Zhongxing Xu313b6da2009-07-06 06:01:24 +00002814 // FIXME: What about layers of ElementRegions?
2815 }
Zhongxing Xua03f1572009-06-29 06:43:40 +00002816
Zhongxing Xu313b6da2009-07-06 06:01:24 +00002817 // Is the invalidated variable something that we were tracking?
2818 SymbolRef Sym = state->getSValAsScalarOrLoc(R).getAsLocSymbol();
2819
2820 // Remove any existing reference-count binding.
2821 if (Sym)
2822 state = state->remove<RefBindings>(Sym);
2823
2824 state = StoreMgr.InvalidateRegion(state, R, *I, Count);
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002825 }
2826 else {
2827 // Nuke all other arguments passed by reference.
Zhongxing Xu313b6da2009-07-06 06:01:24 +00002828 // FIXME: is this necessary or correct? unbind only removes the binding.
2829 // We should bind it to UnknownVal explicitly. Otherwise default value
2830 // may be loaded.
Ted Kremenekb65be702009-06-18 01:23:53 +00002831 state = state->unbindLoc(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002832 }
Ted Kremenekb8873552008-04-11 20:51:02 +00002833 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002834 else if (isa<nonloc::LocAsInteger>(V))
Zhongxing Xu313b6da2009-07-06 06:01:24 +00002835 // FIXME: is this necessary or correct? unbind only removes the binding.
2836 // We should bind it to UnknownVal explicitly. Otherwise default value
2837 // may be loaded.
Ted Kremenekb65be702009-06-18 01:23:53 +00002838 state = state->unbindLoc(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002839 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002840
Ted Kremenek553cf182008-06-25 21:21:56 +00002841 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00002842 if (!ErrorExpr && Receiver) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002843 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002844 if (Sym) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002845 if (const RefVal* T = state->get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002846 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002847 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00002848 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002849 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00002850 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002851 }
Ted Kremenek14993892008-05-06 02:41:27 +00002852 }
2853 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002854
Ted Kremenek553cf182008-06-25 21:21:56 +00002855 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002856 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002857 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002858 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002859 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002860 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002861
Ted Kremenek70a733e2008-07-18 17:24:20 +00002862 // Consult the summary for the return value.
Ted Kremenek7faca822009-05-04 04:57:00 +00002863 RetEffect RE = Summ.getRetEffect();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002864
Ted Kremenek78a35a32009-05-12 20:06:54 +00002865 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2866 assert(Receiver);
Ted Kremenekb65be702009-06-18 01:23:53 +00002867 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek78a35a32009-05-12 20:06:54 +00002868 bool found = false;
2869 if (SymbolRef Sym = V.getAsLocSymbol())
Ted Kremenekb65be702009-06-18 01:23:53 +00002870 if (state->get<RefBindings>(Sym)) {
Ted Kremenek78a35a32009-05-12 20:06:54 +00002871 found = true;
2872 RE = Summaries.getObjAllocRetEffect();
2873 }
2874
2875 if (!found)
2876 RE = RetEffect::MakeNoRet();
2877 }
2878
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002879 switch (RE.getKind()) {
2880 default:
2881 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002882
Ted Kremenek6c07bdb2009-06-26 00:05:51 +00002883 case RetEffect::NoRet: {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002884 // Make up a symbol for the return value (not reference counted).
Ted Kremenek6c07bdb2009-06-26 00:05:51 +00002885 // FIXME: Most of this logic is not specific to the retain/release
2886 // checker.
Ted Kremenekf9561e52008-04-11 20:23:24 +00002887
Ted Kremenekfd301942008-10-17 22:23:12 +00002888 // FIXME: We eventually should handle structs and other compound types
2889 // that are returned by value.
2890
2891 QualType T = Ex->getType();
2892
Ted Kremenek062e2f92008-11-13 06:10:40 +00002893 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002894 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002895 ValueManager &ValMgr = Eng.getValueManager();
2896 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenekb65be702009-06-18 01:23:53 +00002897 state = state->bindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00002898 }
2899
Ted Kremenek940b1d82008-04-10 23:44:06 +00002900 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00002901 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002902
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002903 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00002904 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00002905 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002906 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb65be702009-06-18 01:23:53 +00002907 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
2908 state = state->bindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002909 break;
2910 }
2911
Ted Kremenek14993892008-05-06 02:41:27 +00002912 case RetEffect::ReceiverAlias: {
2913 assert (Receiver);
Ted Kremenekb65be702009-06-18 01:23:53 +00002914 SVal V = state->getSValAsScalarOrLoc(Receiver);
2915 state = state->bindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00002916 break;
2917 }
2918
Ted Kremeneka7344702008-06-23 18:02:52 +00002919 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002920 case RetEffect::OwnedSymbol: {
2921 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002922 ValueManager &ValMgr = Eng.getValueManager();
2923 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2924 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekb65be702009-06-18 01:23:53 +00002925 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
Ted Kremenek044b6f02009-04-09 16:13:17 +00002926 RetT));
Zhongxing Xud91ee272009-06-23 09:02:15 +00002927 state = state->bindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002928
2929 // FIXME: Add a flag to the checker where allocations are assumed to
2930 // *not fail.
2931#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00002932 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2933 bool isFeasible;
2934 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2935 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2936 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002937#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00002938
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002939 break;
2940 }
Ted Kremeneke798e7c2009-04-27 19:14:45 +00002941
2942 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002943 case RetEffect::NotOwnedSymbol: {
2944 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002945 ValueManager &ValMgr = Eng.getValueManager();
2946 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2947 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekb65be702009-06-18 01:23:53 +00002948 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
Ted Kremenek044b6f02009-04-09 16:13:17 +00002949 RetT));
Zhongxing Xud91ee272009-06-23 09:02:15 +00002950 state = state->bindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002951 break;
2952 }
2953 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002954
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002955 // Generate a sink node if we are at the end of a path.
2956 GRExprEngine::NodeTy *NewNode =
Ted Kremenek7faca822009-05-04 04:57:00 +00002957 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2958 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002959
2960 // Annotate the edge with summary we used.
Ted Kremenek7faca822009-05-04 04:57:00 +00002961 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002962}
2963
2964
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002965void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002966 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002967 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002968 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002969 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00002970 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek7faca822009-05-04 04:57:00 +00002971 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xu369f4472009-04-20 05:24:46 +00002972 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002973
Ted Kremenek7faca822009-05-04 04:57:00 +00002974 assert(Summ);
2975 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002976 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002977}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002978
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002979void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00002980 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002981 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00002982 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002983 ExplodedNode<GRState>* Pred) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002984 RetainSummary* Summ = 0;
Ted Kremenek9040c652008-05-01 21:31:50 +00002985
Ted Kremenek553cf182008-06-25 21:21:56 +00002986 if (Expr* Receiver = ME->getReceiver()) {
2987 // We need the type-information of the tracked receiver object
2988 // Retrieve it from the state.
Ted Kremenek70b6a832009-05-13 18:16:01 +00002989 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek553cf182008-06-25 21:21:56 +00002990
2991 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2992 // a chain of lookups.
Ted Kremenek8711c032009-04-29 05:04:30 +00002993 // FIXME: Is this really working as expected? There are cases where
2994 // we just use the 'ID' from the message expression.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002995 const GRState* St = Builder.GetState(Pred);
Ted Kremenek23ec48c2009-06-18 23:58:37 +00002996 SVal V = St->getSValAsScalarOrLoc(Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00002997
Ted Kremenek94c96982009-03-03 22:06:47 +00002998 SymbolRef Sym = V.getAsLocSymbol();
Steve Naroff14108da2009-07-10 23:34:53 +00002999
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00003000 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003001 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Steve Naroff14108da2009-07-10 23:34:53 +00003002 if (const ObjCObjectPointerType* PT =
3003 T->getType()->getAsObjCObjectPointerType())
3004 ID = PT->getInterfaceDecl();
Ted Kremenek553cf182008-06-25 21:21:56 +00003005 }
3006 }
Ted Kremenek70b6a832009-05-13 18:16:01 +00003007
3008 // FIXME: this is a hack. This may or may not be the actual method
3009 // that is called.
3010 if (!ID) {
Steve Naroff14108da2009-07-10 23:34:53 +00003011 if (const ObjCObjectPointerType *PT =
3012 Receiver->getType()->getAsObjCObjectPointerType())
3013 ID = PT->getInterfaceDecl();
Ted Kremenek70b6a832009-05-13 18:16:01 +00003014 }
3015
Ted Kremenekce8a41d2009-04-29 17:09:14 +00003016 // FIXME: The receiver could be a reference to a class, meaning that
3017 // we should use the class method.
3018 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00003019
Ted Kremenek896cd9d2008-10-23 01:56:15 +00003020 // Special-case: are we sending a mesage to "self"?
3021 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek885c27b2009-05-04 05:31:22 +00003022 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
3023 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenek23ec48c2009-06-18 23:58:37 +00003024 SVal X = St->getSValAsScalarOrLoc(Receiver);
Ted Kremenek885c27b2009-05-04 05:31:22 +00003025 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek5e77eba2009-07-29 18:17:40 +00003026 if (L->getBaseRegion() == St->getSelfRegion()) {
Ted Kremenek885c27b2009-05-04 05:31:22 +00003027 // Update the summary to make the default argument effect
3028 // 'StopTracking'.
3029 Summ = Summaries.copySummary(Summ);
3030 Summ->setDefaultArgEffect(StopTracking);
3031 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00003032 }
3033 }
Ted Kremenek553cf182008-06-25 21:21:56 +00003034 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003035 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00003036 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003037
Ted Kremenek7faca822009-05-04 04:57:00 +00003038 if (!Summ)
3039 Summ = Summaries.getDefaultSummary();
Ted Kremenekde4d5332009-04-24 17:50:11 +00003040
Ted Kremenek7faca822009-05-04 04:57:00 +00003041 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenekb3095252008-05-06 04:20:12 +00003042 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00003043}
Ted Kremenek5216ad72009-02-14 03:16:10 +00003044
3045namespace {
3046class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
Ted Kremenek3a772032009-06-18 00:49:02 +00003047 const GRState *state;
Ted Kremenek5216ad72009-02-14 03:16:10 +00003048public:
Ted Kremenek3a772032009-06-18 00:49:02 +00003049 StopTrackingCallback(const GRState *st) : state(st) {}
3050 const GRState *getState() const { return state; }
Ted Kremenek5216ad72009-02-14 03:16:10 +00003051
3052 bool VisitSymbol(SymbolRef sym) {
Ted Kremenek3a772032009-06-18 00:49:02 +00003053 state = state->remove<RefBindings>(sym);
Ted Kremenek5216ad72009-02-14 03:16:10 +00003054 return true;
3055 }
Ted Kremenek5216ad72009-02-14 03:16:10 +00003056};
3057} // end anonymous namespace
3058
3059
Ted Kremenek41573eb2009-02-14 01:43:44 +00003060void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00003061 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00003062 bool escapes = false;
3063
Ted Kremeneka496d162008-10-18 03:49:51 +00003064 // A value escapes in three possible cases (this may change):
3065 //
3066 // (1) we are binding to something that is not a memory region.
3067 // (2) we are binding to a memregion that does not have stack storage
3068 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00003069 // does not understand.
Ted Kremenek3a772032009-06-18 00:49:02 +00003070 const GRState *state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00003071
Ted Kremenek41573eb2009-02-14 01:43:44 +00003072 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00003073 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00003074 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00003075 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
Ted Kremenekea20cd72009-06-23 18:05:21 +00003076 escapes = !R->hasStackStorage();
Ted Kremeneka496d162008-10-18 03:49:51 +00003077
3078 if (!escapes) {
3079 // To test (3), generate a new state with the binding removed. If it is
3080 // the same state, then it escapes (since the store cannot represent
3081 // the binding).
Ted Kremenekb65be702009-06-18 01:23:53 +00003082 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00003083 }
Ted Kremenek9e240492008-10-04 05:50:14 +00003084 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00003085
Ted Kremenek5216ad72009-02-14 03:16:10 +00003086 // If our store can represent the binding and we aren't storing to something
3087 // that doesn't have local storage then just return and have the simulation
3088 // state continue as is.
3089 if (!escapes)
3090 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00003091
Ted Kremenek5216ad72009-02-14 03:16:10 +00003092 // Otherwise, find all symbols referenced by 'val' that we are tracking
3093 // and stop tracking them.
Ted Kremenek3a772032009-06-18 00:49:02 +00003094 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00003095}
3096
Ted Kremenek4fd88972008-04-17 18:12:53 +00003097 // Return statements.
3098
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003099void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00003100 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003101 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00003102 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003103 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003104
3105 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00003106 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00003107 return;
3108
Ted Kremenekb65be702009-06-18 01:23:53 +00003109 const GRState *state = Builder.GetState(Pred);
3110 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00003111
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00003112 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00003113 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003114
Ted Kremenek4fd88972008-04-17 18:12:53 +00003115 // Get the reference count binding (if any).
Ted Kremenekb65be702009-06-18 01:23:53 +00003116 const RefVal* T = state->get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00003117
3118 if (!T)
3119 return;
3120
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003121 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00003122 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003123
Ted Kremenek78a35a32009-05-12 20:06:54 +00003124 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003125 case RefVal::Owned: {
3126 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003127 assert (cnt > 0);
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003128 X.setCount(cnt - 1);
3129 X = X ^ RefVal::ReturnedOwned;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003130 break;
3131 }
3132
3133 case RefVal::NotOwned: {
3134 unsigned cnt = X.getCount();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003135 if (cnt) {
3136 X.setCount(cnt - 1);
3137 X = X ^ RefVal::ReturnedOwned;
3138 }
3139 else {
3140 X = X ^ RefVal::ReturnedNotOwned;
3141 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003142 break;
3143 }
3144
3145 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00003146 return;
3147 }
3148
3149 // Update the binding.
Ted Kremenekb65be702009-06-18 01:23:53 +00003150 state = state->set<RefBindings>(Sym, X);
Ted Kremenekc887d132009-04-29 18:50:19 +00003151 Pred = Builder.MakeNode(Dst, S, Pred, state);
3152
Ted Kremenek9f246b62009-04-30 05:51:50 +00003153 // Did we cache out?
3154 if (!Pred)
3155 return;
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003156
3157 // Update the autorelease counts.
3158 static unsigned autoreleasetag = 0;
3159 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3160 bool stop = false;
3161 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3162 X, stop);
3163
3164 // Did we cache out?
3165 if (!Pred || stop)
3166 return;
3167
3168 // Get the updated binding.
Ted Kremenekb65be702009-06-18 01:23:53 +00003169 T = state->get<RefBindings>(Sym);
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003170 assert(T);
3171 X = *T;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003172
Ted Kremenekc887d132009-04-29 18:50:19 +00003173 // Any leaks or other errors?
3174 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003175 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremeneka8833552009-04-29 23:03:22 +00003176 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00003177 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003178 RetEffect RE = Summ.getRetEffect();
3179 bool hasError = false;
3180
Ted Kremenekfae664a2009-05-16 01:38:01 +00003181 if (RE.getKind() != RetEffect::NoRet) {
3182 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3183 // Things are more complicated with garbage collection. If the
3184 // returned object is suppose to be an Objective-C object, we have
3185 // a leak (as the caller expects a GC'ed object) because no
3186 // method should return ownership unless it returns a CF object.
3187 X = X ^ RefVal::ErrorGCLeakReturned;
3188
3189 // Keep this false until this is properly tested.
3190 hasError = true;
3191 }
3192 else if (!RE.isOwned()) {
3193 // Either we are using GC and the returned object is a CF type
3194 // or we aren't using GC. In either case, we expect that the
3195 // enclosing method is expected to return ownership.
3196 hasError = true;
3197 X = X ^ RefVal::ErrorLeakReturned;
3198 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003199 }
3200
3201 if (hasError) {
Ted Kremenekc887d132009-04-29 18:50:19 +00003202 // Generate an error node.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003203 static int ReturnOwnLeakTag = 0;
Ted Kremenekb65be702009-06-18 01:23:53 +00003204 state = state->set<RefBindings>(Sym, X);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003205 ExplodedNode<GRState> *N =
3206 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3207 if (N) {
3208 CFRefReport *report =
Ted Kremenek9f246b62009-04-30 05:51:50 +00003209 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3210 N, Sym, Eng);
3211 BR->EmitReport(report);
3212 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003213 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003214 }
3215 }
3216 else if (X.isReturnedNotOwned()) {
3217 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3218 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3219 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3220 if (Summ.getRetEffect().isOwned()) {
3221 // Trying to return a not owned object to a caller expecting an
3222 // owned object.
3223
3224 static int ReturnNotOwnedForOwnedTag = 0;
Ted Kremenekb65be702009-06-18 01:23:53 +00003225 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003226 if (ExplodedNode<GRState> *N =
3227 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3228 state, Pred)) {
3229 CFRefReport *report =
3230 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3231 *this, N, Sym);
3232 BR->EmitReport(report);
3233 }
3234 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003235 }
3236 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003237}
3238
Ted Kremenekcb612922008-04-18 19:23:43 +00003239// Assumptions.
3240
Ted Kremeneka591bc02009-06-18 22:57:13 +00003241const GRState* CFRefCount::EvalAssume(const GRState *state,
3242 SVal Cond, bool Assumption) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003243
3244 // FIXME: We may add to the interface of EvalAssume the list of symbols
3245 // whose assumptions have changed. For now we just iterate through the
3246 // bindings and check if any of the tracked symbols are NULL. This isn't
3247 // too bad since the number of symbols we will track in practice are
3248 // probably small and EvalAssume is only called at branches and a few
3249 // other places.
Ted Kremenekb65be702009-06-18 01:23:53 +00003250 RefBindings B = state->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003251
3252 if (B.isEmpty())
Ted Kremenekb65be702009-06-18 01:23:53 +00003253 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003254
Ted Kremenekb65be702009-06-18 01:23:53 +00003255 bool changed = false;
3256 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003257
3258 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003259 // Check if the symbol is null (or equal to any constant).
3260 // If this is the case, stop tracking the symbol.
Ted Kremeneka591bc02009-06-18 22:57:13 +00003261 if (state->getSymVal(I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003262 changed = true;
3263 B = RefBFactory.Remove(B, I.getKey());
3264 }
3265 }
3266
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003267 if (changed)
Ted Kremenekb65be702009-06-18 01:23:53 +00003268 state = state->set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00003269
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003270 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003271}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003272
Ted Kremenekb65be702009-06-18 01:23:53 +00003273const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003274 RefVal V, ArgEffect E,
3275 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00003276
3277 // In GC mode [... release] and [... retain] do nothing.
3278 switch (E) {
3279 default: break;
3280 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3281 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00003282 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00003283 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3284 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003285 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003286
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003287 // Handle all use-after-releases.
3288 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3289 V = V ^ RefVal::ErrorUseAfterRelease;
3290 hasErr = V.getKind();
Ted Kremenekb65be702009-06-18 01:23:53 +00003291 return state->set<RefBindings>(sym, V);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003292 }
3293
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003294 switch (E) {
3295 default:
3296 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003297
3298 case Dealloc:
3299 // Any use of -dealloc in GC is *bad*.
3300 if (isGCEnabled()) {
3301 V = V ^ RefVal::ErrorDeallocGC;
3302 hasErr = V.getKind();
3303 break;
3304 }
3305
3306 switch (V.getKind()) {
3307 default:
3308 assert(false && "Invalid case.");
3309 case RefVal::Owned:
3310 // The object immediately transitions to the released state.
3311 V = V ^ RefVal::Released;
3312 V.clearCounts();
Ted Kremenekb65be702009-06-18 01:23:53 +00003313 return state->set<RefBindings>(sym, V);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003314 case RefVal::NotOwned:
3315 V = V ^ RefVal::ErrorDeallocNotOwned;
3316 hasErr = V.getKind();
3317 break;
3318 }
3319 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003320
Ted Kremenek35790732009-02-25 23:11:49 +00003321 case NewAutoreleasePool:
3322 assert(!isGCEnabled());
Ted Kremenekb65be702009-06-18 01:23:53 +00003323 return state->add<AutoreleaseStack>(sym);
Ted Kremenek35790732009-02-25 23:11:49 +00003324
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003325 case MayEscape:
3326 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00003327 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003328 break;
3329 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003330
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003331 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00003332
Ted Kremenek070a8252008-07-09 18:11:16 +00003333 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003334 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003335 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00003336
Ted Kremenekabf43972009-01-28 21:44:40 +00003337 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003338 if (isGCEnabled())
3339 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00003340
3341 // Update the autorelease counts.
3342 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf21332e2009-05-08 20:01:42 +00003343 V = V.autorelease();
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003344 break;
Ted Kremenek369de562009-05-09 00:10:05 +00003345
Ted Kremenek14993892008-05-06 02:41:27 +00003346 case StopTracking:
Ted Kremenekb65be702009-06-18 01:23:53 +00003347 return state->remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003348
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003349 case IncRef:
3350 switch (V.getKind()) {
3351 default:
3352 assert(false);
3353
3354 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003355 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00003356 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003357 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003358 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003359 // Non-GC cases are handled above.
3360 assert(isGCEnabled());
3361 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003362 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003363 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003364 break;
3365
Ted Kremenek553cf182008-06-25 21:21:56 +00003366 case SelfOwn:
3367 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003368 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003369 case DecRef:
3370 switch (V.getKind()) {
3371 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003372 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003373 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003374
Ted Kremenek553cf182008-06-25 21:21:56 +00003375 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00003376 assert(V.getCount() > 0);
3377 if (V.getCount() == 1) V = V ^ RefVal::Released;
3378 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003379 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003380
Ted Kremenek553cf182008-06-25 21:21:56 +00003381 case RefVal::NotOwned:
3382 if (V.getCount() > 0)
3383 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00003384 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00003385 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003386 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00003387 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003388 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003389
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003390 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003391 // Non-GC cases are handled above.
3392 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00003393 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003394 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003395 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003396 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003397 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003398 }
Ted Kremenekb65be702009-06-18 01:23:53 +00003399 return state->set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003400}
3401
Ted Kremenekfa34b332008-04-09 01:10:13 +00003402//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003403// Handle dead symbols and end-of-path.
3404//===----------------------------------------------------------------------===//
3405
Ted Kremenekb65be702009-06-18 01:23:53 +00003406std::pair<ExplodedNode<GRState>*, const GRState *>
3407CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Ted Kremenekf04dced2009-05-08 23:32:51 +00003408 ExplodedNode<GRState>* Pred,
Ted Kremenek369de562009-05-09 00:10:05 +00003409 GRExprEngine &Eng,
3410 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekf04dced2009-05-08 23:32:51 +00003411
Ted Kremenek369de562009-05-09 00:10:05 +00003412 unsigned ACnt = V.getAutoreleaseCount();
3413 stop = false;
3414
3415 // No autorelease counts? Nothing to be done.
3416 if (!ACnt)
3417 return std::make_pair(Pred, state);
3418
3419 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3420 unsigned Cnt = V.getCount();
3421
Ted Kremenek95d3b902009-05-11 15:26:06 +00003422 // FIXME: Handle sending 'autorelease' to already released object.
3423
3424 if (V.getKind() == RefVal::ReturnedOwned)
3425 ++Cnt;
3426
Ted Kremenek369de562009-05-09 00:10:05 +00003427 if (ACnt <= Cnt) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003428 if (ACnt == Cnt) {
3429 V.clearCounts();
Ted Kremenek95d3b902009-05-11 15:26:06 +00003430 if (V.getKind() == RefVal::ReturnedOwned)
3431 V = V ^ RefVal::ReturnedNotOwned;
3432 else
3433 V = V ^ RefVal::NotOwned;
Ted Kremenek80c24182009-05-09 00:44:07 +00003434 }
Ted Kremenek95d3b902009-05-11 15:26:06 +00003435 else {
Ted Kremenek80c24182009-05-09 00:44:07 +00003436 V.setCount(Cnt - ACnt);
3437 V.setAutoreleaseCount(0);
3438 }
Ted Kremenekb65be702009-06-18 01:23:53 +00003439 state = state->set<RefBindings>(Sym, V);
Ted Kremenek369de562009-05-09 00:10:05 +00003440 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3441 stop = (N == 0);
3442 return std::make_pair(N, state);
3443 }
3444
3445 // Woah! More autorelease counts then retain counts left.
3446 // Emit hard error.
3447 stop = true;
3448 V = V ^ RefVal::ErrorOverAutorelease;
Ted Kremenekb65be702009-06-18 01:23:53 +00003449 state = state->set<RefBindings>(Sym, V);
Ted Kremenek369de562009-05-09 00:10:05 +00003450
3451 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003452 N->markAsSink();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003453
3454 std::string sbuf;
3455 llvm::raw_string_ostream os(sbuf);
Ted Kremenekdaec1452009-05-15 06:02:08 +00003456 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003457 if (V.getAutoreleaseCount() > 1)
3458 os << V.getAutoreleaseCount() << " times";
3459 os << " but the object has ";
3460 if (V.getCount() == 0)
3461 os << "zero (locally visible)";
3462 else
3463 os << "+" << V.getCount();
3464 os << " retain counts";
3465
Ted Kremenek369de562009-05-09 00:10:05 +00003466 CFRefReport *report =
3467 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003468 *this, N, Sym, os.str().c_str());
Ted Kremenek369de562009-05-09 00:10:05 +00003469 BR->EmitReport(report);
3470 }
3471
3472 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekf04dced2009-05-08 23:32:51 +00003473}
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003474
Ted Kremenekb65be702009-06-18 01:23:53 +00003475const GRState *
3476CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003477 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3478
3479 bool hasLeak = V.isOwned() ||
3480 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3481
3482 if (!hasLeak)
Ted Kremenekb65be702009-06-18 01:23:53 +00003483 return state->remove<RefBindings>(sid);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003484
3485 Leaked.push_back(sid);
Ted Kremenekb65be702009-06-18 01:23:53 +00003486 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003487}
3488
3489ExplodedNode<GRState>*
Ted Kremenekb65be702009-06-18 01:23:53 +00003490CFRefCount::ProcessLeaks(const GRState * state,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003491 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3492 GenericNodeBuilder &Builder,
3493 GRExprEngine& Eng,
3494 ExplodedNode<GRState> *Pred) {
3495
3496 if (Leaked.empty())
3497 return Pred;
3498
Ted Kremenekf04dced2009-05-08 23:32:51 +00003499 // Generate an intermediate node representing the leak point.
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003500 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003501
3502 if (N) {
3503 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3504 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3505
3506 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3507 : leakAtReturn);
3508 assert(BT && "BugType not initialized.");
3509 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3510 BR->EmitReport(report);
3511 }
3512 }
3513
3514 return N;
3515}
3516
Ted Kremenekcf701772009-02-05 06:50:21 +00003517void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3518 GREndPathNodeBuilder<GRState>& Builder) {
3519
Ted Kremenekb65be702009-06-18 01:23:53 +00003520 const GRState *state = Builder.getState();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003521 GenericNodeBuilder Bd(Builder);
Ted Kremenekb65be702009-06-18 01:23:53 +00003522 RefBindings B = state->get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003523 ExplodedNode<GRState> *Pred = 0;
3524
3525 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek369de562009-05-09 00:10:05 +00003526 bool stop = false;
3527 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3528 (*I).first,
3529 (*I).second, stop);
3530
3531 if (stop)
3532 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003533 }
3534
Ted Kremenekb65be702009-06-18 01:23:53 +00003535 B = state->get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003536 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003537
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003538 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3539 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3540
Ted Kremenekf04dced2009-05-08 23:32:51 +00003541 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003542}
3543
3544void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3545 GRExprEngine& Eng,
3546 GRStmtNodeBuilder<GRState>& Builder,
3547 ExplodedNode<GRState>* Pred,
3548 Stmt* S,
Ted Kremenekb65be702009-06-18 01:23:53 +00003549 const GRState* state,
Ted Kremenekcf701772009-02-05 06:50:21 +00003550 SymbolReaper& SymReaper) {
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003551
Ted Kremenekb65be702009-06-18 01:23:53 +00003552 RefBindings B = state->get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003553
3554 // Update counts from autorelease pools
3555 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3556 E = SymReaper.dead_end(); I != E; ++I) {
3557 SymbolRef Sym = *I;
3558 if (const RefVal* T = B.lookup(Sym)){
3559 // Use the symbol as the tag.
3560 // FIXME: This might not be as unique as we would like.
3561 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek369de562009-05-09 00:10:05 +00003562 bool stop = false;
3563 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3564 Sym, *T, stop);
3565 if (stop)
3566 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003567 }
3568 }
3569
Ted Kremenekb65be702009-06-18 01:23:53 +00003570 B = state->get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003571 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003572
3573 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003574 E = SymReaper.dead_end(); I != E; ++I) {
3575 if (const RefVal* T = B.lookup(*I))
3576 state = HandleSymbolDeath(state, *I, *T, Leaked);
3577 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003578
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003579 static unsigned LeakPPTag = 0;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003580 {
3581 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3582 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3583 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003584
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003585 // Did we cache out?
3586 if (!Pred)
3587 return;
Ted Kremenek33b6f632009-02-19 23:47:02 +00003588
3589 // Now generate a new node that nukes the old bindings.
Ted Kremenekb65be702009-06-18 01:23:53 +00003590 RefBindings::Factory& F = state->get_context<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003591
Ted Kremenek33b6f632009-02-19 23:47:02 +00003592 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003593 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3594
Ted Kremenekb65be702009-06-18 01:23:53 +00003595 state = state->set<RefBindings>(B);
Ted Kremenek33b6f632009-02-19 23:47:02 +00003596 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003597}
3598
3599void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3600 GRStmtNodeBuilder<GRState>& Builder,
3601 Expr* NodeExpr, Expr* ErrorExpr,
3602 ExplodedNode<GRState>* Pred,
3603 const GRState* St,
3604 RefVal::Kind hasErr, SymbolRef Sym) {
3605 Builder.BuildSinks = true;
3606 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3607
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003608 if (!N)
3609 return;
Ted Kremenekcf701772009-02-05 06:50:21 +00003610
3611 CFRefBug *BT = 0;
3612
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003613 switch (hasErr) {
3614 default:
3615 assert(false && "Unhandled error.");
3616 return;
3617 case RefVal::ErrorUseAfterRelease:
3618 BT = static_cast<CFRefBug*>(useAfterRelease);
3619 break;
3620 case RefVal::ErrorReleaseNotOwned:
3621 BT = static_cast<CFRefBug*>(releaseNotOwned);
3622 break;
3623 case RefVal::ErrorDeallocGC:
3624 BT = static_cast<CFRefBug*>(deallocGC);
3625 break;
3626 case RefVal::ErrorDeallocNotOwned:
3627 BT = static_cast<CFRefBug*>(deallocNotOwned);
3628 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003629 }
3630
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003631 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003632 report->addRange(ErrorExpr->getSourceRange());
3633 BR->EmitReport(report);
3634}
3635
3636//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003637// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003638//===----------------------------------------------------------------------===//
3639
Ted Kremenek072192b2008-04-30 23:47:44 +00003640GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3641 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003642 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003643}