blob: 3cca482633caf28ed3e45e8a8869c78d6d563b48 [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
47// begins with “alloc” or “new” or contains “copy” (for example, alloc,
48// 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*?
251 const PointerType* PT = RetTy->getAsPointerType();
252 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() {}
499
500 typedef MapTy::iterator iterator;
501
Ted Kremeneka8833552009-04-29 23:03:22 +0000502 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
503 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000504 // Lookup the method using the decl for the class @interface. If we
505 // have no decl, lookup using the class name.
506 return D ? find(D, S) : find(ClsName, S);
507 }
508
Ted Kremeneka8833552009-04-29 23:03:22 +0000509 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000510 // Do a lookup with the (D,S) pair. If we find a match return
511 // the iterator.
512 ObjCSummaryKey K(D, S);
513 MapTy::iterator I = M.find(K);
514
515 if (I != M.end() || !D)
516 return I;
517
518 // Walk the super chain. If we find a hit with a parent, we'll end
519 // up returning that summary. We actually allow that key (null,S), as
520 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
521 // generate initial summaries without having to worry about NSObject
522 // being declared.
523 // FIXME: We may change this at some point.
524 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
525 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
526 break;
527
528 if (!C)
529 return I;
530 }
531
532 // Cache the summary with original key to make the next lookup faster
533 // and return the iterator.
534 M[K] = I->second;
535 return I;
536 }
537
Ted Kremenek98530452008-08-12 20:41:56 +0000538
Ted Kremenek553cf182008-06-25 21:21:56 +0000539 iterator find(Expr* Receiver, Selector S) {
540 return find(getReceiverDecl(Receiver), S);
541 }
542
543 iterator find(IdentifierInfo* II, Selector S) {
544 // FIXME: Class method lookup. Right now we dont' have a good way
545 // of going between IdentifierInfo* and the class hierarchy.
546 iterator I = M.find(ObjCSummaryKey(II, S));
547 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
548 }
549
550 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
551
552 const PointerType* PT = E->getType()->getAsPointerType();
553 if (!PT) return 0;
554
555 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
556 if (!OI) return 0;
557
558 return OI ? OI->getDecl() : 0;
559 }
560
561 iterator end() { return M.end(); }
562
563 RetainSummary*& operator[](ObjCMessageExpr* ME) {
564
565 Selector S = ME->getSelector();
566
567 if (Expr* Receiver = ME->getReceiver()) {
568 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
569 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
570 }
571
572 return M[ObjCSummaryKey(ME->getClassName(), S)];
573 }
574
575 RetainSummary*& operator[](ObjCSummaryKey K) {
576 return M[K];
577 }
578
579 RetainSummary*& operator[](Selector S) {
580 return M[ ObjCSummaryKey(S) ];
581 }
582};
583} // end anonymous namespace
584
585//===----------------------------------------------------------------------===//
586// Data structures for managing collections of summaries.
587//===----------------------------------------------------------------------===//
588
589namespace {
590class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000591
592 //==-----------------------------------------------------------------==//
593 // Typedefs.
594 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000595
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000596 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
597 FuncSummariesTy;
598
Ted Kremenek4f22a782008-06-23 23:30:29 +0000599 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000600
601 //==-----------------------------------------------------------------==//
602 // Data.
603 //==-----------------------------------------------------------------==//
604
Ted Kremenek553cf182008-06-25 21:21:56 +0000605 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000606 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000607
Ted Kremenek070a8252008-07-09 18:11:16 +0000608 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
609 /// "CFDictionaryCreate".
610 IdentifierInfo* CFDictionaryCreateII;
611
Ted Kremenek553cf182008-06-25 21:21:56 +0000612 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000613 const bool GCEnabled;
Ted Kremenek22fe2482009-05-04 04:30:18 +0000614
Ted Kremenek553cf182008-06-25 21:21:56 +0000615 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000616 FuncSummariesTy FuncSummaries;
617
Ted Kremenek553cf182008-06-25 21:21:56 +0000618 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
619 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000620 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000621
Ted Kremenek553cf182008-06-25 21:21:56 +0000622 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000623 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000624
Ted Kremenek553cf182008-06-25 21:21:56 +0000625 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
626 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000627 llvm::BumpPtrAllocator BPAlloc;
628
Ted Kremenekb77449c2009-05-03 05:20:50 +0000629 /// AF - A factory for ArgEffects objects.
630 ArgEffects::Factory AF;
631
Ted Kremenek553cf182008-06-25 21:21:56 +0000632 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000633 ArgEffects ScratchArgs;
634
Ted Kremenekec315332009-05-07 23:40:42 +0000635 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
636 /// objects.
637 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000638
Ted Kremenekb04cb592009-06-11 18:17:24 +0000639 /// ObjCInitRetE - Default return effect for init methods returning Objective-C
Ted Kremenek547d4952009-06-05 23:18:01 +0000640 /// objects.
641 RetEffect ObjCInitRetE;
Ted Kremenekb04cb592009-06-11 18:17:24 +0000642
Ted Kremenek7faca822009-05-04 04:57:00 +0000643 RetainSummary DefaultSummary;
Ted Kremenek432af592008-05-06 18:11:36 +0000644 RetainSummary* StopSummary;
645
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000646 //==-----------------------------------------------------------------==//
647 // Methods.
648 //==-----------------------------------------------------------------==//
649
Ted Kremenek553cf182008-06-25 21:21:56 +0000650 /// getArgEffects - Returns a persistent ArgEffects object based on the
651 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000652 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000653
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000654 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000655
656public:
Ted Kremenek78a35a32009-05-12 20:06:54 +0000657 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
658
Ted Kremenek885c27b2009-05-04 05:31:22 +0000659 RetainSummary *getDefaultSummary() {
660 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
661 return new (Summ) RetainSummary(DefaultSummary);
662 }
Ted Kremenek7faca822009-05-04 04:57:00 +0000663
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000664 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000665
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000666 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
667 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000668 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000669
Ted Kremenekb77449c2009-05-03 05:20:50 +0000670 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000671 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000672 ArgEffect DefaultEff = MayEscape,
673 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000674
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000675 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000676 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000677 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000678 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000679 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000680
Ted Kremenek8711c032009-04-29 05:04:30 +0000681 RetainSummary *getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000682 if (StopSummary)
683 return StopSummary;
684
685 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
686 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000687
Ted Kremenek432af592008-05-06 18:11:36 +0000688 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000689 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000690
Ted Kremenek8711c032009-04-29 05:04:30 +0000691 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000692
Ted Kremenek1f180c32008-06-23 22:21:20 +0000693 void InitializeClassMethodSummaries();
694 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000695
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000696 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek92511432009-05-03 06:08:32 +0000697 bool isTrackedCFObjectType(QualType T);
Ted Kremenek234a4c22009-01-07 00:39:56 +0000698
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000699private:
700
Ted Kremenek70a733e2008-07-18 17:24:20 +0000701 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
702 RetainSummary* Summ) {
703 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
704 }
705
Ted Kremenek553cf182008-06-25 21:21:56 +0000706 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
707 ObjCClassMethodSummaries[S] = Summ;
708 }
709
710 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
711 ObjCMethodSummaries[S] = Summ;
712 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000713
714 void addClassMethSummary(const char* Cls, const char* nullaryName,
715 RetainSummary *Summ) {
716 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
717 Selector S = GetNullarySelector(nullaryName, Ctx);
718 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
719 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000720
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000721 void addInstMethSummary(const char* Cls, const char* nullaryName,
722 RetainSummary *Summ) {
723 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
724 Selector S = GetNullarySelector(nullaryName, Ctx);
725 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
726 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000727
728 Selector generateSelector(va_list argp) {
Ted Kremenek9e476de2008-08-12 18:30:56 +0000729 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000730
Ted Kremenek9e476de2008-08-12 18:30:56 +0000731 while (const char* s = va_arg(argp, const char*))
732 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000733
734 return Ctx.Selectors.getSelector(II.size(), &II[0]);
735 }
736
737 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
738 RetainSummary* Summ, va_list argp) {
739 Selector S = generateSelector(argp);
740 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000741 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000742
743 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
744 va_list argp;
745 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000746 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000747 va_end(argp);
748 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000749
750 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
751 va_list argp;
752 va_start(argp, Summ);
753 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
754 va_end(argp);
755 }
756
757 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
758 va_list argp;
759 va_start(argp, Summ);
760 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
761 va_end(argp);
762 }
763
Ted Kremenek9e476de2008-08-12 18:30:56 +0000764 void addPanicSummary(const char* Cls, ...) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000765 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
766 RetEffect::MakeNoRet(),
Ted Kremenek9e476de2008-08-12 18:30:56 +0000767 DoNothing, DoNothing, true);
768 va_list argp;
769 va_start (argp, Cls);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000770 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000771 va_end(argp);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000772 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000773
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000774public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000775
776 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000777 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000778 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000779 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenekec315332009-05-07 23:40:42 +0000780 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
781 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenekb04cb592009-06-11 18:17:24 +0000782 ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned()
783 : RetEffect::MakeOwnedWhenTrackedReceiver()),
Ted Kremenek7faca822009-05-04 04:57:00 +0000784 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
785 RetEffect::MakeNoRet() /* return effect */,
Ted Kremenekebd5a2d2009-05-11 18:30:24 +0000786 MayEscape, /* default argument effect */
787 DoNothing /* receiver effect */),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000788 StopSummary(0) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000789
790 InitializeClassMethodSummaries();
791 InitializeMethodSummaries();
792 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000793
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000794 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000795
Ted Kremenekab592272008-06-24 03:56:45 +0000796 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek8711c032009-04-29 05:04:30 +0000797
Ted Kremeneka8833552009-04-29 23:03:22 +0000798 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
799 const ObjCInterfaceDecl* ID) {
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000800 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremenek8711c032009-04-29 05:04:30 +0000801 ID, ME->getMethodDecl(), ME->getType());
802 }
803
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000804 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000805 const ObjCInterfaceDecl* ID,
806 const ObjCMethodDecl *MD,
807 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000808
809 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000810 const ObjCInterfaceDecl *ID,
811 const ObjCMethodDecl *MD,
812 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000813
814 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
815 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
816 ME->getClassInfo().first,
817 ME->getMethodDecl(), ME->getType());
818 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000819
820 /// getMethodSummary - This version of getMethodSummary is used to query
821 /// the summary for the current method being analyzed.
Ted Kremeneka8833552009-04-29 23:03:22 +0000822 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
823 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000824 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000825 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000826 IdentifierInfo *ClsName = ID->getIdentifier();
827 QualType ResultTy = MD->getResultType();
828
Ted Kremenek76a50e32009-04-30 05:47:23 +0000829 // Resolve the method decl last.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000830 if (const ObjCMethodDecl *InterfaceMD = ResolveToInterfaceMethodDecl(MD))
Ted Kremenek76a50e32009-04-30 05:47:23 +0000831 MD = InterfaceMD;
Ted Kremenek70a65762009-04-30 05:41:14 +0000832
Ted Kremenek552333c2009-04-29 17:17:48 +0000833 if (MD->isInstanceMethod())
834 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
835 else
836 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
837 }
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000838
Ted Kremeneka8833552009-04-29 23:03:22 +0000839 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
840 Selector S, QualType RetTy);
841
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000842 void updateSummaryFromAnnotations(RetainSummary &Summ,
843 const ObjCMethodDecl *MD);
844
845 void updateSummaryFromAnnotations(RetainSummary &Summ,
846 const FunctionDecl *FD);
847
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000848 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek885c27b2009-05-04 05:31:22 +0000849
850 RetainSummary *copySummary(RetainSummary *OldSumm) {
851 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
852 new (Summ) RetainSummary(*OldSumm);
853 return Summ;
854 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000855};
856
857} // end anonymous namespace
858
859//===----------------------------------------------------------------------===//
860// Implementation of checker data structures.
861//===----------------------------------------------------------------------===//
862
Ted Kremenekb77449c2009-05-03 05:20:50 +0000863RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000864
Ted Kremenekb77449c2009-05-03 05:20:50 +0000865ArgEffects RetainSummaryManager::getArgEffects() {
866 ArgEffects AE = ScratchArgs;
867 ScratchArgs = AF.GetEmptyMap();
868 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000869}
870
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000871RetainSummary*
Ted Kremenekb77449c2009-05-03 05:20:50 +0000872RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000873 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000874 ArgEffect DefaultEff,
Ted Kremenek22fe2482009-05-04 04:30:18 +0000875 bool isEndPath) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000876 // Create the summary and return it.
Ted Kremenek22fe2482009-05-04 04:30:18 +0000877 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000878 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000879 return Summ;
880}
881
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000882//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000883// Predicates.
884//===----------------------------------------------------------------------===//
885
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000886bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek97d095f2009-04-23 22:11:07 +0000887 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek234a4c22009-01-07 00:39:56 +0000888 return false;
889
Ted Kremenek97d095f2009-04-23 22:11:07 +0000890 // We assume that id<..>, id, and "Class" all represent tracked objects.
891 const PointerType *PT = Ty->getAsPointerType();
892 if (PT == 0)
893 return true;
894
895 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek234a4c22009-01-07 00:39:56 +0000896
897 // We assume that id<..>, id, and "Class" all represent tracked objects.
898 if (!OT)
899 return true;
Ted Kremenek97d095f2009-04-23 22:11:07 +0000900
Ted Kremenekfae664a2009-05-16 01:38:01 +0000901 // Does the interface subclass NSObject?
902 // FIXME: We can memoize here if this gets too expensive.
Ted Kremenek234a4c22009-01-07 00:39:56 +0000903 ObjCInterfaceDecl* ID = OT->getDecl();
904
Ted Kremenekfae664a2009-05-16 01:38:01 +0000905 // Assume that anything declared with a forward declaration and no
906 // @interface subclasses NSObject.
907 if (ID->isForwardDecl())
908 return true;
909
910 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
911
912
Ted Kremenek234a4c22009-01-07 00:39:56 +0000913 for ( ; ID ; ID = ID->getSuperClass())
914 if (ID->getIdentifier() == NSObjectII)
915 return true;
916
917 return false;
918}
919
Ted Kremenek92511432009-05-03 06:08:32 +0000920bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
921 return isRefType(T, "CF") || // Core Foundation.
922 isRefType(T, "CG") || // Core Graphics.
923 isRefType(T, "DADisk") || // Disk Arbitration API.
924 isRefType(T, "DADissenter") ||
925 isRefType(T, "DASessionRef");
926}
927
Ted Kremenek234a4c22009-01-07 00:39:56 +0000928//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000929// Summary creation for functions (largely uses of Core Foundation).
930//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000931
Ted Kremenek12619382009-01-12 21:45:02 +0000932static bool isRetain(FunctionDecl* FD, const char* FName) {
933 const char* loc = strstr(FName, "Retain");
934 return loc && loc[sizeof("Retain")-1] == '\0';
935}
936
937static bool isRelease(FunctionDecl* FD, const char* FName) {
938 const char* loc = strstr(FName, "Release");
939 return loc && loc[sizeof("Release")-1] == '\0';
940}
941
Ted Kremenekab592272008-06-24 03:56:45 +0000942RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000943 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000944 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000945 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000946 return I->second;
947
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000948 // No summary? Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000949 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000950
Ted Kremenek37d785b2008-07-15 16:50:12 +0000951 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000952 // We generate "stop" summaries for implicitly defined functions.
953 if (FD->isImplicit()) {
954 S = getPersistentStopSummary();
955 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000956 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000957
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000958 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000959 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000960 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000961 const char* FName = FD->getIdentifier()->getName();
962
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000963 // Strip away preceding '_'. Doing this here will effect all the checks
964 // down below.
965 while (*FName == '_') ++FName;
966
Ted Kremenek12619382009-01-12 21:45:02 +0000967 // Inspect the result type.
968 QualType RetTy = FT->getResultType();
969
970 // FIXME: This should all be refactored into a chain of "summary lookup"
971 // filters.
Ted Kremenek39d88b02009-06-15 20:36:07 +0000972 assert (ScratchArgs.isEmpty());
973
Ted Kremenekb04cb592009-06-11 18:17:24 +0000974 switch (strlen(FName)) {
975 default: break;
Ted Kremenek39d88b02009-06-15 20:36:07 +0000976
977
Ted Kremenekb04cb592009-06-11 18:17:24 +0000978 case 17:
979 // Handle: id NSMakeCollectable(CFTypeRef)
980 if (!memcmp(FName, "NSMakeCollectable", 17)) {
981 S = (RetTy == Ctx.getObjCIdType())
982 ? getUnarySummary(FT, cfmakecollectable)
983 : getPersistentStopSummary();
984 }
Ted Kremenek39d88b02009-06-15 20:36:07 +0000985 else if (!memcmp(FName, "IOBSDNameMatching", 17) ||
986 !memcmp(FName, "IOServiceMatching", 17)) {
987 // Part of <rdar://problem/6961230>. (IOKit)
988 // This should be addressed using a API table.
989 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
990 DoNothing, DoNothing);
991 }
Ted Kremenekb04cb592009-06-11 18:17:24 +0000992 break;
Ted Kremenek39d88b02009-06-15 20:36:07 +0000993
994 case 21:
995 if (!memcmp(FName, "IOServiceNameMatching", 21)) {
996 // Part of <rdar://problem/6961230>. (IOKit)
997 // This should be addressed using a API table.
998 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
999 DoNothing, DoNothing);
1000 }
1001 break;
1002
1003 case 24:
1004 if (!memcmp(FName, "IOServiceAddNotification", 24)) {
1005 // Part of <rdar://problem/6961230>. (IOKit)
1006 // This should be addressed using a API table.
1007 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1008 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1009 }
1010 break;
1011
1012 case 25:
1013 if (!memcmp(FName, "IORegistryEntryIDMatching", 25)) {
1014 // Part of <rdar://problem/6961230>. (IOKit)
1015 // This should be addressed using a API table.
1016 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1017 DoNothing, DoNothing);
1018 }
1019 break;
1020
1021 case 26:
1022 if (!memcmp(FName, "IOOpenFirmwarePathMatching", 26)) {
1023 // Part of <rdar://problem/6961230>. (IOKit)
1024 // This should be addressed using a API table.
1025 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1026 DoNothing, DoNothing);
1027 }
1028 break;
1029
Ted Kremenekb04cb592009-06-11 18:17:24 +00001030 case 27:
1031 if (!memcmp(FName, "IOServiceGetMatchingService", 27)) {
1032 // Part of <rdar://problem/6961230>.
1033 // This should be addressed using a API table.
Ted Kremenekb04cb592009-06-11 18:17:24 +00001034 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1035 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1036 }
1037 break;
1038
1039 case 28:
1040 if (!memcmp(FName, "IOServiceGetMatchingServices", 28)) {
1041 // FIXES: <rdar://problem/6326900>
1042 // This should be addressed using a API table. This strcmp is also
1043 // a little gross, but there is no need to super optimize here.
Ted Kremenekb04cb592009-06-11 18:17:24 +00001044 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1045 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1046 }
1047 break;
Ted Kremenek39d88b02009-06-15 20:36:07 +00001048
1049 case 32:
1050 if (!memcmp(FName, "IOServiceAddMatchingNotification", 32)) {
1051 // Part of <rdar://problem/6961230>.
1052 // This should be addressed using a API table.
1053 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1054 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1055 }
1056 break;
Ted Kremenekb04cb592009-06-11 18:17:24 +00001057 }
1058
1059 // Did we get a summary?
1060 if (S)
1061 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001062
1063 // Enable this code once the semantics of NSDeallocateObject are resolved
1064 // for GC. <rdar://problem/6619988>
1065#if 0
1066 // Handle: NSDeallocateObject(id anObject);
1067 // This method does allow 'nil' (although we don't check it now).
1068 if (strcmp(FName, "NSDeallocateObject") == 0) {
1069 return RetTy == Ctx.VoidTy
1070 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1071 : getPersistentStopSummary();
1072 }
1073#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001074
1075 if (RetTy->isPointerType()) {
1076 // For CoreFoundation ('CF') types.
1077 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1078 if (isRetain(FD, FName))
1079 S = getUnarySummary(FT, cfretain);
1080 else if (strstr(FName, "MakeCollectable"))
1081 S = getUnarySummary(FT, cfmakecollectable);
1082 else
1083 S = getCFCreateGetRuleSummary(FD, FName);
1084
1085 break;
1086 }
1087
1088 // For CoreGraphics ('CG') types.
1089 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1090 if (isRetain(FD, FName))
1091 S = getUnarySummary(FT, cfretain);
1092 else
1093 S = getCFCreateGetRuleSummary(FD, FName);
1094
1095 break;
1096 }
1097
1098 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1099 if (isRefType(RetTy, "DADisk") ||
1100 isRefType(RetTy, "DADissenter") ||
1101 isRefType(RetTy, "DASessionRef")) {
1102 S = getCFCreateGetRuleSummary(FD, FName);
1103 break;
1104 }
1105
1106 break;
1107 }
1108
1109 // Check for release functions, the only kind of functions that we care
1110 // about that don't return a pointer type.
1111 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001112 // Test for 'CGCF'.
1113 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1114 FName += 4;
1115 else
1116 FName += 2;
1117
1118 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001119 S = getUnarySummary(FT, cfrelease);
1120 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001121 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001122 // Remaining CoreFoundation and CoreGraphics functions.
1123 // We use to assume that they all strictly followed the ownership idiom
1124 // and that ownership cannot be transferred. While this is technically
1125 // correct, many methods allow a tracked object to escape. For example:
1126 //
1127 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1128 // CFDictionaryAddValue(y, key, x);
1129 // CFRelease(x);
1130 // ... it is okay to use 'x' since 'y' has a reference to it
1131 //
1132 // We handle this and similar cases with the follow heuristic. If the
1133 // function name contains "InsertValue", "SetValue" or "AddValue" then
1134 // we assume that arguments may "escape."
1135 //
1136 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1137 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +00001138 CStrInCStrNoCase(FName, "SetValue") ||
1139 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +00001140 ? MayEscape : DoNothing;
1141
1142 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001143 }
1144 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001145 }
1146 while (0);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001147
1148 if (!S)
1149 S = getDefaultSummary();
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001150
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001151 // Annotations override defaults.
1152 assert(S);
1153 updateSummaryFromAnnotations(*S, FD);
1154
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001155 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001156 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001157}
1158
Ted Kremenek37d785b2008-07-15 16:50:12 +00001159RetainSummary*
1160RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1161 const char* FName) {
1162
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001163 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1164 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +00001165
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001166 if (strstr(FName, "Get"))
1167 return getCFSummaryGetRule(FD);
1168
Ted Kremenek7faca822009-05-04 04:57:00 +00001169 return getDefaultSummary();
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001170}
1171
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001172RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001173RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1174 UnaryFuncKind func) {
1175
Ted Kremenek12619382009-01-12 21:45:02 +00001176 // Sanity check that this is *really* a unary function. This can
1177 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001178 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001179 if (!FTP || FTP->getNumArgs() != 1)
1180 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001181
Ted Kremenekb77449c2009-05-03 05:20:50 +00001182 assert (ScratchArgs.isEmpty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001183
Ted Kremenek377e2302008-04-29 05:33:51 +00001184 switch (func) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001185 case cfretain: {
1186 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001187 return getPersistentSummary(RetEffect::MakeAlias(0),
1188 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001189 }
1190
1191 case cfrelease: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001192 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001193 return getPersistentSummary(RetEffect::MakeNoRet(),
1194 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001195 }
1196
1197 case cfmakecollectable: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001198 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek27019002009-02-18 21:57:45 +00001199 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001200 }
1201
1202 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001203 assert (false && "Not a supported unary function.");
Ted Kremenek7faca822009-05-04 04:57:00 +00001204 return getDefaultSummary();
Ted Kremenek940b1d82008-04-10 23:44:06 +00001205 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001206}
1207
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001208RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001209 assert (ScratchArgs.isEmpty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001210
1211 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001212 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1213 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenek070a8252008-07-09 18:11:16 +00001214 }
1215
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001216 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001217}
1218
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001219RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001220 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001221 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1222 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001223}
1224
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001225//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001226// Summary creation for Selectors.
1227//===----------------------------------------------------------------------===//
1228
Ted Kremenek1bffd742008-05-06 15:44:25 +00001229RetainSummary*
Ted Kremenek8711c032009-04-29 05:04:30 +00001230RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek78a35a32009-05-12 20:06:54 +00001231 assert(ScratchArgs.isEmpty());
1232 // 'init' methods conceptually return a newly allocated object and claim
1233 // the receiver.
1234 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
Ted Kremenek547d4952009-06-05 23:18:01 +00001235 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001236
1237 return getDefaultSummary();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001238}
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001239
1240void
1241RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1242 const FunctionDecl *FD) {
1243 if (!FD)
1244 return;
1245
Ted Kremenekb04cb592009-06-11 18:17:24 +00001246 QualType RetTy = FD->getResultType();
1247
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001248 // Determine if there is a special return effect for this method.
Ted Kremenekb9d8db82009-06-05 23:00:33 +00001249 if (isTrackedObjCObjectType(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001250 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001251 Summ.setRetEffect(ObjCAllocRetE);
1252 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001253 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenekb9d8db82009-06-05 23:00:33 +00001254 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001255 }
1256 }
1257 else if (RetTy->getAsPointerType()) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001258 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001259 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1260 }
1261 }
1262}
1263
1264void
1265RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1266 const ObjCMethodDecl *MD) {
1267 if (!MD)
1268 return;
1269
1270 // Determine if there is a special return effect for this method.
1271 if (isTrackedObjCObjectType(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001272 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001273 Summ.setRetEffect(ObjCAllocRetE);
1274 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001275 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001276 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1277 }
1278 }
1279}
1280
Ted Kremenek1bffd742008-05-06 15:44:25 +00001281RetainSummary*
Ted Kremeneka8833552009-04-29 23:03:22 +00001282RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1283 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001284
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001285 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001286 // Scan the method decl for 'void*' arguments. These should be treated
1287 // as 'StopTracking' because they are often used with delegates.
1288 // Delegates are a frequent form of false positives with the retain
1289 // count checker.
1290 unsigned i = 0;
1291 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1292 E = MD->param_end(); I != E; ++I, ++i)
1293 if (ParmVarDecl *PD = *I) {
1294 QualType Ty = Ctx.getCanonicalType(PD->getType());
1295 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenekb77449c2009-05-03 05:20:50 +00001296 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001297 }
1298 }
1299
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001300 // Any special effect for the receiver?
1301 ArgEffect ReceiverEff = DoNothing;
1302
1303 // If one of the arguments in the selector has the keyword 'delegate' we
1304 // should stop tracking the reference count for the receiver. This is
1305 // because the reference count is quite possibly handled by a delegate
1306 // method.
1307 if (S.isKeywordSelector()) {
1308 const std::string &str = S.getAsString();
1309 assert(!str.empty());
1310 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1311 }
1312
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001313 // Look for methods that return an owned object.
Ted Kremenek92511432009-05-03 06:08:32 +00001314 if (isTrackedObjCObjectType(RetTy)) {
1315 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1316 // by instance methods.
Ted Kremenek7db16042009-05-15 15:49:00 +00001317 RetEffect E = followsFundamentalRule(S)
1318 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek92511432009-05-03 06:08:32 +00001319
1320 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001321 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001322
Ted Kremenek92511432009-05-03 06:08:32 +00001323 // Look for methods that return an owned core foundation object.
1324 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek7db16042009-05-15 15:49:00 +00001325 RetEffect E = followsFundamentalRule(S)
1326 ? RetEffect::MakeOwned(RetEffect::CF, true)
1327 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremenek92511432009-05-03 06:08:32 +00001328
1329 return getPersistentSummary(E, ReceiverEff, MayEscape);
1330 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001331
Ted Kremenek92511432009-05-03 06:08:32 +00001332 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek7faca822009-05-04 04:57:00 +00001333 return getDefaultSummary();
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001334
Ted Kremenek885c27b2009-05-04 05:31:22 +00001335 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001336}
1337
1338RetainSummary*
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001339RetainSummaryManager::getInstanceMethodSummary(Selector S,
1340 IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001341 const ObjCInterfaceDecl* ID,
1342 const ObjCMethodDecl *MD,
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001343 QualType RetTy) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001344
Ted Kremenek8711c032009-04-29 05:04:30 +00001345 // Look up a summary in our summary cache.
1346 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001347
Ted Kremenek1f180c32008-06-23 22:21:20 +00001348 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001349 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001350
Ted Kremenekb77449c2009-05-03 05:20:50 +00001351 assert(ScratchArgs.isEmpty());
Ted Kremenek885c27b2009-05-04 05:31:22 +00001352 RetainSummary *Summ = 0;
Ted Kremenekaee9e572008-05-06 06:09:09 +00001353
Ted Kremenek885c27b2009-05-04 05:31:22 +00001354 // "initXXX": pass-through for receiver.
Ted Kremenek7db16042009-05-15 15:49:00 +00001355 if (deriveNamingConvention(S) == InitRule)
Ted Kremenek885c27b2009-05-04 05:31:22 +00001356 Summ = getInitMethodSummary(RetTy);
1357 else
1358 Summ = getCommonMethodSummary(MD, S, RetTy);
1359
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001360 // Annotations override defaults.
1361 updateSummaryFromAnnotations(*Summ, MD);
1362
Ted Kremenek885c27b2009-05-04 05:31:22 +00001363 // Memoize the summary.
Ted Kremenek70b6a832009-05-13 18:16:01 +00001364 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001365 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001366}
1367
Ted Kremenekc8395602008-05-06 21:26:51 +00001368RetainSummary*
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001369RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001370 const ObjCInterfaceDecl *ID,
1371 const ObjCMethodDecl *MD,
1372 QualType RetTy) {
Ted Kremenekde4d5332009-04-24 17:50:11 +00001373
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001374 assert(ClsName && "Class name must be specified.");
Ted Kremenek8711c032009-04-29 05:04:30 +00001375 ObjCMethodSummariesTy::iterator I =
1376 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001377
Ted Kremenek1f180c32008-06-23 22:21:20 +00001378 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001379 return I->second;
Ted Kremenek885c27b2009-05-04 05:31:22 +00001380
1381 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001382
1383 // Annotations override defaults.
1384 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001385
Ted Kremenek885c27b2009-05-04 05:31:22 +00001386 // Memoize the summary.
Ted Kremenek70b6a832009-05-13 18:16:01 +00001387 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001388 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001389}
1390
Ted Kremenekec315332009-05-07 23:40:42 +00001391void RetainSummaryManager::InitializeClassMethodSummaries() {
1392 assert(ScratchArgs.isEmpty());
1393 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001394
Ted Kremenek553cf182008-06-25 21:21:56 +00001395 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1396 // NSObject and its derivatives.
1397 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1398 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1399 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001400
1401 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001402 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001403 GetNullarySelector("currentHandler", Ctx),
1404 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001405
1406 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb77449c2009-05-03 05:20:50 +00001407 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenekabf43972009-01-28 21:44:40 +00001408 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1409 GetUnarySelector("addObject", Ctx),
1410 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001411 DoNothing, Autorelease));
Ted Kremenekde4d5332009-04-24 17:50:11 +00001412
1413 // Create the summaries for [NSObject performSelector...]. We treat
1414 // these as 'stop tracking' for the arguments because they are often
1415 // used for delegates that can release the object. When we have better
1416 // inter-procedural analysis we can potentially do something better. This
1417 // workaround is to remove false positives.
1418 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1419 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1420 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1421 "afterDelay", NULL);
1422 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1423 "afterDelay", "inModes", NULL);
1424 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1425 "withObject", "waitUntilDone", NULL);
1426 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1427 "withObject", "waitUntilDone", "modes", NULL);
1428 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1429 "withObject", "waitUntilDone", NULL);
1430 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1431 "withObject", "waitUntilDone", "modes", NULL);
1432 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1433 "withObject", NULL);
Ted Kremenek30437662009-05-14 21:29:16 +00001434
1435 // Specially handle NSData.
1436 RetainSummary *dataWithBytesNoCopySumm =
1437 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1438 DoNothing);
1439 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1440 "dataWithBytesNoCopy", "length", NULL);
1441 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1442 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001443}
1444
Ted Kremenek1f180c32008-06-23 22:21:20 +00001445void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001446
Ted Kremenekb77449c2009-05-03 05:20:50 +00001447 assert (ScratchArgs.isEmpty());
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001448
Ted Kremenekc8395602008-05-06 21:26:51 +00001449 // Create the "init" selector. It just acts as a pass-through for the
1450 // receiver.
Ted Kremenek78a35a32009-05-12 20:06:54 +00001451 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
Ted Kremenekb04cb592009-06-11 18:17:24 +00001452 getPersistentSummary(ObjCInitRetE, DecRefMsg));
Ted Kremenekc8395602008-05-06 21:26:51 +00001453
1454 // The next methods are allocators.
Ted Kremenek767d6492009-05-20 22:39:57 +00001455 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Ted Kremenekc8395602008-05-06 21:26:51 +00001456
1457 // Create the "copy" selector.
Ted Kremenek767d6492009-05-20 22:39:57 +00001458 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek98530452008-08-12 20:41:56 +00001459
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001460 // Create the "mutableCopy" selector.
Ted Kremenek767d6492009-05-20 22:39:57 +00001461 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Ted Kremenek98530452008-08-12 20:41:56 +00001462
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001463 // Create the "retain" selector.
Ted Kremenekec315332009-05-07 23:40:42 +00001464 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek767d6492009-05-20 22:39:57 +00001465 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001466 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001467
1468 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001469 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001470 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001471
1472 // Create the "drain" selector.
1473 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001474 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001475
1476 // Create the -dealloc summary.
1477 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1478 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001479
1480 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001481 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001482 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001483
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001484 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001485 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001486 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001487 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001488
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001489 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001490 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1491 // self-own themselves. However, they only do this once they are displayed.
1492 // Thus, we need to track an NSWindow's display status.
1493 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001494 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek78a35a32009-05-12 20:06:54 +00001495 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1496 StopTracking,
1497 StopTracking);
Ted Kremenek99d02692009-04-03 19:02:51 +00001498
1499 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1500
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001501#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001502 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001503 "styleMask", "backing", "defer", NULL);
1504
Ted Kremenek78a35a32009-05-12 20:06:54 +00001505 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001506 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001507#endif
Ted Kremenek78a35a32009-05-12 20:06:54 +00001508
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001509 // For NSPanel (which subclasses NSWindow), allocated objects are not
1510 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001511 // FIXME: For now we don't track NSPanels. object for the same reason
1512 // as for NSWindow objects.
1513 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1514
Ted Kremenek78a35a32009-05-12 20:06:54 +00001515#if 0
1516 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001517 "styleMask", "backing", "defer", NULL);
1518
Ted Kremenek78a35a32009-05-12 20:06:54 +00001519 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001520 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001521#endif
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001522
1523 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1524 // exit a method.
1525 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001526
Ted Kremenek70a733e2008-07-18 17:24:20 +00001527 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001528 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1529 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001530
Ted Kremenek9e476de2008-08-12 18:30:56 +00001531 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1532 "file", "lineNumber", "description", NULL);
Ted Kremenek767d6492009-05-20 22:39:57 +00001533
1534 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1535 addInstMethSummary("QCRenderer", AllocSumm,
1536 "createSnapshotImageOfType", NULL);
1537 addInstMethSummary("QCView", AllocSumm,
1538 "createSnapshotImageOfType", NULL);
1539
Ted Kremenek211a9c62009-06-15 20:58:58 +00001540 // Create summaries for CIContext, 'createCGImage' and
1541 // 'createCGLayerWithSize'.
Ted Kremenek767d6492009-05-20 22:39:57 +00001542 addInstMethSummary("CIContext", AllocSumm,
1543 "createCGImage", "fromRect", NULL);
1544 addInstMethSummary("CIContext", AllocSumm,
Ted Kremenek211a9c62009-06-15 20:58:58 +00001545 "createCGImage", "fromRect", "format", "colorSpace", NULL);
1546 addInstMethSummary("CIContext", AllocSumm, "createCGLayerWithSize",
1547 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001548}
1549
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001550//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001551// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001552//===----------------------------------------------------------------------===//
1553
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001554namespace {
1555
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001556class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001557public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001558 enum Kind {
1559 Owned = 0, // Owning reference.
1560 NotOwned, // Reference is not owned by still valid (not freed).
1561 Released, // Object has been released.
1562 ReturnedOwned, // Returned object passes ownership to caller.
1563 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001564 ERROR_START,
1565 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1566 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001567 ErrorUseAfterRelease, // Object used after released.
1568 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001569 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001570 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek369de562009-05-09 00:10:05 +00001571 ErrorLeakReturned, // A memory leak due to the returning method not having
1572 // the correct naming conventions.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001573 ErrorGCLeakReturned,
1574 ErrorOverAutorelease,
1575 ErrorReturnedNotOwned
Ted Kremenek4fd88972008-04-17 18:12:53 +00001576 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001577
1578private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001579 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001580 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001581 unsigned Cnt;
Ted Kremenekf21332e2009-05-08 20:01:42 +00001582 unsigned ACnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001583 QualType T;
1584
Ted Kremenekf21332e2009-05-08 20:01:42 +00001585 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1586 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001587
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001588 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenekf21332e2009-05-08 20:01:42 +00001589 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001590
1591public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001592 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001593
1594 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001595
Ted Kremenekf21332e2009-05-08 20:01:42 +00001596 unsigned getCount() const { return Cnt; }
1597 unsigned getAutoreleaseCount() const { return ACnt; }
1598 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1599 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek369de562009-05-09 00:10:05 +00001600 void setCount(unsigned i) { Cnt = i; }
1601 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001602
Ted Kremenek553cf182008-06-25 21:21:56 +00001603 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001604
1605 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001606
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001607 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001608
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001609 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001610
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001611 bool isOwned() const {
1612 return getKind() == Owned;
1613 }
1614
Ted Kremenekdb863712008-04-16 22:32:20 +00001615 bool isNotOwned() const {
1616 return getKind() == NotOwned;
1617 }
1618
Ted Kremenek4fd88972008-04-17 18:12:53 +00001619 bool isReturnedOwned() const {
1620 return getKind() == ReturnedOwned;
1621 }
1622
1623 bool isReturnedNotOwned() const {
1624 return getKind() == ReturnedNotOwned;
1625 }
1626
1627 bool isNonLeakError() const {
1628 Kind k = getKind();
1629 return isError(k) && !isLeak(k);
1630 }
1631
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001632 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1633 unsigned Count = 1) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001634 return RefVal(Owned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001635 }
1636
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001637 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1638 unsigned Count = 0) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001639 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001640 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001641
Ted Kremenek4fd88972008-04-17 18:12:53 +00001642 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001643
Ted Kremenek4fd88972008-04-17 18:12:53 +00001644 bool operator==(const RefVal& X) const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001645 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001646 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001647
Ted Kremenek553cf182008-06-25 21:21:56 +00001648 RefVal operator-(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001649 return RefVal(getKind(), getObjKind(), getCount() - i,
1650 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001651 }
1652
1653 RefVal operator+(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001654 return RefVal(getKind(), getObjKind(), getCount() + i,
1655 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001656 }
1657
1658 RefVal operator^(Kind k) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001659 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1660 getType());
1661 }
1662
1663 RefVal autorelease() const {
1664 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1665 getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001666 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001667
Ted Kremenek4fd88972008-04-17 18:12:53 +00001668 void Profile(llvm::FoldingSetNodeID& ID) const {
1669 ID.AddInteger((unsigned) kind);
1670 ID.AddInteger(Cnt);
Ted Kremenekf21332e2009-05-08 20:01:42 +00001671 ID.AddInteger(ACnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001672 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001673 }
1674
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001675 void print(llvm::raw_ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001676};
Ted Kremenekf3948042008-03-11 19:44:10 +00001677
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001678void RefVal::print(llvm::raw_ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001679 if (!T.isNull())
1680 Out << "Tracked Type:" << T.getAsString() << '\n';
1681
Ted Kremenekf3948042008-03-11 19:44:10 +00001682 switch (getKind()) {
1683 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001684 case Owned: {
1685 Out << "Owned";
1686 unsigned cnt = getCount();
1687 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001688 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001689 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001690
Ted Kremenek61b9f872008-04-10 23:09:18 +00001691 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001692 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001693 unsigned cnt = getCount();
1694 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001695 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001696 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001697
Ted Kremenek4fd88972008-04-17 18:12:53 +00001698 case ReturnedOwned: {
1699 Out << "ReturnedOwned";
1700 unsigned cnt = getCount();
1701 if (cnt) Out << " (+ " << cnt << ")";
1702 break;
1703 }
1704
1705 case ReturnedNotOwned: {
1706 Out << "ReturnedNotOwned";
1707 unsigned cnt = getCount();
1708 if (cnt) Out << " (+ " << cnt << ")";
1709 break;
1710 }
1711
Ted Kremenekf3948042008-03-11 19:44:10 +00001712 case Released:
1713 Out << "Released";
1714 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001715
1716 case ErrorDeallocGC:
1717 Out << "-dealloc (GC)";
1718 break;
1719
1720 case ErrorDeallocNotOwned:
1721 Out << "-dealloc (not-owned)";
1722 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001723
Ted Kremenekdb863712008-04-16 22:32:20 +00001724 case ErrorLeak:
1725 Out << "Leaked";
1726 break;
1727
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001728 case ErrorLeakReturned:
1729 Out << "Leaked (Bad naming)";
1730 break;
1731
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001732 case ErrorGCLeakReturned:
1733 Out << "Leaked (GC-ed at return)";
1734 break;
1735
Ted Kremenekf3948042008-03-11 19:44:10 +00001736 case ErrorUseAfterRelease:
1737 Out << "Use-After-Release [ERROR]";
1738 break;
1739
1740 case ErrorReleaseNotOwned:
1741 Out << "Release of Not-Owned [ERROR]";
1742 break;
Ted Kremenek80c24182009-05-09 00:44:07 +00001743
1744 case RefVal::ErrorOverAutorelease:
1745 Out << "Over autoreleased";
1746 break;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001747
1748 case RefVal::ErrorReturnedNotOwned:
1749 Out << "Non-owned object returned instead of owned";
1750 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001751 }
Ted Kremenekf21332e2009-05-08 20:01:42 +00001752
1753 if (ACnt) {
1754 Out << " [ARC +" << ACnt << ']';
1755 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001756}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001757
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001758} // end anonymous namespace
1759
1760//===----------------------------------------------------------------------===//
1761// RefBindings - State used to track object reference counts.
1762//===----------------------------------------------------------------------===//
1763
Ted Kremenek2dabd432008-12-05 02:27:51 +00001764typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001765static int RefBIndex = 0;
1766
1767namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001768 template<>
1769 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1770 static inline void* GDMIndex() { return &RefBIndex; }
1771 };
1772}
Ted Kremenek6d348932008-10-21 15:53:15 +00001773
1774//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001775// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001776//===----------------------------------------------------------------------===//
1777
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001778typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1779typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1780typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001781
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001782static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001783static int AutoRBIndex = 0;
1784
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001785namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001786namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001787
Ted Kremenek6d348932008-10-21 15:53:15 +00001788namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001789template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001790 : public GRStatePartialTrait<ARStack> {
1791 static inline void* GDMIndex() { return &AutoRBIndex; }
1792};
1793
1794template<> struct GRStateTrait<AutoreleasePoolContents>
1795 : public GRStatePartialTrait<ARPoolContents> {
1796 static inline void* GDMIndex() { return &AutoRCIndex; }
1797};
1798} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001799
Ted Kremenek7037ab82009-03-20 17:34:15 +00001800static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1801 ARStack stack = state->get<AutoreleaseStack>();
1802 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1803}
1804
Ted Kremenekb65be702009-06-18 01:23:53 +00001805static const GRState * SendAutorelease(const GRState *state,
1806 ARCounts::Factory &F, SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001807
1808 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001809 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001810 ARCounts newCnts(0);
1811
1812 if (cnts) {
1813 const unsigned *cnt = (*cnts).lookup(sym);
1814 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1815 }
1816 else
1817 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1818
Ted Kremenekb65be702009-06-18 01:23:53 +00001819 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001820}
1821
Ted Kremenek13922612008-04-16 20:40:59 +00001822//===----------------------------------------------------------------------===//
1823// Transfer functions.
1824//===----------------------------------------------------------------------===//
1825
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001826namespace {
1827
Ted Kremenek6c07bdb2009-06-26 00:05:51 +00001828class VISIBILITY_HIDDEN CFRefCount : public GRTransferFuncs {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001829public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001830 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001831 public:
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001832 virtual void Print(llvm::raw_ostream& Out, const GRState* state,
Ted Kremenekae6814e2008-08-13 21:24:49 +00001833 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001834 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001835
1836private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001837 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1838 SummaryLogTy;
1839
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001840 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001841 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001842 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001843 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001844
Ted Kremenekcf701772009-02-05 06:50:21 +00001845 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001846 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001847 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek369de562009-05-09 00:10:05 +00001848 BugType *overAutorelease;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001849 BugType *returnNotOwnedForOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001850 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001851
Ted Kremenekb65be702009-06-18 01:23:53 +00001852 const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001853 RefVal::Kind& hasErr);
1854
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001855 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1856 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu264e9372009-05-12 10:10:00 +00001857 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001858 ExplodedNode<GRState>* Pred,
1859 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001860 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001861
Ted Kremenekb65be702009-06-18 01:23:53 +00001862 const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001863 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1864
Ted Kremenekb65be702009-06-18 01:23:53 +00001865 ExplodedNode<GRState>* ProcessLeaks(const GRState * state,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001866 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1867 GenericNodeBuilder &Builder,
1868 GRExprEngine &Eng,
1869 ExplodedNode<GRState> *Pred = 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001870
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001871public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001872 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001873 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001874 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1875 deallocGC(0), deallocNotOwned(0),
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001876 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1877 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001878
Ted Kremenekcf701772009-02-05 06:50:21 +00001879 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001880
Ted Kremenekcf118d42009-02-04 23:49:09 +00001881 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001882
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001883 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1884 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001885 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001886
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001887 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001888 const LangOptions& getLangOptions() const { return LOpts; }
1889
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001890 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1891 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1892 return I == SummaryLog.end() ? 0 : I->second;
1893 }
1894
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001895 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001896
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001897 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001898 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001899 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001900 Expr* Ex,
1901 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00001902 const RetainSummary& Summ,
Zhongxing Xu264e9372009-05-12 10:10:00 +00001903 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001904 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001905
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001906 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001907 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001908 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001909 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001910 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001911
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001912
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001913 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001914 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001915 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001916 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001917 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001918
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001919 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001920 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001921 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001922 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001923 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001924
Ted Kremenek41573eb2009-02-14 01:43:44 +00001925 // Stores.
1926 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1927
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001928 // End-of-path.
1929
1930 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001931 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001932
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001933 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001934 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001935 GRStmtNodeBuilder<GRState>& Builder,
1936 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001937 Stmt* S, const GRState* state,
1938 SymbolReaper& SymReaper);
Ted Kremenekf04dced2009-05-08 23:32:51 +00001939
Ted Kremenekb65be702009-06-18 01:23:53 +00001940 std::pair<ExplodedNode<GRState>*, const GRState *>
1941 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Ted Kremenek369de562009-05-09 00:10:05 +00001942 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1943 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001944 // Return statements.
1945
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001946 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001947 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001948 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001949 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001950 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001951
1952 // Assumptions.
1953
Ted Kremeneka591bc02009-06-18 22:57:13 +00001954 virtual const GRState *EvalAssume(const GRState* state, SVal condition,
1955 bool assumption);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001956};
1957
1958} // end anonymous namespace
1959
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001960static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym,
1961 const GRState *state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001962 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001963 if (Sym)
1964 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001965 else
1966 Out << "<pool>";
1967 Out << ":{";
1968
1969 // Get the contents of the pool.
1970 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1971 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1972 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1973
1974 Out << '}';
1975}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001976
Ted Kremenek53ba0b62009-06-24 23:06:47 +00001977void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out,
1978 const GRState* state,
Ted Kremenekae6814e2008-08-13 21:24:49 +00001979 const char* nl, const char* sep) {
1980
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001981 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001982
Ted Kremenekae6814e2008-08-13 21:24:49 +00001983 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001984 Out << sep << nl;
1985
1986 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1987 Out << (*I).first << " : ";
1988 (*I).second.print(Out);
1989 Out << nl;
1990 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001991
1992 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001993 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001994 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001995
Ted Kremenek7037ab82009-03-20 17:34:15 +00001996 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1997 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1998 PrintPool(Out, *I, state);
1999
2000 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00002001}
2002
Ted Kremenekc887d132009-04-29 18:50:19 +00002003//===----------------------------------------------------------------------===//
2004// Error reporting.
2005//===----------------------------------------------------------------------===//
2006
2007namespace {
2008
2009 //===-------------===//
2010 // Bug Descriptions. //
2011 //===-------------===//
2012
2013 class VISIBILITY_HIDDEN CFRefBug : public BugType {
2014 protected:
2015 CFRefCount& TF;
2016
2017 CFRefBug(CFRefCount* tf, const char* name)
2018 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
2019 public:
2020
2021 CFRefCount& getTF() { return TF; }
2022 const CFRefCount& getTF() const { return TF; }
2023
2024 // FIXME: Eventually remove.
2025 virtual const char* getDescription() const = 0;
2026
2027 virtual bool isLeak() const { return false; }
2028 };
2029
2030 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2031 public:
2032 UseAfterRelease(CFRefCount* tf)
2033 : CFRefBug(tf, "Use-after-release") {}
2034
2035 const char* getDescription() const {
2036 return "Reference-counted object is used after it is released";
2037 }
2038 };
2039
2040 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2041 public:
2042 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
2043
2044 const char* getDescription() const {
2045 return "Incorrect decrement of the reference count of an "
2046 "object is not owned at this point by the caller";
2047 }
2048 };
2049
2050 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2051 public:
Ted Kremenek369de562009-05-09 00:10:05 +00002052 DeallocGC(CFRefCount *tf)
2053 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002054
2055 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00002056 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00002057 }
2058 };
2059
2060 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2061 public:
Ted Kremenek369de562009-05-09 00:10:05 +00002062 DeallocNotOwned(CFRefCount *tf)
2063 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002064
2065 const char *getDescription() const {
2066 return "-dealloc sent to object that may be referenced elsewhere";
2067 }
2068 };
2069
Ted Kremenek369de562009-05-09 00:10:05 +00002070 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
2071 public:
2072 OverAutorelease(CFRefCount *tf) :
2073 CFRefBug(tf, "Object sent -autorelease too many times") {}
2074
2075 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002076 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00002077 }
2078 };
2079
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002080 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
2081 public:
2082 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2083 CFRefBug(tf, "Method should return an owned object") {}
2084
2085 const char *getDescription() const {
2086 return "Object with +0 retain counts returned to caller where a +1 "
2087 "(owning) retain count is expected";
2088 }
2089 };
2090
Ted Kremenekc887d132009-04-29 18:50:19 +00002091 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2092 const bool isReturn;
2093 protected:
2094 Leak(CFRefCount* tf, const char* name, bool isRet)
2095 : CFRefBug(tf, name), isReturn(isRet) {}
2096 public:
2097
2098 const char* getDescription() const { return ""; }
2099
2100 bool isLeak() const { return true; }
2101 };
2102
2103 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2104 public:
2105 LeakAtReturn(CFRefCount* tf, const char* name)
2106 : Leak(tf, name, true) {}
2107 };
2108
2109 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2110 public:
2111 LeakWithinFunction(CFRefCount* tf, const char* name)
2112 : Leak(tf, name, false) {}
2113 };
2114
2115 //===---------===//
2116 // Bug Reports. //
2117 //===---------===//
2118
2119 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2120 protected:
2121 SymbolRef Sym;
2122 const CFRefCount &TF;
2123 public:
2124 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2125 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002126 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2127
2128 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2129 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu264e9372009-05-12 10:10:00 +00002130 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002131
2132 virtual ~CFRefReport() {}
2133
2134 CFRefBug& getBugType() {
2135 return (CFRefBug&) RangedBugReport::getBugType();
2136 }
2137 const CFRefBug& getBugType() const {
2138 return (const CFRefBug&) RangedBugReport::getBugType();
2139 }
2140
2141 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2142 const SourceRange*& end) {
2143
2144 if (!getBugType().isLeak())
2145 RangedBugReport::getRanges(BR, beg, end);
2146 else
2147 beg = end = 0;
2148 }
2149
2150 SymbolRef getSymbol() const { return Sym; }
2151
Ted Kremenek8966bc12009-05-06 21:39:49 +00002152 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002153 const ExplodedNode<GRState>* N);
2154
2155 std::pair<const char**,const char**> getExtraDescriptiveText();
2156
2157 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2158 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002159 BugReporterContext& BRC);
Ted Kremenekc887d132009-04-29 18:50:19 +00002160 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002161
Ted Kremenekc887d132009-04-29 18:50:19 +00002162 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2163 SourceLocation AllocSite;
2164 const MemRegion* AllocBinding;
2165 public:
2166 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2167 ExplodedNode<GRState> *n, SymbolRef sym,
2168 GRExprEngine& Eng);
2169
Ted Kremenek8966bc12009-05-06 21:39:49 +00002170 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002171 const ExplodedNode<GRState>* N);
2172
2173 SourceLocation getLocation() const { return AllocSite; }
2174 };
2175} // end anonymous namespace
2176
2177void CFRefCount::RegisterChecks(BugReporter& BR) {
2178 useAfterRelease = new UseAfterRelease(this);
2179 BR.Register(useAfterRelease);
2180
2181 releaseNotOwned = new BadRelease(this);
2182 BR.Register(releaseNotOwned);
2183
2184 deallocGC = new DeallocGC(this);
2185 BR.Register(deallocGC);
2186
2187 deallocNotOwned = new DeallocNotOwned(this);
2188 BR.Register(deallocNotOwned);
2189
Ted Kremenek369de562009-05-09 00:10:05 +00002190 overAutorelease = new OverAutorelease(this);
2191 BR.Register(overAutorelease);
2192
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002193 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2194 BR.Register(returnNotOwnedForOwned);
2195
Ted Kremenekc887d132009-04-29 18:50:19 +00002196 // First register "return" leaks.
2197 const char* name = 0;
2198
2199 if (isGCEnabled())
2200 name = "Leak of returned object when using garbage collection";
2201 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2202 name = "Leak of returned object when not using garbage collection (GC) in "
2203 "dual GC/non-GC code";
2204 else {
2205 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2206 name = "Leak of returned object";
2207 }
2208
2209 leakAtReturn = new LeakAtReturn(this, name);
2210 BR.Register(leakAtReturn);
2211
2212 // Second, register leaks within a function/method.
2213 if (isGCEnabled())
2214 name = "Leak of object when using garbage collection";
2215 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2216 name = "Leak of object when not using garbage collection (GC) in "
2217 "dual GC/non-GC code";
2218 else {
2219 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2220 name = "Leak";
2221 }
2222
2223 leakWithinFunction = new LeakWithinFunction(this, name);
2224 BR.Register(leakWithinFunction);
2225
2226 // Save the reference to the BugReporter.
2227 this->BR = &BR;
2228}
2229
2230static const char* Msgs[] = {
2231 // GC only
2232 "Code is compiled to only use garbage collection",
2233 // No GC.
2234 "Code is compiled to use reference counts",
2235 // Hybrid, with GC.
2236 "Code is compiled to use either garbage collection (GC) or reference counts"
2237 " (non-GC). The bug occurs with GC enabled",
2238 // Hybrid, without GC
2239 "Code is compiled to use either garbage collection (GC) or reference counts"
2240 " (non-GC). The bug occurs in non-GC mode"
2241};
2242
2243std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2244 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2245
2246 switch (TF.getLangOptions().getGCMode()) {
2247 default:
2248 assert(false);
2249
2250 case LangOptions::GCOnly:
2251 assert (TF.isGCEnabled());
2252 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2253
2254 case LangOptions::NonGC:
2255 assert (!TF.isGCEnabled());
2256 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2257
2258 case LangOptions::HybridGC:
2259 if (TF.isGCEnabled())
2260 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2261 else
2262 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2263 }
2264}
2265
2266static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2267 ArgEffect X) {
2268 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2269 I!=E; ++I)
2270 if (*I == X) return true;
2271
2272 return false;
2273}
2274
2275PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2276 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002277 BugReporterContext& BRC) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002278
Ted Kremenek2033a952009-05-13 07:12:33 +00002279 if (!isa<PostStmt>(N->getLocation()))
2280 return NULL;
2281
Ted Kremenek8966bc12009-05-06 21:39:49 +00002282 // Check if the type state has changed.
Ted Kremenekb65be702009-06-18 01:23:53 +00002283 const GRState *PrevSt = PrevN->getState();
2284 const GRState *CurrSt = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002285
Ted Kremenekb65be702009-06-18 01:23:53 +00002286 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002287 if (!CurrT) return NULL;
2288
Ted Kremenekb65be702009-06-18 01:23:53 +00002289 const RefVal &CurrV = *CurrT;
2290 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002291
2292 // Create a string buffer to constain all the useful things we want
2293 // to tell the user.
2294 std::string sbuf;
2295 llvm::raw_string_ostream os(sbuf);
2296
2297 // This is the allocation site since the previous node had no bindings
2298 // for this symbol.
2299 if (!PrevT) {
2300 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2301
2302 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2303 // Get the name of the callee (if it is available).
Ted Kremenekb65be702009-06-18 01:23:53 +00002304 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
Ted Kremenekc887d132009-04-29 18:50:19 +00002305 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2306 os << "Call to function '" << FD->getNameAsString() <<'\'';
2307 else
2308 os << "function call";
2309 }
2310 else {
2311 assert (isa<ObjCMessageExpr>(S));
2312 os << "Method";
2313 }
2314
2315 if (CurrV.getObjKind() == RetEffect::CF) {
2316 os << " returns a Core Foundation object with a ";
2317 }
2318 else {
2319 assert (CurrV.getObjKind() == RetEffect::ObjC);
2320 os << " returns an Objective-C object with a ";
2321 }
2322
2323 if (CurrV.isOwned()) {
2324 os << "+1 retain count (owning reference).";
2325
2326 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2327 assert(CurrV.getObjKind() == RetEffect::CF);
2328 os << " "
2329 "Core Foundation objects are not automatically garbage collected.";
2330 }
2331 }
2332 else {
2333 assert (CurrV.isNotOwned());
2334 os << "+0 retain count (non-owning reference).";
2335 }
2336
Ted Kremenek8966bc12009-05-06 21:39:49 +00002337 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002338 return new PathDiagnosticEventPiece(Pos, os.str());
2339 }
2340
2341 // Gather up the effects that were performed on the object at this
2342 // program point
2343 llvm::SmallVector<ArgEffect, 2> AEffects;
2344
Ted Kremenek8966bc12009-05-06 21:39:49 +00002345 if (const RetainSummary *Summ =
2346 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002347 // We only have summaries attached to nodes after evaluating CallExpr and
2348 // ObjCMessageExprs.
2349 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2350
2351 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2352 // Iterate through the parameter expressions and see if the symbol
2353 // was ever passed as an argument.
2354 unsigned i = 0;
2355
2356 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2357 AI!=AE; ++AI, ++i) {
2358
2359 // Retrieve the value of the argument. Is it the symbol
2360 // we are interested in?
Ted Kremenekb65be702009-06-18 01:23:53 +00002361 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002362 continue;
2363
2364 // We have an argument. Get the effect!
2365 AEffects.push_back(Summ->getArg(i));
2366 }
2367 }
2368 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2369 if (Expr *receiver = ME->getReceiver())
Ted Kremenekb65be702009-06-18 01:23:53 +00002370 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002371 // The symbol we are tracking is the receiver.
2372 AEffects.push_back(Summ->getReceiverEffect());
2373 }
2374 }
2375 }
2376
2377 do {
2378 // Get the previous type state.
2379 RefVal PrevV = *PrevT;
2380
2381 // Specially handle -dealloc.
2382 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2383 // Determine if the object's reference count was pushed to zero.
2384 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2385 // We may not have transitioned to 'release' if we hit an error.
2386 // This case is handled elsewhere.
2387 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002388 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002389 os << "Object released by directly sending the '-dealloc' message";
2390 break;
2391 }
2392 }
2393
2394 // Specially handle CFMakeCollectable and friends.
2395 if (contains(AEffects, MakeCollectable)) {
2396 // Get the name of the function.
2397 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekb65be702009-06-18 01:23:53 +00002398 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
Ted Kremenekc887d132009-04-29 18:50:19 +00002399 const FunctionDecl* FD = X.getAsFunctionDecl();
2400 const std::string& FName = FD->getNameAsString();
2401
2402 if (TF.isGCEnabled()) {
2403 // Determine if the object's reference count was pushed to zero.
2404 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2405
2406 os << "In GC mode a call to '" << FName
2407 << "' decrements an object's retain count and registers the "
2408 "object with the garbage collector. ";
2409
2410 if (CurrV.getKind() == RefVal::Released) {
2411 assert(CurrV.getCount() == 0);
2412 os << "Since it now has a 0 retain count the object can be "
2413 "automatically collected by the garbage collector.";
2414 }
2415 else
2416 os << "An object must have a 0 retain count to be garbage collected. "
2417 "After this call its retain count is +" << CurrV.getCount()
2418 << '.';
2419 }
2420 else
2421 os << "When GC is not enabled a call to '" << FName
2422 << "' has no effect on its argument.";
2423
2424 // Nothing more to say.
2425 break;
2426 }
2427
2428 // Determine if the typestate has changed.
2429 if (!(PrevV == CurrV))
2430 switch (CurrV.getKind()) {
2431 case RefVal::Owned:
2432 case RefVal::NotOwned:
2433
Ted Kremenekf21332e2009-05-08 20:01:42 +00002434 if (PrevV.getCount() == CurrV.getCount()) {
2435 // Did an autorelease message get sent?
2436 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2437 return 0;
2438
Zhongxing Xu264e9372009-05-12 10:10:00 +00002439 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002440 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002441 break;
2442 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002443
2444 if (PrevV.getCount() > CurrV.getCount())
2445 os << "Reference count decremented.";
2446 else
2447 os << "Reference count incremented.";
2448
2449 if (unsigned Count = CurrV.getCount())
2450 os << " The object now has a +" << Count << " retain count.";
2451
2452 if (PrevV.getKind() == RefVal::Released) {
2453 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2454 os << " The object is not eligible for garbage collection until the "
2455 "retain count reaches 0 again.";
2456 }
2457
2458 break;
2459
2460 case RefVal::Released:
2461 os << "Object released.";
2462 break;
2463
2464 case RefVal::ReturnedOwned:
2465 os << "Object returned to caller as an owning reference (single retain "
2466 "count transferred to caller).";
2467 break;
2468
2469 case RefVal::ReturnedNotOwned:
2470 os << "Object returned to caller with a +0 (non-owning) retain count.";
2471 break;
2472
2473 default:
2474 return NULL;
2475 }
2476
2477 // Emit any remaining diagnostics for the argument effects (if any).
2478 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2479 E=AEffects.end(); I != E; ++I) {
2480
2481 // A bunch of things have alternate behavior under GC.
2482 if (TF.isGCEnabled())
2483 switch (*I) {
2484 default: break;
2485 case Autorelease:
2486 os << "In GC mode an 'autorelease' has no effect.";
2487 continue;
2488 case IncRefMsg:
2489 os << "In GC mode the 'retain' message has no effect.";
2490 continue;
2491 case DecRefMsg:
2492 os << "In GC mode the 'release' message has no effect.";
2493 continue;
2494 }
2495 }
2496 } while(0);
2497
2498 if (os.str().empty())
2499 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002500
2501 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek8966bc12009-05-06 21:39:49 +00002502 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002503 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2504
2505 // Add the range by scanning the children of the statement for any bindings
2506 // to Sym.
2507 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2508 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb65be702009-06-18 01:23:53 +00002509 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002510 P->addRange(Exp->getSourceRange());
2511 break;
2512 }
2513
2514 return P;
2515}
2516
2517namespace {
2518 class VISIBILITY_HIDDEN FindUniqueBinding :
2519 public StoreManager::BindingsHandler {
2520 SymbolRef Sym;
2521 const MemRegion* Binding;
2522 bool First;
2523
2524 public:
2525 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2526
2527 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2528 SVal val) {
2529
2530 SymbolRef SymV = val.getAsSymbol();
2531 if (!SymV || SymV != Sym)
2532 return true;
2533
2534 if (Binding) {
2535 First = false;
2536 return false;
2537 }
2538 else
2539 Binding = R;
2540
2541 return true;
2542 }
2543
2544 operator bool() { return First && Binding; }
2545 const MemRegion* getRegion() { return Binding; }
2546 };
2547}
2548
2549static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2550GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2551 SymbolRef Sym) {
2552
2553 // Find both first node that referred to the tracked symbol and the
2554 // memory location that value was store to.
2555 const ExplodedNode<GRState>* Last = N;
2556 const MemRegion* FirstBinding = 0;
2557
2558 while (N) {
2559 const GRState* St = N->getState();
2560 RefBindings B = St->get<RefBindings>();
2561
2562 if (!B.lookup(Sym))
2563 break;
2564
2565 FindUniqueBinding FB(Sym);
2566 StateMgr.iterBindings(St, FB);
2567 if (FB) FirstBinding = FB.getRegion();
2568
2569 Last = N;
2570 N = N->pred_empty() ? NULL : *(N->pred_begin());
2571 }
2572
2573 return std::make_pair(Last, FirstBinding);
2574}
2575
2576PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002577CFRefReport::getEndPath(BugReporterContext& BRC,
2578 const ExplodedNode<GRState>* EndN) {
2579 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002580 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002581 BRC.addNotableSymbol(Sym);
2582 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenekc887d132009-04-29 18:50:19 +00002583}
2584
2585PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002586CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2587 const ExplodedNode<GRState>* EndN){
Ted Kremenekc887d132009-04-29 18:50:19 +00002588
Ted Kremenek8966bc12009-05-06 21:39:49 +00002589 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002590 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002591 BRC.addNotableSymbol(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002592
2593 // We are reporting a leak. Walk up the graph to get to the first node where
2594 // the symbol appeared, and also get the first VarDecl that tracked object
2595 // is stored to.
2596 const ExplodedNode<GRState>* AllocNode = 0;
2597 const MemRegion* FirstBinding = 0;
2598
2599 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002600 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002601
2602 // Get the allocate site.
2603 assert(AllocNode);
2604 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2605
Ted Kremenek8966bc12009-05-06 21:39:49 +00002606 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002607 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2608
2609 // Compute an actual location for the leak. Sometimes a leak doesn't
2610 // occur at an actual statement (e.g., transition between blocks; end
2611 // of function) so we need to walk the graph and compute a real location.
2612 const ExplodedNode<GRState>* LeakN = EndN;
2613 PathDiagnosticLocation L;
2614
2615 while (LeakN) {
2616 ProgramPoint P = LeakN->getLocation();
2617
2618 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2619 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2620 break;
2621 }
2622 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2623 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2624 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2625 break;
2626 }
2627 }
2628
2629 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2630 }
2631
2632 if (!L.isValid()) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00002633 const Decl &D = BRC.getCodeDecl();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002634 L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
Ted Kremenekc887d132009-04-29 18:50:19 +00002635 }
2636
2637 std::string sbuf;
2638 llvm::raw_string_ostream os(sbuf);
2639
2640 os << "Object allocated on line " << AllocLine;
2641
2642 if (FirstBinding)
2643 os << " and stored into '" << FirstBinding->getString() << '\'';
2644
2645 // Get the retain count.
2646 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2647
2648 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2649 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2650 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2651 // to the caller for NS objects.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002652 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenekc887d132009-04-29 18:50:19 +00002653 os << " is returned from a method whose name ('"
Ted Kremeneka8833552009-04-29 23:03:22 +00002654 << MD.getSelector().getAsString()
Ted Kremenekc887d132009-04-29 18:50:19 +00002655 << "') does not contain 'copy' or otherwise starts with"
2656 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek8987a022009-04-29 22:25:52 +00002657 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002658 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002659 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2660 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2661 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002662 << "' is potentially leaked when using garbage collection. Callers "
2663 "of this method do not expect a returned object with a +1 retain "
2664 "count since they expect the object to be managed by the garbage "
2665 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002666 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002667 else
2668 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek8987a022009-04-29 22:25:52 +00002669 " +" << RV->getCount() << " (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002670
2671 return new PathDiagnosticEventPiece(L, os.str());
2672}
2673
Ted Kremenekc887d132009-04-29 18:50:19 +00002674CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2675 ExplodedNode<GRState> *n,
2676 SymbolRef sym, GRExprEngine& Eng)
2677: CFRefReport(D, tf, n, sym)
2678{
2679
2680 // Most bug reports are cached at the location where they occured.
2681 // With leaks, we want to unique them by the location where they were
2682 // allocated, and only report a single path. To do this, we need to find
2683 // the allocation site of a piece of tracked memory, which we do via a
2684 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2685 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2686 // that all ancestor nodes that represent the allocation site have the
2687 // same SourceLocation.
2688 const ExplodedNode<GRState>* AllocNode = 0;
2689
2690 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekf04dced2009-05-08 23:32:51 +00002691 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenekc887d132009-04-29 18:50:19 +00002692
2693 // Get the SourceLocation for the allocation site.
2694 ProgramPoint P = AllocNode->getLocation();
2695 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2696
2697 // Fill in the description of the bug.
2698 Description.clear();
2699 llvm::raw_string_ostream os(Description);
2700 SourceManager& SMgr = Eng.getContext().getSourceManager();
2701 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002702 os << "Potential leak ";
2703 if (tf.isGCEnabled()) {
2704 os << "(when using garbage collection) ";
2705 }
2706 os << "of an object allocated on line " << AllocLine;
Ted Kremenekc887d132009-04-29 18:50:19 +00002707
2708 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2709 if (AllocBinding)
2710 os << " and stored into '" << AllocBinding->getString() << '\'';
2711}
2712
2713//===----------------------------------------------------------------------===//
2714// Main checker logic.
2715//===----------------------------------------------------------------------===//
2716
Ted Kremenek553cf182008-06-25 21:21:56 +00002717/// GetReturnType - Used to get the return type of a message expression or
2718/// function call with the intention of affixing that type to a tracked symbol.
2719/// While the the return type can be queried directly from RetEx, when
2720/// invoking class methods we augment to the return type to be that of
2721/// a pointer to the class (as opposed it just being id).
2722static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2723
2724 QualType RetTy = RetE->getType();
2725
2726 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00002727 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002728 if (!PT)
2729 return RetTy;
2730
2731 // If RetEx is not a message expression just return its type.
2732 // If RetEx is a message expression, return its types if it is something
2733 /// more specific than id.
2734
2735 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2736
Steve Naroff389bf462009-02-12 17:52:19 +00002737 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00002738 return RetTy;
2739
2740 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2741
2742 // At this point we know the return type of the message expression is id.
2743 // If we have an ObjCInterceDecl, we know this is a call to a class method
2744 // whose type we can resolve. In such cases, promote the return type to
2745 // Class*.
2746 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2747}
2748
2749
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002750void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002751 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002752 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002753 Expr* Ex,
2754 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00002755 const RetainSummary& Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00002756 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002757 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002758
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002759 // Get the state.
Zhongxing Xu264e9372009-05-12 10:10:00 +00002760 GRStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekb65be702009-06-18 01:23:53 +00002761 const GRState *state = Builder.GetState(Pred);
Zhongxing Xu264e9372009-05-12 10:10:00 +00002762 ASTContext& Ctx = StateMgr.getContext();
2763 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek14993892008-05-06 02:41:27 +00002764
2765 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002766 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002767 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002768 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00002769 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002770
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002771 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002772 SVal V = state->getSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00002773 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002774
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002775 if (Sym)
Ted Kremenekb65be702009-06-18 01:23:53 +00002776 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002777 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002778 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002779 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002780 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002781 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00002782 }
2783 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002784 }
Ted Kremenek070a8252008-07-09 18:11:16 +00002785
Ted Kremenek94c96982009-03-03 22:06:47 +00002786 if (isa<Loc>(V)) {
2787 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002788 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenek070a8252008-07-09 18:11:16 +00002789 continue;
2790
Ted Kremenek6c07bdb2009-06-26 00:05:51 +00002791 // Invalidate the value of the variable passed by reference.
Ted Kremenek070a8252008-07-09 18:11:16 +00002792
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002793 // FIXME: We can have collisions on the conjured symbol if the
2794 // expression *I also creates conjured symbols. We probably want
2795 // to identify conjured symbols by an expression pair: the enclosing
2796 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00002797 // disambiguate conjured symbols.
Zhongxing Xua03f1572009-06-29 06:43:40 +00002798 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek993f1c72008-10-17 20:28:54 +00002799 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xuf82af1e2009-04-29 02:30:09 +00002800
Ted Kremenek42530512009-05-06 18:19:24 +00002801 if (R) {
2802 // Are we dealing with an ElementRegion? If the element type is
2803 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xu2e7c6782009-05-11 14:28:14 +00002804 // is a variable region then strip off the ElementRegion.
Ted Kremenek42530512009-05-06 18:19:24 +00002805 // FIXME: We really need to think about this for the general case
2806 // as sometimes we are reasoning about arrays and other times
2807 // about (char*), etc., is just a form of passing raw bytes.
2808 // e.g., void *p = alloca(); foo((char*)p);
2809 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2810 // Checking for 'integral type' is probably too promiscuous, but
2811 // we'll leave it in for now until we have a systematic way of
2812 // handling all of these cases. Eventually we need to come up
2813 // with an interface to StoreManager so that this logic can be
2814 // approriately delegated to the respective StoreManagers while
2815 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu264e9372009-05-12 10:10:00 +00002816 // invalidating reference counts), probably via callbacks.
Ted Kremenek109bf472009-05-11 22:55:17 +00002817 if (ER->getElementType()->isIntegralType()) {
2818 const MemRegion *superReg = ER->getSuperRegion();
2819 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2820 isa<ObjCIvarRegion>(superReg))
2821 R = cast<TypedRegion>(superReg);
2822 }
2823
Ted Kremenek42530512009-05-06 18:19:24 +00002824 // FIXME: What about layers of ElementRegions?
2825 }
2826
Ted Kremenek40e86d92008-12-18 23:34:57 +00002827 // Is the invalidated variable something that we were tracking?
Ted Kremenekb65be702009-06-18 01:23:53 +00002828 SymbolRef Sym = state->getSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00002829
Ted Kremenekd104a092009-03-04 22:56:43 +00002830 // Remove any existing reference-count binding.
Ted Kremenekb65be702009-06-18 01:23:53 +00002831 if (Sym) state = state->remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00002832
Ted Kremeneka43484a2009-06-23 00:46:41 +00002833 if (R->isBoundable()) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002834 // Set the value of the variable to be a conjured symbol.
Zhongxing Xua03f1572009-06-29 06:43:40 +00002835
Zhongxing Xua82d8aa2009-05-09 03:57:34 +00002836 QualType T = R->getValueType(Ctx);
Ted Kremenekd104a092009-03-04 22:56:43 +00002837
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002838 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002839 ValueManager &ValMgr = Eng.getValueManager();
2840 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xud91ee272009-06-23 09:02:15 +00002841 state = state->bindLoc(ValMgr.makeLoc(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002842 }
2843 else if (const RecordType *RT = T->getAsStructureType()) {
2844 // Handle structs in a not so awesome way. Here we just
2845 // eagerly bind new symbols to the fields. In reality we
2846 // should have the store manager handle this. The idea is just
2847 // to prototype some basic functionality here. All of this logic
2848 // should one day soon just go away.
2849 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2850
2851 // No record definition. There is nothing we can do.
2852 if (!RD)
2853 continue;
2854
Ted Kremenekb65be702009-06-18 01:23:53 +00002855 MemRegionManager &MRMgr =
2856 state->getStateManager().getRegionManager();
Ted Kremenekd104a092009-03-04 22:56:43 +00002857
2858 // Iterate through the fields and construct new symbols.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002859 for (RecordDecl::field_iterator FI=RD->field_begin(),
2860 FE=RD->field_end(); FI!=FE; ++FI) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002861
2862 // For now just handle scalar fields.
2863 FieldDecl *FD = *FI;
2864 QualType FT = FD->getType();
Zhongxing Xu6bd8a522009-06-28 13:59:24 +00002865 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
2866
Ted Kremenekd104a092009-03-04 22:56:43 +00002867 if (Loc::IsLocType(FT) ||
Zhongxing Xu264e9372009-05-12 10:10:00 +00002868 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002869 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xud91ee272009-06-23 09:02:15 +00002870 state = state->bindLoc(ValMgr.makeLoc(FR), V);
Zhongxing Xu6bd8a522009-06-28 13:59:24 +00002871 }
2872 else if (FT->isStructureType()) {
2873 // set the default value of the struct field to conjured
2874 // symbol. Note that the type of the symbol is irrelavant.
2875 // We cannot use the type of the struct otherwise ValMgr won't
2876 // give us the conjured symbol.
2877 StoreManager& StoreMgr =
2878 Eng.getStateManager().getStoreManager();
2879 SVal V = ValMgr.getConjuredSymbolVal(*I,
2880 Eng.getContext().IntTy,
2881 Count);
2882 state = StoreMgr.setDefaultValue(state, FR, V);
2883 }
Ted Kremenekd104a092009-03-04 22:56:43 +00002884 }
Zhongxing Xu264e9372009-05-12 10:10:00 +00002885 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2886 // Set the default value of the array to conjured symbol.
2887 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2888 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2889 Count);
Ted Kremenekb65be702009-06-18 01:23:53 +00002890 state = StoreMgr.setDefaultValue(state, R, V);
Zhongxing Xu264e9372009-05-12 10:10:00 +00002891 } else {
Ted Kremenekd104a092009-03-04 22:56:43 +00002892 // Just blast away other values.
Ted Kremenekb65be702009-06-18 01:23:53 +00002893 state = state->bindLoc(*MR, UnknownVal());
Ted Kremenekd104a092009-03-04 22:56:43 +00002894 }
Ted Kremenekfd301942008-10-17 22:23:12 +00002895 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002896 }
Zhongxing Xua03f1572009-06-29 06:43:40 +00002897 else if (isa<AllocaRegion>(MR->getRegion())) {
2898 // Invalidate the alloca region by setting its default value to
2899 // conjured symbol. The type of the symbol is irrelavant.
2900 SVal V = ValMgr.getConjuredSymbolVal(*I, Eng.getContext().IntTy,
2901 Count);
2902 StoreManager& StoreMgr =
2903 Eng.getStateManager().getStoreManager();
2904 state = StoreMgr.setDefaultValue(state, MR->getRegion(), V);
2905 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002906 else
Ted Kremenekb65be702009-06-18 01:23:53 +00002907 state = state->bindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002908 }
2909 else {
2910 // Nuke all other arguments passed by reference.
Ted Kremenekb65be702009-06-18 01:23:53 +00002911 state = state->unbindLoc(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002912 }
Ted Kremenekb8873552008-04-11 20:51:02 +00002913 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002914 else if (isa<nonloc::LocAsInteger>(V))
Ted Kremenekb65be702009-06-18 01:23:53 +00002915 state = state->unbindLoc(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002916 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002917
Ted Kremenek553cf182008-06-25 21:21:56 +00002918 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00002919 if (!ErrorExpr && Receiver) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002920 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002921 if (Sym) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002922 if (const RefVal* T = state->get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002923 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002924 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00002925 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002926 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00002927 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002928 }
Ted Kremenek14993892008-05-06 02:41:27 +00002929 }
2930 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002931
Ted Kremenek553cf182008-06-25 21:21:56 +00002932 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002933 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002934 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002935 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002936 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002937 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002938
Ted Kremenek70a733e2008-07-18 17:24:20 +00002939 // Consult the summary for the return value.
Ted Kremenek7faca822009-05-04 04:57:00 +00002940 RetEffect RE = Summ.getRetEffect();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002941
Ted Kremenek78a35a32009-05-12 20:06:54 +00002942 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2943 assert(Receiver);
Ted Kremenekb65be702009-06-18 01:23:53 +00002944 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek78a35a32009-05-12 20:06:54 +00002945 bool found = false;
2946 if (SymbolRef Sym = V.getAsLocSymbol())
Ted Kremenekb65be702009-06-18 01:23:53 +00002947 if (state->get<RefBindings>(Sym)) {
Ted Kremenek78a35a32009-05-12 20:06:54 +00002948 found = true;
2949 RE = Summaries.getObjAllocRetEffect();
2950 }
2951
2952 if (!found)
2953 RE = RetEffect::MakeNoRet();
2954 }
2955
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002956 switch (RE.getKind()) {
2957 default:
2958 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002959
Ted Kremenek6c07bdb2009-06-26 00:05:51 +00002960 case RetEffect::NoRet: {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002961 // Make up a symbol for the return value (not reference counted).
Ted Kremenek6c07bdb2009-06-26 00:05:51 +00002962 // FIXME: Most of this logic is not specific to the retain/release
2963 // checker.
Ted Kremenekf9561e52008-04-11 20:23:24 +00002964
Ted Kremenekfd301942008-10-17 22:23:12 +00002965 // FIXME: We eventually should handle structs and other compound types
2966 // that are returned by value.
2967
2968 QualType T = Ex->getType();
2969
Ted Kremenek062e2f92008-11-13 06:10:40 +00002970 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002971 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002972 ValueManager &ValMgr = Eng.getValueManager();
2973 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenekb65be702009-06-18 01:23:53 +00002974 state = state->bindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00002975 }
2976
Ted Kremenek940b1d82008-04-10 23:44:06 +00002977 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00002978 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002979
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002980 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00002981 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00002982 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002983 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb65be702009-06-18 01:23:53 +00002984 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
2985 state = state->bindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002986 break;
2987 }
2988
Ted Kremenek14993892008-05-06 02:41:27 +00002989 case RetEffect::ReceiverAlias: {
2990 assert (Receiver);
Ted Kremenekb65be702009-06-18 01:23:53 +00002991 SVal V = state->getSValAsScalarOrLoc(Receiver);
2992 state = state->bindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00002993 break;
2994 }
2995
Ted Kremeneka7344702008-06-23 18:02:52 +00002996 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002997 case RetEffect::OwnedSymbol: {
2998 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002999 ValueManager &ValMgr = Eng.getValueManager();
3000 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
3001 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekb65be702009-06-18 01:23:53 +00003002 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
Ted Kremenek044b6f02009-04-09 16:13:17 +00003003 RetT));
Zhongxing Xud91ee272009-06-23 09:02:15 +00003004 state = state->bindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00003005
3006 // FIXME: Add a flag to the checker where allocations are assumed to
3007 // *not fail.
3008#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00003009 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
3010 bool isFeasible;
3011 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
3012 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
3013 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00003014#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00003015
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00003016 break;
3017 }
Ted Kremeneke798e7c2009-04-27 19:14:45 +00003018
3019 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00003020 case RetEffect::NotOwnedSymbol: {
3021 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00003022 ValueManager &ValMgr = Eng.getValueManager();
3023 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
3024 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekb65be702009-06-18 01:23:53 +00003025 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
Ted Kremenek044b6f02009-04-09 16:13:17 +00003026 RetT));
Zhongxing Xud91ee272009-06-23 09:02:15 +00003027 state = state->bindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00003028 break;
3029 }
3030 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003031
Ted Kremenekf5b34b12009-02-18 02:00:25 +00003032 // Generate a sink node if we are at the end of a path.
3033 GRExprEngine::NodeTy *NewNode =
Ted Kremenek7faca822009-05-04 04:57:00 +00003034 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
3035 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekf5b34b12009-02-18 02:00:25 +00003036
3037 // Annotate the edge with summary we used.
Ted Kremenek7faca822009-05-04 04:57:00 +00003038 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003039}
3040
3041
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003042void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003043 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003044 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00003045 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003046 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00003047 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek7faca822009-05-04 04:57:00 +00003048 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xu369f4472009-04-20 05:24:46 +00003049 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003050
Ted Kremenek7faca822009-05-04 04:57:00 +00003051 assert(Summ);
3052 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003053 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00003054}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003055
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003056void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00003057 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003058 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00003059 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003060 ExplodedNode<GRState>* Pred) {
Ted Kremenek7faca822009-05-04 04:57:00 +00003061 RetainSummary* Summ = 0;
Ted Kremenek9040c652008-05-01 21:31:50 +00003062
Ted Kremenek553cf182008-06-25 21:21:56 +00003063 if (Expr* Receiver = ME->getReceiver()) {
3064 // We need the type-information of the tracked receiver object
3065 // Retrieve it from the state.
Ted Kremenek70b6a832009-05-13 18:16:01 +00003066 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek553cf182008-06-25 21:21:56 +00003067
3068 // FIXME: Wouldn't it be great if this code could be reduced? It's just
3069 // a chain of lookups.
Ted Kremenek8711c032009-04-29 05:04:30 +00003070 // FIXME: Is this really working as expected? There are cases where
3071 // we just use the 'ID' from the message expression.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003072 const GRState* St = Builder.GetState(Pred);
Ted Kremenek23ec48c2009-06-18 23:58:37 +00003073 SVal V = St->getSValAsScalarOrLoc(Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00003074
Ted Kremenek94c96982009-03-03 22:06:47 +00003075 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00003076 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003077 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00003078 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00003079
3080 if (const PointerType* PT = Ty->getAsPointerType()) {
3081 QualType PointeeTy = PT->getPointeeType();
3082
3083 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
3084 ID = IT->getDecl();
3085 }
3086 }
3087 }
Ted Kremenek70b6a832009-05-13 18:16:01 +00003088
3089 // FIXME: this is a hack. This may or may not be the actual method
3090 // that is called.
3091 if (!ID) {
3092 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
3093 if (const ObjCInterfaceType *p =
3094 PT->getPointeeType()->getAsObjCInterfaceType())
3095 ID = p->getDecl();
3096 }
3097
Ted Kremenekce8a41d2009-04-29 17:09:14 +00003098 // FIXME: The receiver could be a reference to a class, meaning that
3099 // we should use the class method.
3100 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00003101
Ted Kremenek896cd9d2008-10-23 01:56:15 +00003102 // Special-case: are we sending a mesage to "self"?
3103 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek885c27b2009-05-04 05:31:22 +00003104 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
3105 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenek23ec48c2009-06-18 23:58:37 +00003106 SVal X = St->getSValAsScalarOrLoc(Receiver);
Ted Kremenek885c27b2009-05-04 05:31:22 +00003107 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek25e751a2009-06-23 21:37:46 +00003108 if (L->getRegion() == St->getSelfRegion()) {
Ted Kremenek885c27b2009-05-04 05:31:22 +00003109 // Update the summary to make the default argument effect
3110 // 'StopTracking'.
3111 Summ = Summaries.copySummary(Summ);
3112 Summ->setDefaultArgEffect(StopTracking);
3113 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00003114 }
3115 }
Ted Kremenek553cf182008-06-25 21:21:56 +00003116 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003117 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00003118 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003119
Ted Kremenek7faca822009-05-04 04:57:00 +00003120 if (!Summ)
3121 Summ = Summaries.getDefaultSummary();
Ted Kremenekde4d5332009-04-24 17:50:11 +00003122
Ted Kremenek7faca822009-05-04 04:57:00 +00003123 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenekb3095252008-05-06 04:20:12 +00003124 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00003125}
Ted Kremenek5216ad72009-02-14 03:16:10 +00003126
3127namespace {
3128class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
Ted Kremenek3a772032009-06-18 00:49:02 +00003129 const GRState *state;
Ted Kremenek5216ad72009-02-14 03:16:10 +00003130public:
Ted Kremenek3a772032009-06-18 00:49:02 +00003131 StopTrackingCallback(const GRState *st) : state(st) {}
3132 const GRState *getState() const { return state; }
Ted Kremenek5216ad72009-02-14 03:16:10 +00003133
3134 bool VisitSymbol(SymbolRef sym) {
Ted Kremenek3a772032009-06-18 00:49:02 +00003135 state = state->remove<RefBindings>(sym);
Ted Kremenek5216ad72009-02-14 03:16:10 +00003136 return true;
3137 }
Ted Kremenek5216ad72009-02-14 03:16:10 +00003138};
3139} // end anonymous namespace
3140
3141
Ted Kremenek41573eb2009-02-14 01:43:44 +00003142void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00003143 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00003144 bool escapes = false;
3145
Ted Kremeneka496d162008-10-18 03:49:51 +00003146 // A value escapes in three possible cases (this may change):
3147 //
3148 // (1) we are binding to something that is not a memory region.
3149 // (2) we are binding to a memregion that does not have stack storage
3150 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00003151 // does not understand.
Ted Kremenek3a772032009-06-18 00:49:02 +00003152 const GRState *state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00003153
Ted Kremenek41573eb2009-02-14 01:43:44 +00003154 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00003155 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00003156 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00003157 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
Ted Kremenekea20cd72009-06-23 18:05:21 +00003158 escapes = !R->hasStackStorage();
Ted Kremeneka496d162008-10-18 03:49:51 +00003159
3160 if (!escapes) {
3161 // To test (3), generate a new state with the binding removed. If it is
3162 // the same state, then it escapes (since the store cannot represent
3163 // the binding).
Ted Kremenekb65be702009-06-18 01:23:53 +00003164 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00003165 }
Ted Kremenek9e240492008-10-04 05:50:14 +00003166 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00003167
Ted Kremenek5216ad72009-02-14 03:16:10 +00003168 // If our store can represent the binding and we aren't storing to something
3169 // that doesn't have local storage then just return and have the simulation
3170 // state continue as is.
3171 if (!escapes)
3172 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00003173
Ted Kremenek5216ad72009-02-14 03:16:10 +00003174 // Otherwise, find all symbols referenced by 'val' that we are tracking
3175 // and stop tracking them.
Ted Kremenek3a772032009-06-18 00:49:02 +00003176 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00003177}
3178
Ted Kremenek4fd88972008-04-17 18:12:53 +00003179 // Return statements.
3180
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003181void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00003182 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003183 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00003184 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003185 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003186
3187 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00003188 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00003189 return;
3190
Ted Kremenekb65be702009-06-18 01:23:53 +00003191 const GRState *state = Builder.GetState(Pred);
3192 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00003193
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00003194 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00003195 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003196
Ted Kremenek4fd88972008-04-17 18:12:53 +00003197 // Get the reference count binding (if any).
Ted Kremenekb65be702009-06-18 01:23:53 +00003198 const RefVal* T = state->get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00003199
3200 if (!T)
3201 return;
3202
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003203 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00003204 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003205
Ted Kremenek78a35a32009-05-12 20:06:54 +00003206 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003207 case RefVal::Owned: {
3208 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003209 assert (cnt > 0);
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003210 X.setCount(cnt - 1);
3211 X = X ^ RefVal::ReturnedOwned;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003212 break;
3213 }
3214
3215 case RefVal::NotOwned: {
3216 unsigned cnt = X.getCount();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003217 if (cnt) {
3218 X.setCount(cnt - 1);
3219 X = X ^ RefVal::ReturnedOwned;
3220 }
3221 else {
3222 X = X ^ RefVal::ReturnedNotOwned;
3223 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003224 break;
3225 }
3226
3227 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00003228 return;
3229 }
3230
3231 // Update the binding.
Ted Kremenekb65be702009-06-18 01:23:53 +00003232 state = state->set<RefBindings>(Sym, X);
Ted Kremenekc887d132009-04-29 18:50:19 +00003233 Pred = Builder.MakeNode(Dst, S, Pred, state);
3234
Ted Kremenek9f246b62009-04-30 05:51:50 +00003235 // Did we cache out?
3236 if (!Pred)
3237 return;
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003238
3239 // Update the autorelease counts.
3240 static unsigned autoreleasetag = 0;
3241 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3242 bool stop = false;
3243 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3244 X, stop);
3245
3246 // Did we cache out?
3247 if (!Pred || stop)
3248 return;
3249
3250 // Get the updated binding.
Ted Kremenekb65be702009-06-18 01:23:53 +00003251 T = state->get<RefBindings>(Sym);
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003252 assert(T);
3253 X = *T;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003254
Ted Kremenekc887d132009-04-29 18:50:19 +00003255 // Any leaks or other errors?
3256 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003257 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremeneka8833552009-04-29 23:03:22 +00003258 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00003259 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003260 RetEffect RE = Summ.getRetEffect();
3261 bool hasError = false;
3262
Ted Kremenekfae664a2009-05-16 01:38:01 +00003263 if (RE.getKind() != RetEffect::NoRet) {
3264 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3265 // Things are more complicated with garbage collection. If the
3266 // returned object is suppose to be an Objective-C object, we have
3267 // a leak (as the caller expects a GC'ed object) because no
3268 // method should return ownership unless it returns a CF object.
3269 X = X ^ RefVal::ErrorGCLeakReturned;
3270
3271 // Keep this false until this is properly tested.
3272 hasError = true;
3273 }
3274 else if (!RE.isOwned()) {
3275 // Either we are using GC and the returned object is a CF type
3276 // or we aren't using GC. In either case, we expect that the
3277 // enclosing method is expected to return ownership.
3278 hasError = true;
3279 X = X ^ RefVal::ErrorLeakReturned;
3280 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003281 }
3282
3283 if (hasError) {
Ted Kremenekc887d132009-04-29 18:50:19 +00003284 // Generate an error node.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003285 static int ReturnOwnLeakTag = 0;
Ted Kremenekb65be702009-06-18 01:23:53 +00003286 state = state->set<RefBindings>(Sym, X);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003287 ExplodedNode<GRState> *N =
3288 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3289 if (N) {
3290 CFRefReport *report =
Ted Kremenek9f246b62009-04-30 05:51:50 +00003291 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3292 N, Sym, Eng);
3293 BR->EmitReport(report);
3294 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003295 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003296 }
3297 }
3298 else if (X.isReturnedNotOwned()) {
3299 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3300 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3301 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3302 if (Summ.getRetEffect().isOwned()) {
3303 // Trying to return a not owned object to a caller expecting an
3304 // owned object.
3305
3306 static int ReturnNotOwnedForOwnedTag = 0;
Ted Kremenekb65be702009-06-18 01:23:53 +00003307 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003308 if (ExplodedNode<GRState> *N =
3309 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3310 state, Pred)) {
3311 CFRefReport *report =
3312 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3313 *this, N, Sym);
3314 BR->EmitReport(report);
3315 }
3316 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003317 }
3318 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003319}
3320
Ted Kremenekcb612922008-04-18 19:23:43 +00003321// Assumptions.
3322
Ted Kremeneka591bc02009-06-18 22:57:13 +00003323const GRState* CFRefCount::EvalAssume(const GRState *state,
3324 SVal Cond, bool Assumption) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003325
3326 // FIXME: We may add to the interface of EvalAssume the list of symbols
3327 // whose assumptions have changed. For now we just iterate through the
3328 // bindings and check if any of the tracked symbols are NULL. This isn't
3329 // too bad since the number of symbols we will track in practice are
3330 // probably small and EvalAssume is only called at branches and a few
3331 // other places.
Ted Kremenekb65be702009-06-18 01:23:53 +00003332 RefBindings B = state->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003333
3334 if (B.isEmpty())
Ted Kremenekb65be702009-06-18 01:23:53 +00003335 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003336
Ted Kremenekb65be702009-06-18 01:23:53 +00003337 bool changed = false;
3338 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003339
3340 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003341 // Check if the symbol is null (or equal to any constant).
3342 // If this is the case, stop tracking the symbol.
Ted Kremeneka591bc02009-06-18 22:57:13 +00003343 if (state->getSymVal(I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003344 changed = true;
3345 B = RefBFactory.Remove(B, I.getKey());
3346 }
3347 }
3348
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003349 if (changed)
Ted Kremenekb65be702009-06-18 01:23:53 +00003350 state = state->set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00003351
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003352 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003353}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003354
Ted Kremenekb65be702009-06-18 01:23:53 +00003355const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003356 RefVal V, ArgEffect E,
3357 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00003358
3359 // In GC mode [... release] and [... retain] do nothing.
3360 switch (E) {
3361 default: break;
3362 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3363 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00003364 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00003365 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3366 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003367 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003368
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003369 // Handle all use-after-releases.
3370 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3371 V = V ^ RefVal::ErrorUseAfterRelease;
3372 hasErr = V.getKind();
Ted Kremenekb65be702009-06-18 01:23:53 +00003373 return state->set<RefBindings>(sym, V);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003374 }
3375
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003376 switch (E) {
3377 default:
3378 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003379
3380 case Dealloc:
3381 // Any use of -dealloc in GC is *bad*.
3382 if (isGCEnabled()) {
3383 V = V ^ RefVal::ErrorDeallocGC;
3384 hasErr = V.getKind();
3385 break;
3386 }
3387
3388 switch (V.getKind()) {
3389 default:
3390 assert(false && "Invalid case.");
3391 case RefVal::Owned:
3392 // The object immediately transitions to the released state.
3393 V = V ^ RefVal::Released;
3394 V.clearCounts();
Ted Kremenekb65be702009-06-18 01:23:53 +00003395 return state->set<RefBindings>(sym, V);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003396 case RefVal::NotOwned:
3397 V = V ^ RefVal::ErrorDeallocNotOwned;
3398 hasErr = V.getKind();
3399 break;
3400 }
3401 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003402
Ted Kremenek35790732009-02-25 23:11:49 +00003403 case NewAutoreleasePool:
3404 assert(!isGCEnabled());
Ted Kremenekb65be702009-06-18 01:23:53 +00003405 return state->add<AutoreleaseStack>(sym);
Ted Kremenek35790732009-02-25 23:11:49 +00003406
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003407 case MayEscape:
3408 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00003409 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003410 break;
3411 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003412
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003413 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00003414
Ted Kremenek070a8252008-07-09 18:11:16 +00003415 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003416 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003417 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00003418
Ted Kremenekabf43972009-01-28 21:44:40 +00003419 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003420 if (isGCEnabled())
3421 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00003422
3423 // Update the autorelease counts.
3424 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf21332e2009-05-08 20:01:42 +00003425 V = V.autorelease();
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003426 break;
Ted Kremenek369de562009-05-09 00:10:05 +00003427
Ted Kremenek14993892008-05-06 02:41:27 +00003428 case StopTracking:
Ted Kremenekb65be702009-06-18 01:23:53 +00003429 return state->remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003430
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003431 case IncRef:
3432 switch (V.getKind()) {
3433 default:
3434 assert(false);
3435
3436 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003437 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00003438 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003439 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003440 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003441 // Non-GC cases are handled above.
3442 assert(isGCEnabled());
3443 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003444 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003445 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003446 break;
3447
Ted Kremenek553cf182008-06-25 21:21:56 +00003448 case SelfOwn:
3449 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003450 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003451 case DecRef:
3452 switch (V.getKind()) {
3453 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003454 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003455 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003456
Ted Kremenek553cf182008-06-25 21:21:56 +00003457 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00003458 assert(V.getCount() > 0);
3459 if (V.getCount() == 1) V = V ^ RefVal::Released;
3460 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003461 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003462
Ted Kremenek553cf182008-06-25 21:21:56 +00003463 case RefVal::NotOwned:
3464 if (V.getCount() > 0)
3465 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00003466 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00003467 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003468 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00003469 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003470 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003471
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003472 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003473 // Non-GC cases are handled above.
3474 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00003475 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003476 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003477 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003478 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003479 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003480 }
Ted Kremenekb65be702009-06-18 01:23:53 +00003481 return state->set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003482}
3483
Ted Kremenekfa34b332008-04-09 01:10:13 +00003484//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003485// Handle dead symbols and end-of-path.
3486//===----------------------------------------------------------------------===//
3487
Ted Kremenekb65be702009-06-18 01:23:53 +00003488std::pair<ExplodedNode<GRState>*, const GRState *>
3489CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Ted Kremenekf04dced2009-05-08 23:32:51 +00003490 ExplodedNode<GRState>* Pred,
Ted Kremenek369de562009-05-09 00:10:05 +00003491 GRExprEngine &Eng,
3492 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekf04dced2009-05-08 23:32:51 +00003493
Ted Kremenek369de562009-05-09 00:10:05 +00003494 unsigned ACnt = V.getAutoreleaseCount();
3495 stop = false;
3496
3497 // No autorelease counts? Nothing to be done.
3498 if (!ACnt)
3499 return std::make_pair(Pred, state);
3500
3501 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3502 unsigned Cnt = V.getCount();
3503
Ted Kremenek95d3b902009-05-11 15:26:06 +00003504 // FIXME: Handle sending 'autorelease' to already released object.
3505
3506 if (V.getKind() == RefVal::ReturnedOwned)
3507 ++Cnt;
3508
Ted Kremenek369de562009-05-09 00:10:05 +00003509 if (ACnt <= Cnt) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003510 if (ACnt == Cnt) {
3511 V.clearCounts();
Ted Kremenek95d3b902009-05-11 15:26:06 +00003512 if (V.getKind() == RefVal::ReturnedOwned)
3513 V = V ^ RefVal::ReturnedNotOwned;
3514 else
3515 V = V ^ RefVal::NotOwned;
Ted Kremenek80c24182009-05-09 00:44:07 +00003516 }
Ted Kremenek95d3b902009-05-11 15:26:06 +00003517 else {
Ted Kremenek80c24182009-05-09 00:44:07 +00003518 V.setCount(Cnt - ACnt);
3519 V.setAutoreleaseCount(0);
3520 }
Ted Kremenekb65be702009-06-18 01:23:53 +00003521 state = state->set<RefBindings>(Sym, V);
Ted Kremenek369de562009-05-09 00:10:05 +00003522 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3523 stop = (N == 0);
3524 return std::make_pair(N, state);
3525 }
3526
3527 // Woah! More autorelease counts then retain counts left.
3528 // Emit hard error.
3529 stop = true;
3530 V = V ^ RefVal::ErrorOverAutorelease;
Ted Kremenekb65be702009-06-18 01:23:53 +00003531 state = state->set<RefBindings>(Sym, V);
Ted Kremenek369de562009-05-09 00:10:05 +00003532
3533 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003534 N->markAsSink();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003535
3536 std::string sbuf;
3537 llvm::raw_string_ostream os(sbuf);
Ted Kremenekdaec1452009-05-15 06:02:08 +00003538 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003539 if (V.getAutoreleaseCount() > 1)
3540 os << V.getAutoreleaseCount() << " times";
3541 os << " but the object has ";
3542 if (V.getCount() == 0)
3543 os << "zero (locally visible)";
3544 else
3545 os << "+" << V.getCount();
3546 os << " retain counts";
3547
Ted Kremenek369de562009-05-09 00:10:05 +00003548 CFRefReport *report =
3549 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003550 *this, N, Sym, os.str().c_str());
Ted Kremenek369de562009-05-09 00:10:05 +00003551 BR->EmitReport(report);
3552 }
3553
3554 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekf04dced2009-05-08 23:32:51 +00003555}
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003556
Ted Kremenekb65be702009-06-18 01:23:53 +00003557const GRState *
3558CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003559 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3560
3561 bool hasLeak = V.isOwned() ||
3562 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3563
3564 if (!hasLeak)
Ted Kremenekb65be702009-06-18 01:23:53 +00003565 return state->remove<RefBindings>(sid);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003566
3567 Leaked.push_back(sid);
Ted Kremenekb65be702009-06-18 01:23:53 +00003568 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003569}
3570
3571ExplodedNode<GRState>*
Ted Kremenekb65be702009-06-18 01:23:53 +00003572CFRefCount::ProcessLeaks(const GRState * state,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003573 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3574 GenericNodeBuilder &Builder,
3575 GRExprEngine& Eng,
3576 ExplodedNode<GRState> *Pred) {
3577
3578 if (Leaked.empty())
3579 return Pred;
3580
Ted Kremenekf04dced2009-05-08 23:32:51 +00003581 // Generate an intermediate node representing the leak point.
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003582 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003583
3584 if (N) {
3585 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3586 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3587
3588 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3589 : leakAtReturn);
3590 assert(BT && "BugType not initialized.");
3591 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3592 BR->EmitReport(report);
3593 }
3594 }
3595
3596 return N;
3597}
3598
Ted Kremenekcf701772009-02-05 06:50:21 +00003599void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3600 GREndPathNodeBuilder<GRState>& Builder) {
3601
Ted Kremenekb65be702009-06-18 01:23:53 +00003602 const GRState *state = Builder.getState();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003603 GenericNodeBuilder Bd(Builder);
Ted Kremenekb65be702009-06-18 01:23:53 +00003604 RefBindings B = state->get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003605 ExplodedNode<GRState> *Pred = 0;
3606
3607 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek369de562009-05-09 00:10:05 +00003608 bool stop = false;
3609 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3610 (*I).first,
3611 (*I).second, stop);
3612
3613 if (stop)
3614 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003615 }
3616
Ted Kremenekb65be702009-06-18 01:23:53 +00003617 B = state->get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003618 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003619
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003620 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3621 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3622
Ted Kremenekf04dced2009-05-08 23:32:51 +00003623 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003624}
3625
3626void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3627 GRExprEngine& Eng,
3628 GRStmtNodeBuilder<GRState>& Builder,
3629 ExplodedNode<GRState>* Pred,
3630 Stmt* S,
Ted Kremenekb65be702009-06-18 01:23:53 +00003631 const GRState* state,
Ted Kremenekcf701772009-02-05 06:50:21 +00003632 SymbolReaper& SymReaper) {
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003633
Ted Kremenekb65be702009-06-18 01:23:53 +00003634 RefBindings B = state->get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003635
3636 // Update counts from autorelease pools
3637 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3638 E = SymReaper.dead_end(); I != E; ++I) {
3639 SymbolRef Sym = *I;
3640 if (const RefVal* T = B.lookup(Sym)){
3641 // Use the symbol as the tag.
3642 // FIXME: This might not be as unique as we would like.
3643 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek369de562009-05-09 00:10:05 +00003644 bool stop = false;
3645 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3646 Sym, *T, stop);
3647 if (stop)
3648 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003649 }
3650 }
3651
Ted Kremenekb65be702009-06-18 01:23:53 +00003652 B = state->get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003653 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003654
3655 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003656 E = SymReaper.dead_end(); I != E; ++I) {
3657 if (const RefVal* T = B.lookup(*I))
3658 state = HandleSymbolDeath(state, *I, *T, Leaked);
3659 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003660
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003661 static unsigned LeakPPTag = 0;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003662 {
3663 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3664 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3665 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003666
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003667 // Did we cache out?
3668 if (!Pred)
3669 return;
Ted Kremenek33b6f632009-02-19 23:47:02 +00003670
3671 // Now generate a new node that nukes the old bindings.
Ted Kremenekb65be702009-06-18 01:23:53 +00003672 RefBindings::Factory& F = state->get_context<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003673
Ted Kremenek33b6f632009-02-19 23:47:02 +00003674 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003675 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3676
Ted Kremenekb65be702009-06-18 01:23:53 +00003677 state = state->set<RefBindings>(B);
Ted Kremenek33b6f632009-02-19 23:47:02 +00003678 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003679}
3680
3681void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3682 GRStmtNodeBuilder<GRState>& Builder,
3683 Expr* NodeExpr, Expr* ErrorExpr,
3684 ExplodedNode<GRState>* Pred,
3685 const GRState* St,
3686 RefVal::Kind hasErr, SymbolRef Sym) {
3687 Builder.BuildSinks = true;
3688 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3689
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003690 if (!N)
3691 return;
Ted Kremenekcf701772009-02-05 06:50:21 +00003692
3693 CFRefBug *BT = 0;
3694
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003695 switch (hasErr) {
3696 default:
3697 assert(false && "Unhandled error.");
3698 return;
3699 case RefVal::ErrorUseAfterRelease:
3700 BT = static_cast<CFRefBug*>(useAfterRelease);
3701 break;
3702 case RefVal::ErrorReleaseNotOwned:
3703 BT = static_cast<CFRefBug*>(releaseNotOwned);
3704 break;
3705 case RefVal::ErrorDeallocGC:
3706 BT = static_cast<CFRefBug*>(deallocGC);
3707 break;
3708 case RefVal::ErrorDeallocNotOwned:
3709 BT = static_cast<CFRefBug*>(deallocNotOwned);
3710 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003711 }
3712
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003713 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003714 report->addRange(ErrorExpr->getSourceRange());
3715 BR->EmitReport(report);
3716}
3717
3718//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003719// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003720//===----------------------------------------------------------------------===//
3721
Ted Kremenek072192b2008-04-30 23:47:44 +00003722GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3723 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003724 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003725}