blob: 1a89f3d784a5d35345741ce78e995e9f75d10dd7 [file] [log] [blame]
Chris Lattnerbda0b622008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif843e9342008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek2fff37e2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenek072192b2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekc9fa2f72008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek41573eb2009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenekb9d17f92008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenek4dc41cc2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek5216ad72009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenek8966bc12009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek900a2d72008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenekf3948042008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek98530452008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenek5c74d502008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenek5c74d502008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenekb80976c2009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenek39868cd2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenekb80976c2009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
Ted Kremenek7db16042009-05-15 15:49:00 +000079static NamingConvention deriveNamingConvention(Selector S) {
80 IdentifierInfo *II = S.getIdentifierInfoForSlot(0);
81
82 if (!II)
83 return NoConvention;
84
85 const char *s = II->getName();
86
Ted Kremenekb80976c2009-02-21 05:13:43 +000087 // A method/function name may contain a prefix. We don't know it is there,
88 // however, until we encounter the first '_'.
89 bool InPossiblePrefix = true;
90 bool AtBeginning = true;
91 NamingConvention C = NoConvention;
92
93 while (*s != '\0') {
94 // Skip '_'.
95 if (*s == '_') {
96 if (InPossiblePrefix) {
97 InPossiblePrefix = false;
98 AtBeginning = true;
99 // Discard whatever 'convention' we
100 // had already derived since it occurs
101 // in the prefix.
102 C = NoConvention;
103 }
104 ++s;
105 continue;
106 }
107
108 // Skip numbers, ':', etc.
109 if (!isalpha(*s)) {
110 ++s;
111 continue;
112 }
113
114 const char *wordEnd = parseWord(s);
115 assert(wordEnd > s);
116 unsigned len = wordEnd - s;
117
118 switch (len) {
119 default:
120 break;
121 case 3:
122 // Methods starting with 'new' follow the create rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000123 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000124 C = CreateRule;
125 break;
126 case 4:
127 // Methods starting with 'alloc' or contain 'copy' follow the
128 // create rule
Ted Kremenek8be2a672009-03-13 20:27:06 +0000129 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000130 C = CreateRule;
131 else // Methods starting with 'init' follow the init rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000132 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek8be2a672009-03-13 20:27:06 +0000133 C = InitRule;
134 break;
135 case 5:
136 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
137 C = CreateRule;
Ted Kremenekb80976c2009-02-21 05:13:43 +0000138 break;
139 }
140
141 // If we aren't in the prefix and have a derived convention then just
142 // return it now.
143 if (!InPossiblePrefix && C != NoConvention)
144 return C;
145
146 AtBeginning = false;
147 s = wordEnd;
148 }
149
150 // We will get here if there wasn't more than one word
151 // after the prefix.
152 return C;
153}
154
Ted Kremenek7db16042009-05-15 15:49:00 +0000155static bool followsFundamentalRule(Selector S) {
156 return deriveNamingConvention(S) == CreateRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000157}
158
Ted Kremeneka8833552009-04-29 23:03:22 +0000159static const ObjCMethodDecl*
160ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
161 ObjCInterfaceDecl *ID =
162 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
163
164 return MD->isInstanceMethod()
165 ? ID->lookupInstanceMethod(Context, MD->getSelector())
166 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenek4c79e552008-11-05 16:54:44 +0000167}
Ted Kremenek5c74d502008-10-24 21:18:08 +0000168
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000169namespace {
170class VISIBILITY_HIDDEN GenericNodeBuilder {
171 GRStmtNodeBuilder<GRState> *SNB;
172 Stmt *S;
173 const void *tag;
174 GREndPathNodeBuilder<GRState> *ENB;
175public:
176 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
177 const void *t)
178 : SNB(&snb), S(s), tag(t), ENB(0) {}
179 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
180 : SNB(0), S(0), tag(0), ENB(&enb) {}
181
182 ExplodedNode<GRState> *MakeNode(const GRState *state,
183 ExplodedNode<GRState> *Pred) {
184 if (SNB)
Ted Kremenek6b62ec92009-05-09 01:50:57 +0000185 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000186
187 assert(ENB);
Ted Kremenek80c24182009-05-09 00:44:07 +0000188 return ENB->generateNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000189 }
190};
191} // end anonymous namespace
192
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000193//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000194// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000195//===----------------------------------------------------------------------===//
196
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000197static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000198 IdentifierInfo* II = &Ctx.Idents.get(name);
199 return Ctx.Selectors.getSelector(0, &II);
200}
201
Ted Kremenek9c32d082008-05-06 00:30:21 +0000202static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
203 IdentifierInfo* II = &Ctx.Idents.get(name);
204 return Ctx.Selectors.getSelector(1, &II);
205}
206
Ted Kremenek553cf182008-06-25 21:21:56 +0000207//===----------------------------------------------------------------------===//
208// Type querying functions.
209//===----------------------------------------------------------------------===//
210
Ted Kremenek12619382009-01-12 21:45:02 +0000211static bool hasPrefix(const char* s, const char* prefix) {
212 if (!prefix)
213 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000214
Ted Kremenek12619382009-01-12 21:45:02 +0000215 char c = *s;
216 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000217
Ted Kremenek12619382009-01-12 21:45:02 +0000218 while (c != '\0' && cP != '\0') {
219 if (c != cP) break;
220 c = *(++s);
221 cP = *(++prefix);
222 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000223
Ted Kremenek12619382009-01-12 21:45:02 +0000224 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000225}
226
Ted Kremenek12619382009-01-12 21:45:02 +0000227static bool hasSuffix(const char* s, const char* suffix) {
228 const char* loc = strstr(s, suffix);
229 return loc && strcmp(suffix, loc) == 0;
230}
231
232static bool isRefType(QualType RetTy, const char* prefix,
233 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek37d785b2008-07-15 16:50:12 +0000234
Ted Kremenek6738b732009-05-12 04:53:03 +0000235 // Recursively walk the typedef stack, allowing typedefs of reference types.
236 while (1) {
237 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
238 const char* TDName = TD->getDecl()->getIdentifier()->getName();
239 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
240 return true;
241
242 RetTy = TD->getDecl()->getUnderlyingType();
243 continue;
244 }
245 break;
Ted Kremenek12619382009-01-12 21:45:02 +0000246 }
247
248 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000249 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000250
251 // Is the type void*?
252 const PointerType* PT = RetTy->getAsPointerType();
253 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000254 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000255
256 // Does the name start with the prefix?
257 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000258}
259
Ted Kremenek4fd88972008-04-17 18:12:53 +0000260//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000261// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000262//===----------------------------------------------------------------------===//
263
Ted Kremenek553cf182008-06-25 21:21:56 +0000264/// ArgEffect is used to summarize a function/method call's effect on a
265/// particular argument.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +0000266enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
267 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
268 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +0000269
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000270namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000271template <> struct FoldingSetTrait<ArgEffect> {
272static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
273 ID.AddInteger((unsigned) X);
274}
Ted Kremenek553cf182008-06-25 21:21:56 +0000275};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000276} // end llvm namespace
277
Ted Kremenekb77449c2009-05-03 05:20:50 +0000278/// ArgEffects summarizes the effects of a function/method call on all of
279/// its arguments.
280typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
281
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000282namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000283
284/// RetEffect is used to summarize a function/method call's behavior with
285/// respect to its return value.
286class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000287public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000288 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +0000289 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
290 OwnedWhenTrackedReceiver };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000291
292 enum ObjKind { CF, ObjC, AnyObj };
293
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000294private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000295 Kind K;
296 ObjKind O;
297 unsigned index;
298
299 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
300 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000301
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000302public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000303 Kind getKind() const { return K; }
304
305 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000306
307 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000308 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000309 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000310 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000311
Ted Kremeneka8833552009-04-29 23:03:22 +0000312 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000313 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
314 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000315 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +0000316
Ted Kremenek78a35a32009-05-12 20:06:54 +0000317 static RetEffect MakeOwnedWhenTrackedReceiver() {
318 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
319 }
320
Ted Kremenek553cf182008-06-25 21:21:56 +0000321 static RetEffect MakeAlias(unsigned Idx) {
322 return RetEffect(Alias, Idx);
323 }
324 static RetEffect MakeReceiverAlias() {
325 return RetEffect(ReceiverAlias);
326 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000327 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
328 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000329 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000330 static RetEffect MakeNotOwned(ObjKind o) {
331 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000332 }
333 static RetEffect MakeGCNotOwned() {
334 return RetEffect(GCNotOwnedSymbol, ObjC);
335 }
336
Ted Kremenek553cf182008-06-25 21:21:56 +0000337 static RetEffect MakeNoRet() {
338 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000339 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000340
Ted Kremenek553cf182008-06-25 21:21:56 +0000341 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000342 ID.AddInteger((unsigned)K);
343 ID.AddInteger((unsigned)O);
344 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000345 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000346};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000347
Ted Kremenek553cf182008-06-25 21:21:56 +0000348
Ted Kremenek885c27b2009-05-04 05:31:22 +0000349class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000350 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
351 /// specifies the argument (starting from 0). This can be sparsely
352 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000353 ArgEffects Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000354
355 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
356 /// do not have an entry in Args.
357 ArgEffect DefaultArgEffect;
358
Ted Kremenek553cf182008-06-25 21:21:56 +0000359 /// Receiver - If this summary applies to an Objective-C message expression,
360 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000361 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000362
363 /// Ret - The effect on the return value. Used to indicate if the
364 /// function/method call returns a new tracked symbol, returns an
365 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000366 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000367
Ted Kremenek70a733e2008-07-18 17:24:20 +0000368 /// EndPath - Indicates that execution of this method/function should
369 /// terminate the simulation of a path.
370 bool EndPath;
371
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000372public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000373 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000374 ArgEffect ReceiverEff, bool endpath = false)
375 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
376 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000377
Ted Kremenek553cf182008-06-25 21:21:56 +0000378 /// getArg - Return the argument effect on the argument specified by
379 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000380 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000381 if (const ArgEffect *AE = Args.lookup(idx))
382 return *AE;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000383
Ted Kremenek1bffd742008-05-06 15:44:25 +0000384 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000385 }
386
Ted Kremenek885c27b2009-05-04 05:31:22 +0000387 /// setDefaultArgEffect - Set the default argument effect.
388 void setDefaultArgEffect(ArgEffect E) {
389 DefaultArgEffect = E;
390 }
391
392 /// setArg - Set the argument effect on the argument specified by idx.
393 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
394 Args = AF.Add(Args, idx, E);
395 }
396
Ted Kremenek553cf182008-06-25 21:21:56 +0000397 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000398 RetEffect getRetEffect() const { return Ret; }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000399
Ted Kremenek885c27b2009-05-04 05:31:22 +0000400 /// setRetEffect - Set the effect of the return value of the call.
401 void setRetEffect(RetEffect E) { Ret = E; }
402
Ted Kremenek70a733e2008-07-18 17:24:20 +0000403 /// isEndPath - Returns true if executing the given method/function should
404 /// terminate the path.
405 bool isEndPath() const { return EndPath; }
406
Ted Kremenek553cf182008-06-25 21:21:56 +0000407 /// getReceiverEffect - Returns the effect on the receiver of the call.
408 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000409 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000410
Ted Kremenek885c27b2009-05-04 05:31:22 +0000411 /// setReceiverEffect - Set the effect on the receiver of the call.
412 void setReceiverEffect(ArgEffect E) { Receiver = E; }
413
Ted Kremenekb77449c2009-05-03 05:20:50 +0000414 typedef ArgEffects::iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000415
Ted Kremenekb77449c2009-05-03 05:20:50 +0000416 ExprIterator begin_args() const { return Args.begin(); }
417 ExprIterator end_args() const { return Args.end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000418
Ted Kremenekb77449c2009-05-03 05:20:50 +0000419 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000420 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000421 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000422 ID.Add(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000423 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000424 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000425 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000426 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000427 }
428
429 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000430 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000431 }
432};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000433} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000434
Ted Kremenek553cf182008-06-25 21:21:56 +0000435//===----------------------------------------------------------------------===//
436// Data structures for constructing summaries.
437//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000438
Ted Kremenek553cf182008-06-25 21:21:56 +0000439namespace {
440class VISIBILITY_HIDDEN ObjCSummaryKey {
441 IdentifierInfo* II;
442 Selector S;
443public:
444 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
445 : II(ii), S(s) {}
446
Ted Kremeneka8833552009-04-29 23:03:22 +0000447 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000448 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000449
450 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
451 : II(d ? d->getIdentifier() : ii), S(s) {}
Ted Kremenek553cf182008-06-25 21:21:56 +0000452
453 ObjCSummaryKey(Selector s)
454 : II(0), S(s) {}
455
456 IdentifierInfo* getIdentifier() const { return II; }
457 Selector getSelector() const { return S; }
458};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000459}
460
461namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000462template <> struct DenseMapInfo<ObjCSummaryKey> {
463 static inline ObjCSummaryKey getEmptyKey() {
464 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
465 DenseMapInfo<Selector>::getEmptyKey());
466 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000467
Ted Kremenek553cf182008-06-25 21:21:56 +0000468 static inline ObjCSummaryKey getTombstoneKey() {
469 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
470 DenseMapInfo<Selector>::getTombstoneKey());
471 }
472
473 static unsigned getHashValue(const ObjCSummaryKey &V) {
474 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
475 & 0x88888888)
476 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
477 & 0x55555555);
478 }
479
480 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
481 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
482 RHS.getIdentifier()) &&
483 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
484 RHS.getSelector());
485 }
486
487 static bool isPod() {
488 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
489 DenseMapInfo<Selector>::isPod();
490 }
491};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000492} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000493
Ted Kremenek4f22a782008-06-23 23:30:29 +0000494namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000495class VISIBILITY_HIDDEN ObjCSummaryCache {
496 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
497 MapTy M;
498public:
499 ObjCSummaryCache() {}
500
501 typedef MapTy::iterator iterator;
502
Ted Kremeneka8833552009-04-29 23:03:22 +0000503 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
504 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000505 // Lookup the method using the decl for the class @interface. If we
506 // have no decl, lookup using the class name.
507 return D ? find(D, S) : find(ClsName, S);
508 }
509
Ted Kremeneka8833552009-04-29 23:03:22 +0000510 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000511 // Do a lookup with the (D,S) pair. If we find a match return
512 // the iterator.
513 ObjCSummaryKey K(D, S);
514 MapTy::iterator I = M.find(K);
515
516 if (I != M.end() || !D)
517 return I;
518
519 // Walk the super chain. If we find a hit with a parent, we'll end
520 // up returning that summary. We actually allow that key (null,S), as
521 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
522 // generate initial summaries without having to worry about NSObject
523 // being declared.
524 // FIXME: We may change this at some point.
525 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
526 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
527 break;
528
529 if (!C)
530 return I;
531 }
532
533 // Cache the summary with original key to make the next lookup faster
534 // and return the iterator.
535 M[K] = I->second;
536 return I;
537 }
538
Ted Kremenek98530452008-08-12 20:41:56 +0000539
Ted Kremenek553cf182008-06-25 21:21:56 +0000540 iterator find(Expr* Receiver, Selector S) {
541 return find(getReceiverDecl(Receiver), S);
542 }
543
544 iterator find(IdentifierInfo* II, Selector S) {
545 // FIXME: Class method lookup. Right now we dont' have a good way
546 // of going between IdentifierInfo* and the class hierarchy.
547 iterator I = M.find(ObjCSummaryKey(II, S));
548 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
549 }
550
551 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
552
553 const PointerType* PT = E->getType()->getAsPointerType();
554 if (!PT) return 0;
555
556 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
557 if (!OI) return 0;
558
559 return OI ? OI->getDecl() : 0;
560 }
561
562 iterator end() { return M.end(); }
563
564 RetainSummary*& operator[](ObjCMessageExpr* ME) {
565
566 Selector S = ME->getSelector();
567
568 if (Expr* Receiver = ME->getReceiver()) {
569 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
570 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
571 }
572
573 return M[ObjCSummaryKey(ME->getClassName(), S)];
574 }
575
576 RetainSummary*& operator[](ObjCSummaryKey K) {
577 return M[K];
578 }
579
580 RetainSummary*& operator[](Selector S) {
581 return M[ ObjCSummaryKey(S) ];
582 }
583};
584} // end anonymous namespace
585
586//===----------------------------------------------------------------------===//
587// Data structures for managing collections of summaries.
588//===----------------------------------------------------------------------===//
589
590namespace {
591class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000592
593 //==-----------------------------------------------------------------==//
594 // Typedefs.
595 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000596
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000597 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
598 FuncSummariesTy;
599
Ted Kremenek4f22a782008-06-23 23:30:29 +0000600 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000601
602 //==-----------------------------------------------------------------==//
603 // Data.
604 //==-----------------------------------------------------------------==//
605
Ted Kremenek553cf182008-06-25 21:21:56 +0000606 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000607 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000608
Ted Kremenek070a8252008-07-09 18:11:16 +0000609 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
610 /// "CFDictionaryCreate".
611 IdentifierInfo* CFDictionaryCreateII;
612
Ted Kremenek553cf182008-06-25 21:21:56 +0000613 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000614 const bool GCEnabled;
Ted Kremenek22fe2482009-05-04 04:30:18 +0000615
Ted Kremenek553cf182008-06-25 21:21:56 +0000616 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000617 FuncSummariesTy FuncSummaries;
618
Ted Kremenek553cf182008-06-25 21:21:56 +0000619 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
620 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000621 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000622
Ted Kremenek553cf182008-06-25 21:21:56 +0000623 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000624 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000625
Ted Kremenek553cf182008-06-25 21:21:56 +0000626 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
627 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000628 llvm::BumpPtrAllocator BPAlloc;
629
Ted Kremenekb77449c2009-05-03 05:20:50 +0000630 /// AF - A factory for ArgEffects objects.
631 ArgEffects::Factory AF;
632
Ted Kremenek553cf182008-06-25 21:21:56 +0000633 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000634 ArgEffects ScratchArgs;
635
Ted Kremenekec315332009-05-07 23:40:42 +0000636 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
637 /// objects.
638 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000639
Ted Kremenekb04cb592009-06-11 18:17:24 +0000640 /// ObjCInitRetE - Default return effect for init methods returning Objective-C
Ted Kremenek547d4952009-06-05 23:18:01 +0000641 /// objects.
642 RetEffect ObjCInitRetE;
Ted Kremenekb04cb592009-06-11 18:17:24 +0000643
Ted Kremenek7faca822009-05-04 04:57:00 +0000644 RetainSummary DefaultSummary;
Ted Kremenek432af592008-05-06 18:11:36 +0000645 RetainSummary* StopSummary;
646
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000647 //==-----------------------------------------------------------------==//
648 // Methods.
649 //==-----------------------------------------------------------------==//
650
Ted Kremenek553cf182008-06-25 21:21:56 +0000651 /// getArgEffects - Returns a persistent ArgEffects object based on the
652 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000653 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000654
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000655 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000656
657public:
Ted Kremenek78a35a32009-05-12 20:06:54 +0000658 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
659
Ted Kremenek885c27b2009-05-04 05:31:22 +0000660 RetainSummary *getDefaultSummary() {
661 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
662 return new (Summ) RetainSummary(DefaultSummary);
663 }
Ted Kremenek7faca822009-05-04 04:57:00 +0000664
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000665 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000666
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000667 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
668 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000669 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000670
Ted Kremenekb77449c2009-05-03 05:20:50 +0000671 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000672 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000673 ArgEffect DefaultEff = MayEscape,
674 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000675
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000676 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000677 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000678 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000679 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000680 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000681
Ted Kremenek8711c032009-04-29 05:04:30 +0000682 RetainSummary *getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000683 if (StopSummary)
684 return StopSummary;
685
686 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
687 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000688
Ted Kremenek432af592008-05-06 18:11:36 +0000689 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000690 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000691
Ted Kremenek8711c032009-04-29 05:04:30 +0000692 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000693
Ted Kremenek1f180c32008-06-23 22:21:20 +0000694 void InitializeClassMethodSummaries();
695 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000696
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000697 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek92511432009-05-03 06:08:32 +0000698 bool isTrackedCFObjectType(QualType T);
Ted Kremenek234a4c22009-01-07 00:39:56 +0000699
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000700private:
701
Ted Kremenek70a733e2008-07-18 17:24:20 +0000702 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
703 RetainSummary* Summ) {
704 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
705 }
706
Ted Kremenek553cf182008-06-25 21:21:56 +0000707 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
708 ObjCClassMethodSummaries[S] = Summ;
709 }
710
711 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
712 ObjCMethodSummaries[S] = Summ;
713 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000714
715 void addClassMethSummary(const char* Cls, const char* nullaryName,
716 RetainSummary *Summ) {
717 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
718 Selector S = GetNullarySelector(nullaryName, Ctx);
719 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
720 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000721
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000722 void addInstMethSummary(const char* Cls, const char* nullaryName,
723 RetainSummary *Summ) {
724 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
725 Selector S = GetNullarySelector(nullaryName, Ctx);
726 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
727 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000728
729 Selector generateSelector(va_list argp) {
Ted Kremenek9e476de2008-08-12 18:30:56 +0000730 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000731
Ted Kremenek9e476de2008-08-12 18:30:56 +0000732 while (const char* s = va_arg(argp, const char*))
733 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000734
735 return Ctx.Selectors.getSelector(II.size(), &II[0]);
736 }
737
738 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
739 RetainSummary* Summ, va_list argp) {
740 Selector S = generateSelector(argp);
741 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000742 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000743
744 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
745 va_list argp;
746 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000747 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000748 va_end(argp);
749 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000750
751 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
752 va_list argp;
753 va_start(argp, Summ);
754 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
755 va_end(argp);
756 }
757
758 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
759 va_list argp;
760 va_start(argp, Summ);
761 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
762 va_end(argp);
763 }
764
Ted Kremenek9e476de2008-08-12 18:30:56 +0000765 void addPanicSummary(const char* Cls, ...) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000766 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
767 RetEffect::MakeNoRet(),
Ted Kremenek9e476de2008-08-12 18:30:56 +0000768 DoNothing, DoNothing, true);
769 va_list argp;
770 va_start (argp, Cls);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000771 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000772 va_end(argp);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000773 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000774
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000775public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000776
777 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000778 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000779 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000780 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenekec315332009-05-07 23:40:42 +0000781 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
782 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenekb04cb592009-06-11 18:17:24 +0000783 ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned()
784 : RetEffect::MakeOwnedWhenTrackedReceiver()),
Ted Kremenek7faca822009-05-04 04:57:00 +0000785 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
786 RetEffect::MakeNoRet() /* return effect */,
Ted Kremenekebd5a2d2009-05-11 18:30:24 +0000787 MayEscape, /* default argument effect */
788 DoNothing /* receiver effect */),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000789 StopSummary(0) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000790
791 InitializeClassMethodSummaries();
792 InitializeMethodSummaries();
793 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000794
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000795 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000796
Ted Kremenekab592272008-06-24 03:56:45 +0000797 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek8711c032009-04-29 05:04:30 +0000798
Ted Kremeneka8833552009-04-29 23:03:22 +0000799 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
800 const ObjCInterfaceDecl* ID) {
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000801 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremenek8711c032009-04-29 05:04:30 +0000802 ID, ME->getMethodDecl(), ME->getType());
803 }
804
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000805 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000806 const ObjCInterfaceDecl* ID,
807 const ObjCMethodDecl *MD,
808 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000809
810 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000811 const ObjCInterfaceDecl *ID,
812 const ObjCMethodDecl *MD,
813 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000814
815 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
816 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
817 ME->getClassInfo().first,
818 ME->getMethodDecl(), ME->getType());
819 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000820
821 /// getMethodSummary - This version of getMethodSummary is used to query
822 /// the summary for the current method being analyzed.
Ted Kremeneka8833552009-04-29 23:03:22 +0000823 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
824 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000825 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000826 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000827 IdentifierInfo *ClsName = ID->getIdentifier();
828 QualType ResultTy = MD->getResultType();
829
Ted Kremenek76a50e32009-04-30 05:47:23 +0000830 // Resolve the method decl last.
831 if (const ObjCMethodDecl *InterfaceMD =
832 ResolveToInterfaceMethodDecl(MD, Ctx))
833 MD = InterfaceMD;
Ted Kremenek70a65762009-04-30 05:41:14 +0000834
Ted Kremenek552333c2009-04-29 17:17:48 +0000835 if (MD->isInstanceMethod())
836 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
837 else
838 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
839 }
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000840
Ted Kremeneka8833552009-04-29 23:03:22 +0000841 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
842 Selector S, QualType RetTy);
843
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000844 void updateSummaryFromAnnotations(RetainSummary &Summ,
845 const ObjCMethodDecl *MD);
846
847 void updateSummaryFromAnnotations(RetainSummary &Summ,
848 const FunctionDecl *FD);
849
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000850 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek885c27b2009-05-04 05:31:22 +0000851
852 RetainSummary *copySummary(RetainSummary *OldSumm) {
853 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
854 new (Summ) RetainSummary(*OldSumm);
855 return Summ;
856 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000857};
858
859} // end anonymous namespace
860
861//===----------------------------------------------------------------------===//
862// Implementation of checker data structures.
863//===----------------------------------------------------------------------===//
864
Ted Kremenekb77449c2009-05-03 05:20:50 +0000865RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000866
Ted Kremenekb77449c2009-05-03 05:20:50 +0000867ArgEffects RetainSummaryManager::getArgEffects() {
868 ArgEffects AE = ScratchArgs;
869 ScratchArgs = AF.GetEmptyMap();
870 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000871}
872
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000873RetainSummary*
Ted Kremenekb77449c2009-05-03 05:20:50 +0000874RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000875 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000876 ArgEffect DefaultEff,
Ted Kremenek22fe2482009-05-04 04:30:18 +0000877 bool isEndPath) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000878 // Create the summary and return it.
Ted Kremenek22fe2482009-05-04 04:30:18 +0000879 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000880 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000881 return Summ;
882}
883
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000884//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000885// Predicates.
886//===----------------------------------------------------------------------===//
887
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000888bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek97d095f2009-04-23 22:11:07 +0000889 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek234a4c22009-01-07 00:39:56 +0000890 return false;
891
Ted Kremenek97d095f2009-04-23 22:11:07 +0000892 // We assume that id<..>, id, and "Class" all represent tracked objects.
893 const PointerType *PT = Ty->getAsPointerType();
894 if (PT == 0)
895 return true;
896
897 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek234a4c22009-01-07 00:39:56 +0000898
899 // We assume that id<..>, id, and "Class" all represent tracked objects.
900 if (!OT)
901 return true;
Ted Kremenek97d095f2009-04-23 22:11:07 +0000902
Ted Kremenekfae664a2009-05-16 01:38:01 +0000903 // Does the interface subclass NSObject?
904 // FIXME: We can memoize here if this gets too expensive.
Ted Kremenek234a4c22009-01-07 00:39:56 +0000905 ObjCInterfaceDecl* ID = OT->getDecl();
906
Ted Kremenekfae664a2009-05-16 01:38:01 +0000907 // Assume that anything declared with a forward declaration and no
908 // @interface subclasses NSObject.
909 if (ID->isForwardDecl())
910 return true;
911
912 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
913
914
Ted Kremenek234a4c22009-01-07 00:39:56 +0000915 for ( ; ID ; ID = ID->getSuperClass())
916 if (ID->getIdentifier() == NSObjectII)
917 return true;
918
919 return false;
920}
921
Ted Kremenek92511432009-05-03 06:08:32 +0000922bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
923 return isRefType(T, "CF") || // Core Foundation.
924 isRefType(T, "CG") || // Core Graphics.
925 isRefType(T, "DADisk") || // Disk Arbitration API.
926 isRefType(T, "DADissenter") ||
927 isRefType(T, "DASessionRef");
928}
929
Ted Kremenek234a4c22009-01-07 00:39:56 +0000930//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000931// Summary creation for functions (largely uses of Core Foundation).
932//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000933
Ted Kremenek12619382009-01-12 21:45:02 +0000934static bool isRetain(FunctionDecl* FD, const char* FName) {
935 const char* loc = strstr(FName, "Retain");
936 return loc && loc[sizeof("Retain")-1] == '\0';
937}
938
939static bool isRelease(FunctionDecl* FD, const char* FName) {
940 const char* loc = strstr(FName, "Release");
941 return loc && loc[sizeof("Release")-1] == '\0';
942}
943
Ted Kremenekab592272008-06-24 03:56:45 +0000944RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000945 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000946 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000947 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000948 return I->second;
949
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000950 // No summary? Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000951 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000952
Ted Kremenek37d785b2008-07-15 16:50:12 +0000953 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000954 // We generate "stop" summaries for implicitly defined functions.
955 if (FD->isImplicit()) {
956 S = getPersistentStopSummary();
957 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000958 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000959
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000960 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000961 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000962 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000963 const char* FName = FD->getIdentifier()->getName();
964
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000965 // Strip away preceding '_'. Doing this here will effect all the checks
966 // down below.
967 while (*FName == '_') ++FName;
968
Ted Kremenek12619382009-01-12 21:45:02 +0000969 // Inspect the result type.
970 QualType RetTy = FT->getResultType();
971
972 // FIXME: This should all be refactored into a chain of "summary lookup"
973 // filters.
Ted Kremenek39d88b02009-06-15 20:36:07 +0000974 assert (ScratchArgs.isEmpty());
975
Ted Kremenekb04cb592009-06-11 18:17:24 +0000976 switch (strlen(FName)) {
977 default: break;
Ted Kremenek39d88b02009-06-15 20:36:07 +0000978
979
Ted Kremenekb04cb592009-06-11 18:17:24 +0000980 case 17:
981 // Handle: id NSMakeCollectable(CFTypeRef)
982 if (!memcmp(FName, "NSMakeCollectable", 17)) {
983 S = (RetTy == Ctx.getObjCIdType())
984 ? getUnarySummary(FT, cfmakecollectable)
985 : getPersistentStopSummary();
986 }
Ted Kremenek39d88b02009-06-15 20:36:07 +0000987 else if (!memcmp(FName, "IOBSDNameMatching", 17) ||
988 !memcmp(FName, "IOServiceMatching", 17)) {
989 // Part of <rdar://problem/6961230>. (IOKit)
990 // This should be addressed using a API table.
991 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
992 DoNothing, DoNothing);
993 }
Ted Kremenekb04cb592009-06-11 18:17:24 +0000994 break;
Ted Kremenek39d88b02009-06-15 20:36:07 +0000995
996 case 21:
997 if (!memcmp(FName, "IOServiceNameMatching", 21)) {
998 // Part of <rdar://problem/6961230>. (IOKit)
999 // This should be addressed using a API table.
1000 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1001 DoNothing, DoNothing);
1002 }
1003 break;
1004
1005 case 24:
1006 if (!memcmp(FName, "IOServiceAddNotification", 24)) {
1007 // Part of <rdar://problem/6961230>. (IOKit)
1008 // This should be addressed using a API table.
1009 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1010 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1011 }
1012 break;
1013
1014 case 25:
1015 if (!memcmp(FName, "IORegistryEntryIDMatching", 25)) {
1016 // Part of <rdar://problem/6961230>. (IOKit)
1017 // This should be addressed using a API table.
1018 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1019 DoNothing, DoNothing);
1020 }
1021 break;
1022
1023 case 26:
1024 if (!memcmp(FName, "IOOpenFirmwarePathMatching", 26)) {
1025 // Part of <rdar://problem/6961230>. (IOKit)
1026 // This should be addressed using a API table.
1027 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1028 DoNothing, DoNothing);
1029 }
1030 break;
1031
Ted Kremenekb04cb592009-06-11 18:17:24 +00001032 case 27:
1033 if (!memcmp(FName, "IOServiceGetMatchingService", 27)) {
1034 // Part of <rdar://problem/6961230>.
1035 // This should be addressed using a API table.
Ted Kremenekb04cb592009-06-11 18:17:24 +00001036 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1037 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1038 }
1039 break;
1040
1041 case 28:
1042 if (!memcmp(FName, "IOServiceGetMatchingServices", 28)) {
1043 // FIXES: <rdar://problem/6326900>
1044 // This should be addressed using a API table. This strcmp is also
1045 // a little gross, but there is no need to super optimize here.
Ted Kremenekb04cb592009-06-11 18:17:24 +00001046 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1047 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1048 }
1049 break;
Ted Kremenek39d88b02009-06-15 20:36:07 +00001050
1051 case 32:
1052 if (!memcmp(FName, "IOServiceAddMatchingNotification", 32)) {
1053 // Part of <rdar://problem/6961230>.
1054 // This should be addressed using a API table.
1055 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1056 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1057 }
1058 break;
Ted Kremenekb04cb592009-06-11 18:17:24 +00001059 }
1060
1061 // Did we get a summary?
1062 if (S)
1063 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001064
1065 // Enable this code once the semantics of NSDeallocateObject are resolved
1066 // for GC. <rdar://problem/6619988>
1067#if 0
1068 // Handle: NSDeallocateObject(id anObject);
1069 // This method does allow 'nil' (although we don't check it now).
1070 if (strcmp(FName, "NSDeallocateObject") == 0) {
1071 return RetTy == Ctx.VoidTy
1072 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1073 : getPersistentStopSummary();
1074 }
1075#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001076
1077 if (RetTy->isPointerType()) {
1078 // For CoreFoundation ('CF') types.
1079 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1080 if (isRetain(FD, FName))
1081 S = getUnarySummary(FT, cfretain);
1082 else if (strstr(FName, "MakeCollectable"))
1083 S = getUnarySummary(FT, cfmakecollectable);
1084 else
1085 S = getCFCreateGetRuleSummary(FD, FName);
1086
1087 break;
1088 }
1089
1090 // For CoreGraphics ('CG') types.
1091 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1092 if (isRetain(FD, FName))
1093 S = getUnarySummary(FT, cfretain);
1094 else
1095 S = getCFCreateGetRuleSummary(FD, FName);
1096
1097 break;
1098 }
1099
1100 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1101 if (isRefType(RetTy, "DADisk") ||
1102 isRefType(RetTy, "DADissenter") ||
1103 isRefType(RetTy, "DASessionRef")) {
1104 S = getCFCreateGetRuleSummary(FD, FName);
1105 break;
1106 }
1107
1108 break;
1109 }
1110
1111 // Check for release functions, the only kind of functions that we care
1112 // about that don't return a pointer type.
1113 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001114 // Test for 'CGCF'.
1115 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1116 FName += 4;
1117 else
1118 FName += 2;
1119
1120 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001121 S = getUnarySummary(FT, cfrelease);
1122 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001123 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001124 // Remaining CoreFoundation and CoreGraphics functions.
1125 // We use to assume that they all strictly followed the ownership idiom
1126 // and that ownership cannot be transferred. While this is technically
1127 // correct, many methods allow a tracked object to escape. For example:
1128 //
1129 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1130 // CFDictionaryAddValue(y, key, x);
1131 // CFRelease(x);
1132 // ... it is okay to use 'x' since 'y' has a reference to it
1133 //
1134 // We handle this and similar cases with the follow heuristic. If the
1135 // function name contains "InsertValue", "SetValue" or "AddValue" then
1136 // we assume that arguments may "escape."
1137 //
1138 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1139 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +00001140 CStrInCStrNoCase(FName, "SetValue") ||
1141 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +00001142 ? MayEscape : DoNothing;
1143
1144 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001145 }
1146 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001147 }
1148 while (0);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001149
1150 if (!S)
1151 S = getDefaultSummary();
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001152
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001153 // Annotations override defaults.
1154 assert(S);
1155 updateSummaryFromAnnotations(*S, FD);
1156
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001157 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001158 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001159}
1160
Ted Kremenek37d785b2008-07-15 16:50:12 +00001161RetainSummary*
1162RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1163 const char* FName) {
1164
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001165 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1166 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +00001167
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001168 if (strstr(FName, "Get"))
1169 return getCFSummaryGetRule(FD);
1170
Ted Kremenek7faca822009-05-04 04:57:00 +00001171 return getDefaultSummary();
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001172}
1173
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001174RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001175RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1176 UnaryFuncKind func) {
1177
Ted Kremenek12619382009-01-12 21:45:02 +00001178 // Sanity check that this is *really* a unary function. This can
1179 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001180 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001181 if (!FTP || FTP->getNumArgs() != 1)
1182 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001183
Ted Kremenekb77449c2009-05-03 05:20:50 +00001184 assert (ScratchArgs.isEmpty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001185
Ted Kremenek377e2302008-04-29 05:33:51 +00001186 switch (func) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001187 case cfretain: {
1188 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001189 return getPersistentSummary(RetEffect::MakeAlias(0),
1190 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001191 }
1192
1193 case cfrelease: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001194 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001195 return getPersistentSummary(RetEffect::MakeNoRet(),
1196 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001197 }
1198
1199 case cfmakecollectable: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001200 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek27019002009-02-18 21:57:45 +00001201 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001202 }
1203
1204 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001205 assert (false && "Not a supported unary function.");
Ted Kremenek7faca822009-05-04 04:57:00 +00001206 return getDefaultSummary();
Ted Kremenek940b1d82008-04-10 23:44:06 +00001207 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001208}
1209
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001210RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001211 assert (ScratchArgs.isEmpty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001212
1213 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001214 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1215 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenek070a8252008-07-09 18:11:16 +00001216 }
1217
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001218 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001219}
1220
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001221RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001222 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001223 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1224 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001225}
1226
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001227//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001228// Summary creation for Selectors.
1229//===----------------------------------------------------------------------===//
1230
Ted Kremenek1bffd742008-05-06 15:44:25 +00001231RetainSummary*
Ted Kremenek8711c032009-04-29 05:04:30 +00001232RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek78a35a32009-05-12 20:06:54 +00001233 assert(ScratchArgs.isEmpty());
1234 // 'init' methods conceptually return a newly allocated object and claim
1235 // the receiver.
1236 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
Ted Kremenek547d4952009-06-05 23:18:01 +00001237 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001238
1239 return getDefaultSummary();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001240}
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001241
1242void
1243RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1244 const FunctionDecl *FD) {
1245 if (!FD)
1246 return;
1247
Ted Kremenekb04cb592009-06-11 18:17:24 +00001248 QualType RetTy = FD->getResultType();
1249
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001250 // Determine if there is a special return effect for this method.
Ted Kremenekb9d8db82009-06-05 23:00:33 +00001251 if (isTrackedObjCObjectType(RetTy)) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001252 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1253 Summ.setRetEffect(ObjCAllocRetE);
1254 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001255 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenekb9d8db82009-06-05 23:00:33 +00001256 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001257 }
1258 }
1259 else if (RetTy->getAsPointerType()) {
1260 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001261 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1262 }
1263 }
1264}
1265
1266void
1267RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1268 const ObjCMethodDecl *MD) {
1269 if (!MD)
1270 return;
1271
1272 // Determine if there is a special return effect for this method.
1273 if (isTrackedObjCObjectType(MD->getResultType())) {
1274 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1275 Summ.setRetEffect(ObjCAllocRetE);
1276 }
1277 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1278 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1279 }
1280 }
1281}
1282
Ted Kremenek1bffd742008-05-06 15:44:25 +00001283RetainSummary*
Ted Kremeneka8833552009-04-29 23:03:22 +00001284RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1285 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001286
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001287 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001288 // Scan the method decl for 'void*' arguments. These should be treated
1289 // as 'StopTracking' because they are often used with delegates.
1290 // Delegates are a frequent form of false positives with the retain
1291 // count checker.
1292 unsigned i = 0;
1293 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1294 E = MD->param_end(); I != E; ++I, ++i)
1295 if (ParmVarDecl *PD = *I) {
1296 QualType Ty = Ctx.getCanonicalType(PD->getType());
1297 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenekb77449c2009-05-03 05:20:50 +00001298 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001299 }
1300 }
1301
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001302 // Any special effect for the receiver?
1303 ArgEffect ReceiverEff = DoNothing;
1304
1305 // If one of the arguments in the selector has the keyword 'delegate' we
1306 // should stop tracking the reference count for the receiver. This is
1307 // because the reference count is quite possibly handled by a delegate
1308 // method.
1309 if (S.isKeywordSelector()) {
1310 const std::string &str = S.getAsString();
1311 assert(!str.empty());
1312 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1313 }
1314
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001315 // Look for methods that return an owned object.
Ted Kremenek92511432009-05-03 06:08:32 +00001316 if (isTrackedObjCObjectType(RetTy)) {
1317 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1318 // by instance methods.
Ted Kremenek7db16042009-05-15 15:49:00 +00001319 RetEffect E = followsFundamentalRule(S)
1320 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek92511432009-05-03 06:08:32 +00001321
1322 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001323 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001324
Ted Kremenek92511432009-05-03 06:08:32 +00001325 // Look for methods that return an owned core foundation object.
1326 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek7db16042009-05-15 15:49:00 +00001327 RetEffect E = followsFundamentalRule(S)
1328 ? RetEffect::MakeOwned(RetEffect::CF, true)
1329 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremenek92511432009-05-03 06:08:32 +00001330
1331 return getPersistentSummary(E, ReceiverEff, MayEscape);
1332 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001333
Ted Kremenek92511432009-05-03 06:08:32 +00001334 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek7faca822009-05-04 04:57:00 +00001335 return getDefaultSummary();
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001336
Ted Kremenek885c27b2009-05-04 05:31:22 +00001337 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001338}
1339
1340RetainSummary*
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001341RetainSummaryManager::getInstanceMethodSummary(Selector S,
1342 IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001343 const ObjCInterfaceDecl* ID,
1344 const ObjCMethodDecl *MD,
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001345 QualType RetTy) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001346
Ted Kremenek8711c032009-04-29 05:04:30 +00001347 // Look up a summary in our summary cache.
1348 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001349
Ted Kremenek1f180c32008-06-23 22:21:20 +00001350 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001351 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001352
Ted Kremenekb77449c2009-05-03 05:20:50 +00001353 assert(ScratchArgs.isEmpty());
Ted Kremenek885c27b2009-05-04 05:31:22 +00001354 RetainSummary *Summ = 0;
Ted Kremenekaee9e572008-05-06 06:09:09 +00001355
Ted Kremenek885c27b2009-05-04 05:31:22 +00001356 // "initXXX": pass-through for receiver.
Ted Kremenek7db16042009-05-15 15:49:00 +00001357 if (deriveNamingConvention(S) == InitRule)
Ted Kremenek885c27b2009-05-04 05:31:22 +00001358 Summ = getInitMethodSummary(RetTy);
1359 else
1360 Summ = getCommonMethodSummary(MD, S, RetTy);
1361
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001362 // Annotations override defaults.
1363 updateSummaryFromAnnotations(*Summ, MD);
1364
Ted Kremenek885c27b2009-05-04 05:31:22 +00001365 // Memoize the summary.
Ted Kremenek70b6a832009-05-13 18:16:01 +00001366 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001367 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001368}
1369
Ted Kremenekc8395602008-05-06 21:26:51 +00001370RetainSummary*
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001371RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001372 const ObjCInterfaceDecl *ID,
1373 const ObjCMethodDecl *MD,
1374 QualType RetTy) {
Ted Kremenekde4d5332009-04-24 17:50:11 +00001375
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001376 assert(ClsName && "Class name must be specified.");
Ted Kremenek8711c032009-04-29 05:04:30 +00001377 ObjCMethodSummariesTy::iterator I =
1378 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001379
Ted Kremenek1f180c32008-06-23 22:21:20 +00001380 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001381 return I->second;
Ted Kremenek885c27b2009-05-04 05:31:22 +00001382
1383 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001384
1385 // Annotations override defaults.
1386 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001387
Ted Kremenek885c27b2009-05-04 05:31:22 +00001388 // Memoize the summary.
Ted Kremenek70b6a832009-05-13 18:16:01 +00001389 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001390 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001391}
1392
Ted Kremenekec315332009-05-07 23:40:42 +00001393void RetainSummaryManager::InitializeClassMethodSummaries() {
1394 assert(ScratchArgs.isEmpty());
1395 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001396
Ted Kremenek553cf182008-06-25 21:21:56 +00001397 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1398 // NSObject and its derivatives.
1399 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1400 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1401 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001402
1403 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001404 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001405 GetNullarySelector("currentHandler", Ctx),
1406 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001407
1408 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb77449c2009-05-03 05:20:50 +00001409 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenekabf43972009-01-28 21:44:40 +00001410 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1411 GetUnarySelector("addObject", Ctx),
1412 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001413 DoNothing, Autorelease));
Ted Kremenekde4d5332009-04-24 17:50:11 +00001414
1415 // Create the summaries for [NSObject performSelector...]. We treat
1416 // these as 'stop tracking' for the arguments because they are often
1417 // used for delegates that can release the object. When we have better
1418 // inter-procedural analysis we can potentially do something better. This
1419 // workaround is to remove false positives.
1420 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1421 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1422 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1423 "afterDelay", NULL);
1424 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1425 "afterDelay", "inModes", NULL);
1426 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1427 "withObject", "waitUntilDone", NULL);
1428 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1429 "withObject", "waitUntilDone", "modes", NULL);
1430 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1431 "withObject", "waitUntilDone", NULL);
1432 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1433 "withObject", "waitUntilDone", "modes", NULL);
1434 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1435 "withObject", NULL);
Ted Kremenek30437662009-05-14 21:29:16 +00001436
1437 // Specially handle NSData.
1438 RetainSummary *dataWithBytesNoCopySumm =
1439 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1440 DoNothing);
1441 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1442 "dataWithBytesNoCopy", "length", NULL);
1443 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1444 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001445}
1446
Ted Kremenek1f180c32008-06-23 22:21:20 +00001447void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001448
Ted Kremenekb77449c2009-05-03 05:20:50 +00001449 assert (ScratchArgs.isEmpty());
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001450
Ted Kremenekc8395602008-05-06 21:26:51 +00001451 // Create the "init" selector. It just acts as a pass-through for the
1452 // receiver.
Ted Kremenek78a35a32009-05-12 20:06:54 +00001453 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
Ted Kremenekb04cb592009-06-11 18:17:24 +00001454 getPersistentSummary(ObjCInitRetE, DecRefMsg));
Ted Kremenekc8395602008-05-06 21:26:51 +00001455
1456 // The next methods are allocators.
Ted Kremenek767d6492009-05-20 22:39:57 +00001457 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Ted Kremenekc8395602008-05-06 21:26:51 +00001458
1459 // Create the "copy" selector.
Ted Kremenek767d6492009-05-20 22:39:57 +00001460 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek98530452008-08-12 20:41:56 +00001461
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001462 // Create the "mutableCopy" selector.
Ted Kremenek767d6492009-05-20 22:39:57 +00001463 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Ted Kremenek98530452008-08-12 20:41:56 +00001464
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001465 // Create the "retain" selector.
Ted Kremenekec315332009-05-07 23:40:42 +00001466 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek767d6492009-05-20 22:39:57 +00001467 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001468 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001469
1470 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001471 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001472 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001473
1474 // Create the "drain" selector.
1475 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001476 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001477
1478 // Create the -dealloc summary.
1479 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1480 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001481
1482 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001483 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001484 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001485
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001486 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001487 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001488 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001489 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001490
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001491 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001492 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1493 // self-own themselves. However, they only do this once they are displayed.
1494 // Thus, we need to track an NSWindow's display status.
1495 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001496 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek78a35a32009-05-12 20:06:54 +00001497 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1498 StopTracking,
1499 StopTracking);
Ted Kremenek99d02692009-04-03 19:02:51 +00001500
1501 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1502
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001503#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001504 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001505 "styleMask", "backing", "defer", NULL);
1506
Ted Kremenek78a35a32009-05-12 20:06:54 +00001507 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001508 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001509#endif
Ted Kremenek78a35a32009-05-12 20:06:54 +00001510
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001511 // For NSPanel (which subclasses NSWindow), allocated objects are not
1512 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001513 // FIXME: For now we don't track NSPanels. object for the same reason
1514 // as for NSWindow objects.
1515 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1516
Ted Kremenek78a35a32009-05-12 20:06:54 +00001517#if 0
1518 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001519 "styleMask", "backing", "defer", NULL);
1520
Ted Kremenek78a35a32009-05-12 20:06:54 +00001521 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001522 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001523#endif
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001524
1525 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1526 // exit a method.
1527 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001528
Ted Kremenek70a733e2008-07-18 17:24:20 +00001529 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001530 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1531 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001532
Ted Kremenek9e476de2008-08-12 18:30:56 +00001533 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1534 "file", "lineNumber", "description", NULL);
Ted Kremenek767d6492009-05-20 22:39:57 +00001535
1536 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1537 addInstMethSummary("QCRenderer", AllocSumm,
1538 "createSnapshotImageOfType", NULL);
1539 addInstMethSummary("QCView", AllocSumm,
1540 "createSnapshotImageOfType", NULL);
1541
Ted Kremenek211a9c62009-06-15 20:58:58 +00001542 // Create summaries for CIContext, 'createCGImage' and
1543 // 'createCGLayerWithSize'.
Ted Kremenek767d6492009-05-20 22:39:57 +00001544 addInstMethSummary("CIContext", AllocSumm,
1545 "createCGImage", "fromRect", NULL);
1546 addInstMethSummary("CIContext", AllocSumm,
Ted Kremenek211a9c62009-06-15 20:58:58 +00001547 "createCGImage", "fromRect", "format", "colorSpace", NULL);
1548 addInstMethSummary("CIContext", AllocSumm, "createCGLayerWithSize",
1549 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001550}
1551
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001552//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001553// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001554//===----------------------------------------------------------------------===//
1555
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001556namespace {
1557
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001558class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001559public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001560 enum Kind {
1561 Owned = 0, // Owning reference.
1562 NotOwned, // Reference is not owned by still valid (not freed).
1563 Released, // Object has been released.
1564 ReturnedOwned, // Returned object passes ownership to caller.
1565 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001566 ERROR_START,
1567 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1568 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001569 ErrorUseAfterRelease, // Object used after released.
1570 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001571 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001572 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek369de562009-05-09 00:10:05 +00001573 ErrorLeakReturned, // A memory leak due to the returning method not having
1574 // the correct naming conventions.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001575 ErrorGCLeakReturned,
1576 ErrorOverAutorelease,
1577 ErrorReturnedNotOwned
Ted Kremenek4fd88972008-04-17 18:12:53 +00001578 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001579
1580private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001581 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001582 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001583 unsigned Cnt;
Ted Kremenekf21332e2009-05-08 20:01:42 +00001584 unsigned ACnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001585 QualType T;
1586
Ted Kremenekf21332e2009-05-08 20:01:42 +00001587 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1588 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001589
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001590 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenekf21332e2009-05-08 20:01:42 +00001591 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001592
1593public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001594 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001595
1596 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001597
Ted Kremenekf21332e2009-05-08 20:01:42 +00001598 unsigned getCount() const { return Cnt; }
1599 unsigned getAutoreleaseCount() const { return ACnt; }
1600 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1601 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek369de562009-05-09 00:10:05 +00001602 void setCount(unsigned i) { Cnt = i; }
1603 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001604
Ted Kremenek553cf182008-06-25 21:21:56 +00001605 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001606
1607 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001608
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001609 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001610
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001611 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001612
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001613 bool isOwned() const {
1614 return getKind() == Owned;
1615 }
1616
Ted Kremenekdb863712008-04-16 22:32:20 +00001617 bool isNotOwned() const {
1618 return getKind() == NotOwned;
1619 }
1620
Ted Kremenek4fd88972008-04-17 18:12:53 +00001621 bool isReturnedOwned() const {
1622 return getKind() == ReturnedOwned;
1623 }
1624
1625 bool isReturnedNotOwned() const {
1626 return getKind() == ReturnedNotOwned;
1627 }
1628
1629 bool isNonLeakError() const {
1630 Kind k = getKind();
1631 return isError(k) && !isLeak(k);
1632 }
1633
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001634 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1635 unsigned Count = 1) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001636 return RefVal(Owned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001637 }
1638
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001639 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1640 unsigned Count = 0) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001641 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001642 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001643
Ted Kremenek4fd88972008-04-17 18:12:53 +00001644 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001645
Ted Kremenek4fd88972008-04-17 18:12:53 +00001646 bool operator==(const RefVal& X) const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001647 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001648 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001649
Ted Kremenek553cf182008-06-25 21:21:56 +00001650 RefVal operator-(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001651 return RefVal(getKind(), getObjKind(), getCount() - i,
1652 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001653 }
1654
1655 RefVal operator+(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001656 return RefVal(getKind(), getObjKind(), getCount() + i,
1657 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001658 }
1659
1660 RefVal operator^(Kind k) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001661 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1662 getType());
1663 }
1664
1665 RefVal autorelease() const {
1666 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1667 getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001668 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001669
Ted Kremenek4fd88972008-04-17 18:12:53 +00001670 void Profile(llvm::FoldingSetNodeID& ID) const {
1671 ID.AddInteger((unsigned) kind);
1672 ID.AddInteger(Cnt);
Ted Kremenekf21332e2009-05-08 20:01:42 +00001673 ID.AddInteger(ACnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001674 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001675 }
1676
Ted Kremenekf3948042008-03-11 19:44:10 +00001677 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001678};
Ted Kremenekf3948042008-03-11 19:44:10 +00001679
1680void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001681 if (!T.isNull())
1682 Out << "Tracked Type:" << T.getAsString() << '\n';
1683
Ted Kremenekf3948042008-03-11 19:44:10 +00001684 switch (getKind()) {
1685 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001686 case Owned: {
1687 Out << "Owned";
1688 unsigned cnt = getCount();
1689 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001690 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001691 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001692
Ted Kremenek61b9f872008-04-10 23:09:18 +00001693 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001694 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001695 unsigned cnt = getCount();
1696 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001697 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001698 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001699
Ted Kremenek4fd88972008-04-17 18:12:53 +00001700 case ReturnedOwned: {
1701 Out << "ReturnedOwned";
1702 unsigned cnt = getCount();
1703 if (cnt) Out << " (+ " << cnt << ")";
1704 break;
1705 }
1706
1707 case ReturnedNotOwned: {
1708 Out << "ReturnedNotOwned";
1709 unsigned cnt = getCount();
1710 if (cnt) Out << " (+ " << cnt << ")";
1711 break;
1712 }
1713
Ted Kremenekf3948042008-03-11 19:44:10 +00001714 case Released:
1715 Out << "Released";
1716 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001717
1718 case ErrorDeallocGC:
1719 Out << "-dealloc (GC)";
1720 break;
1721
1722 case ErrorDeallocNotOwned:
1723 Out << "-dealloc (not-owned)";
1724 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001725
Ted Kremenekdb863712008-04-16 22:32:20 +00001726 case ErrorLeak:
1727 Out << "Leaked";
1728 break;
1729
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001730 case ErrorLeakReturned:
1731 Out << "Leaked (Bad naming)";
1732 break;
1733
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001734 case ErrorGCLeakReturned:
1735 Out << "Leaked (GC-ed at return)";
1736 break;
1737
Ted Kremenekf3948042008-03-11 19:44:10 +00001738 case ErrorUseAfterRelease:
1739 Out << "Use-After-Release [ERROR]";
1740 break;
1741
1742 case ErrorReleaseNotOwned:
1743 Out << "Release of Not-Owned [ERROR]";
1744 break;
Ted Kremenek80c24182009-05-09 00:44:07 +00001745
1746 case RefVal::ErrorOverAutorelease:
1747 Out << "Over autoreleased";
1748 break;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001749
1750 case RefVal::ErrorReturnedNotOwned:
1751 Out << "Non-owned object returned instead of owned";
1752 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001753 }
Ted Kremenekf21332e2009-05-08 20:01:42 +00001754
1755 if (ACnt) {
1756 Out << " [ARC +" << ACnt << ']';
1757 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001758}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001759
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001760} // end anonymous namespace
1761
1762//===----------------------------------------------------------------------===//
1763// RefBindings - State used to track object reference counts.
1764//===----------------------------------------------------------------------===//
1765
Ted Kremenek2dabd432008-12-05 02:27:51 +00001766typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001767static int RefBIndex = 0;
1768
1769namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001770 template<>
1771 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1772 static inline void* GDMIndex() { return &RefBIndex; }
1773 };
1774}
Ted Kremenek6d348932008-10-21 15:53:15 +00001775
1776//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001777// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001778//===----------------------------------------------------------------------===//
1779
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001780typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1781typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1782typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001783
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001784static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001785static int AutoRBIndex = 0;
1786
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001787namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001788namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001789
Ted Kremenek6d348932008-10-21 15:53:15 +00001790namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001791template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001792 : public GRStatePartialTrait<ARStack> {
1793 static inline void* GDMIndex() { return &AutoRBIndex; }
1794};
1795
1796template<> struct GRStateTrait<AutoreleasePoolContents>
1797 : public GRStatePartialTrait<ARPoolContents> {
1798 static inline void* GDMIndex() { return &AutoRCIndex; }
1799};
1800} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001801
Ted Kremenek7037ab82009-03-20 17:34:15 +00001802static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1803 ARStack stack = state->get<AutoreleaseStack>();
1804 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1805}
1806
Ted Kremenekb65be702009-06-18 01:23:53 +00001807static const GRState * SendAutorelease(const GRState *state,
1808 ARCounts::Factory &F, SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001809
1810 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001811 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001812 ARCounts newCnts(0);
1813
1814 if (cnts) {
1815 const unsigned *cnt = (*cnts).lookup(sym);
1816 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1817 }
1818 else
1819 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1820
Ted Kremenekb65be702009-06-18 01:23:53 +00001821 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001822}
1823
Ted Kremenek13922612008-04-16 20:40:59 +00001824//===----------------------------------------------------------------------===//
1825// Transfer functions.
1826//===----------------------------------------------------------------------===//
1827
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001828namespace {
1829
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001830class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001831public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001832 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001833 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001834 virtual void Print(std::ostream& Out, const GRState* state,
1835 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001836 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001837
1838private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001839 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1840 SummaryLogTy;
1841
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001842 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001843 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001844 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001845 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001846
Ted Kremenekcf701772009-02-05 06:50:21 +00001847 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001848 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001849 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek369de562009-05-09 00:10:05 +00001850 BugType *overAutorelease;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001851 BugType *returnNotOwnedForOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001852 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001853
Ted Kremenekb65be702009-06-18 01:23:53 +00001854 const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001855 RefVal::Kind& hasErr);
1856
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001857 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1858 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu264e9372009-05-12 10:10:00 +00001859 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001860 ExplodedNode<GRState>* Pred,
1861 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001862 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001863
Ted Kremenekb65be702009-06-18 01:23:53 +00001864 const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001865 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1866
Ted Kremenekb65be702009-06-18 01:23:53 +00001867 ExplodedNode<GRState>* ProcessLeaks(const GRState * state,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001868 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1869 GenericNodeBuilder &Builder,
1870 GRExprEngine &Eng,
1871 ExplodedNode<GRState> *Pred = 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001872
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001873public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001874 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001875 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001876 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1877 deallocGC(0), deallocNotOwned(0),
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001878 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1879 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001880
Ted Kremenekcf701772009-02-05 06:50:21 +00001881 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001882
Ted Kremenekcf118d42009-02-04 23:49:09 +00001883 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001884
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001885 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1886 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001887 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001888
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001889 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001890 const LangOptions& getLangOptions() const { return LOpts; }
1891
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001892 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1893 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1894 return I == SummaryLog.end() ? 0 : I->second;
1895 }
1896
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001897 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001898
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001899 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001900 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001901 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001902 Expr* Ex,
1903 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00001904 const RetainSummary& Summ,
Zhongxing Xu264e9372009-05-12 10:10:00 +00001905 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001906 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001907
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001908 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001909 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001910 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001911 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001912 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001913
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001914
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001915 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001916 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001917 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001918 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001919 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001920
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001921 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001922 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001923 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001924 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001925 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001926
Ted Kremenek41573eb2009-02-14 01:43:44 +00001927 // Stores.
1928 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1929
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001930 // End-of-path.
1931
1932 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001933 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001934
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001935 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001936 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001937 GRStmtNodeBuilder<GRState>& Builder,
1938 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001939 Stmt* S, const GRState* state,
1940 SymbolReaper& SymReaper);
Ted Kremenekf04dced2009-05-08 23:32:51 +00001941
Ted Kremenekb65be702009-06-18 01:23:53 +00001942 std::pair<ExplodedNode<GRState>*, const GRState *>
1943 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Ted Kremenek369de562009-05-09 00:10:05 +00001944 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1945 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001946 // Return statements.
1947
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001948 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001949 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001950 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001951 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001952 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001953
1954 // Assumptions.
1955
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001956 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001957 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001958 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001959};
1960
1961} // end anonymous namespace
1962
Ted Kremenek7037ab82009-03-20 17:34:15 +00001963static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1964 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001965 if (Sym)
1966 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001967 else
1968 Out << "<pool>";
1969 Out << ":{";
1970
1971 // Get the contents of the pool.
1972 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1973 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1974 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1975
1976 Out << '}';
1977}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001978
Ted Kremenekae6814e2008-08-13 21:24:49 +00001979void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1980 const char* nl, const char* sep) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001981
1982
Ted Kremenekae6814e2008-08-13 21:24:49 +00001983
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001984 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001985
Ted Kremenekae6814e2008-08-13 21:24:49 +00001986 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001987 Out << sep << nl;
1988
1989 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1990 Out << (*I).first << " : ";
1991 (*I).second.print(Out);
1992 Out << nl;
1993 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001994
1995 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001996 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001997 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001998
Ted Kremenek7037ab82009-03-20 17:34:15 +00001999 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
2000 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
2001 PrintPool(Out, *I, state);
2002
2003 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00002004}
2005
Ted Kremenekc887d132009-04-29 18:50:19 +00002006//===----------------------------------------------------------------------===//
2007// Error reporting.
2008//===----------------------------------------------------------------------===//
2009
2010namespace {
2011
2012 //===-------------===//
2013 // Bug Descriptions. //
2014 //===-------------===//
2015
2016 class VISIBILITY_HIDDEN CFRefBug : public BugType {
2017 protected:
2018 CFRefCount& TF;
2019
2020 CFRefBug(CFRefCount* tf, const char* name)
2021 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
2022 public:
2023
2024 CFRefCount& getTF() { return TF; }
2025 const CFRefCount& getTF() const { return TF; }
2026
2027 // FIXME: Eventually remove.
2028 virtual const char* getDescription() const = 0;
2029
2030 virtual bool isLeak() const { return false; }
2031 };
2032
2033 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2034 public:
2035 UseAfterRelease(CFRefCount* tf)
2036 : CFRefBug(tf, "Use-after-release") {}
2037
2038 const char* getDescription() const {
2039 return "Reference-counted object is used after it is released";
2040 }
2041 };
2042
2043 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2044 public:
2045 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
2046
2047 const char* getDescription() const {
2048 return "Incorrect decrement of the reference count of an "
2049 "object is not owned at this point by the caller";
2050 }
2051 };
2052
2053 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2054 public:
Ted Kremenek369de562009-05-09 00:10:05 +00002055 DeallocGC(CFRefCount *tf)
2056 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002057
2058 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00002059 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00002060 }
2061 };
2062
2063 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2064 public:
Ted Kremenek369de562009-05-09 00:10:05 +00002065 DeallocNotOwned(CFRefCount *tf)
2066 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002067
2068 const char *getDescription() const {
2069 return "-dealloc sent to object that may be referenced elsewhere";
2070 }
2071 };
2072
Ted Kremenek369de562009-05-09 00:10:05 +00002073 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
2074 public:
2075 OverAutorelease(CFRefCount *tf) :
2076 CFRefBug(tf, "Object sent -autorelease too many times") {}
2077
2078 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002079 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00002080 }
2081 };
2082
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002083 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
2084 public:
2085 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2086 CFRefBug(tf, "Method should return an owned object") {}
2087
2088 const char *getDescription() const {
2089 return "Object with +0 retain counts returned to caller where a +1 "
2090 "(owning) retain count is expected";
2091 }
2092 };
2093
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2095 const bool isReturn;
2096 protected:
2097 Leak(CFRefCount* tf, const char* name, bool isRet)
2098 : CFRefBug(tf, name), isReturn(isRet) {}
2099 public:
2100
2101 const char* getDescription() const { return ""; }
2102
2103 bool isLeak() const { return true; }
2104 };
2105
2106 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2107 public:
2108 LeakAtReturn(CFRefCount* tf, const char* name)
2109 : Leak(tf, name, true) {}
2110 };
2111
2112 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2113 public:
2114 LeakWithinFunction(CFRefCount* tf, const char* name)
2115 : Leak(tf, name, false) {}
2116 };
2117
2118 //===---------===//
2119 // Bug Reports. //
2120 //===---------===//
2121
2122 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2123 protected:
2124 SymbolRef Sym;
2125 const CFRefCount &TF;
2126 public:
2127 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2128 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002129 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2130
2131 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2132 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu264e9372009-05-12 10:10:00 +00002133 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00002134
2135 virtual ~CFRefReport() {}
2136
2137 CFRefBug& getBugType() {
2138 return (CFRefBug&) RangedBugReport::getBugType();
2139 }
2140 const CFRefBug& getBugType() const {
2141 return (const CFRefBug&) RangedBugReport::getBugType();
2142 }
2143
2144 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2145 const SourceRange*& end) {
2146
2147 if (!getBugType().isLeak())
2148 RangedBugReport::getRanges(BR, beg, end);
2149 else
2150 beg = end = 0;
2151 }
2152
2153 SymbolRef getSymbol() const { return Sym; }
2154
Ted Kremenek8966bc12009-05-06 21:39:49 +00002155 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002156 const ExplodedNode<GRState>* N);
2157
2158 std::pair<const char**,const char**> getExtraDescriptiveText();
2159
2160 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2161 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002162 BugReporterContext& BRC);
Ted Kremenekc887d132009-04-29 18:50:19 +00002163 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002164
Ted Kremenekc887d132009-04-29 18:50:19 +00002165 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2166 SourceLocation AllocSite;
2167 const MemRegion* AllocBinding;
2168 public:
2169 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2170 ExplodedNode<GRState> *n, SymbolRef sym,
2171 GRExprEngine& Eng);
2172
Ted Kremenek8966bc12009-05-06 21:39:49 +00002173 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002174 const ExplodedNode<GRState>* N);
2175
2176 SourceLocation getLocation() const { return AllocSite; }
2177 };
2178} // end anonymous namespace
2179
2180void CFRefCount::RegisterChecks(BugReporter& BR) {
2181 useAfterRelease = new UseAfterRelease(this);
2182 BR.Register(useAfterRelease);
2183
2184 releaseNotOwned = new BadRelease(this);
2185 BR.Register(releaseNotOwned);
2186
2187 deallocGC = new DeallocGC(this);
2188 BR.Register(deallocGC);
2189
2190 deallocNotOwned = new DeallocNotOwned(this);
2191 BR.Register(deallocNotOwned);
2192
Ted Kremenek369de562009-05-09 00:10:05 +00002193 overAutorelease = new OverAutorelease(this);
2194 BR.Register(overAutorelease);
2195
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002196 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2197 BR.Register(returnNotOwnedForOwned);
2198
Ted Kremenekc887d132009-04-29 18:50:19 +00002199 // First register "return" leaks.
2200 const char* name = 0;
2201
2202 if (isGCEnabled())
2203 name = "Leak of returned object when using garbage collection";
2204 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2205 name = "Leak of returned object when not using garbage collection (GC) in "
2206 "dual GC/non-GC code";
2207 else {
2208 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2209 name = "Leak of returned object";
2210 }
2211
2212 leakAtReturn = new LeakAtReturn(this, name);
2213 BR.Register(leakAtReturn);
2214
2215 // Second, register leaks within a function/method.
2216 if (isGCEnabled())
2217 name = "Leak of object when using garbage collection";
2218 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2219 name = "Leak of object when not using garbage collection (GC) in "
2220 "dual GC/non-GC code";
2221 else {
2222 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2223 name = "Leak";
2224 }
2225
2226 leakWithinFunction = new LeakWithinFunction(this, name);
2227 BR.Register(leakWithinFunction);
2228
2229 // Save the reference to the BugReporter.
2230 this->BR = &BR;
2231}
2232
2233static const char* Msgs[] = {
2234 // GC only
2235 "Code is compiled to only use garbage collection",
2236 // No GC.
2237 "Code is compiled to use reference counts",
2238 // Hybrid, with GC.
2239 "Code is compiled to use either garbage collection (GC) or reference counts"
2240 " (non-GC). The bug occurs with GC enabled",
2241 // Hybrid, without GC
2242 "Code is compiled to use either garbage collection (GC) or reference counts"
2243 " (non-GC). The bug occurs in non-GC mode"
2244};
2245
2246std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2247 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2248
2249 switch (TF.getLangOptions().getGCMode()) {
2250 default:
2251 assert(false);
2252
2253 case LangOptions::GCOnly:
2254 assert (TF.isGCEnabled());
2255 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2256
2257 case LangOptions::NonGC:
2258 assert (!TF.isGCEnabled());
2259 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2260
2261 case LangOptions::HybridGC:
2262 if (TF.isGCEnabled())
2263 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2264 else
2265 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2266 }
2267}
2268
2269static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2270 ArgEffect X) {
2271 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2272 I!=E; ++I)
2273 if (*I == X) return true;
2274
2275 return false;
2276}
2277
2278PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2279 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002280 BugReporterContext& BRC) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002281
Ted Kremenek2033a952009-05-13 07:12:33 +00002282 if (!isa<PostStmt>(N->getLocation()))
2283 return NULL;
2284
Ted Kremenek8966bc12009-05-06 21:39:49 +00002285 // Check if the type state has changed.
Ted Kremenekb65be702009-06-18 01:23:53 +00002286 const GRState *PrevSt = PrevN->getState();
2287 const GRState *CurrSt = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002288
Ted Kremenekb65be702009-06-18 01:23:53 +00002289 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002290 if (!CurrT) return NULL;
2291
Ted Kremenekb65be702009-06-18 01:23:53 +00002292 const RefVal &CurrV = *CurrT;
2293 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002294
2295 // Create a string buffer to constain all the useful things we want
2296 // to tell the user.
2297 std::string sbuf;
2298 llvm::raw_string_ostream os(sbuf);
2299
2300 // This is the allocation site since the previous node had no bindings
2301 // for this symbol.
2302 if (!PrevT) {
2303 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2304
2305 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2306 // Get the name of the callee (if it is available).
Ted Kremenekb65be702009-06-18 01:23:53 +00002307 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
Ted Kremenekc887d132009-04-29 18:50:19 +00002308 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2309 os << "Call to function '" << FD->getNameAsString() <<'\'';
2310 else
2311 os << "function call";
2312 }
2313 else {
2314 assert (isa<ObjCMessageExpr>(S));
2315 os << "Method";
2316 }
2317
2318 if (CurrV.getObjKind() == RetEffect::CF) {
2319 os << " returns a Core Foundation object with a ";
2320 }
2321 else {
2322 assert (CurrV.getObjKind() == RetEffect::ObjC);
2323 os << " returns an Objective-C object with a ";
2324 }
2325
2326 if (CurrV.isOwned()) {
2327 os << "+1 retain count (owning reference).";
2328
2329 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2330 assert(CurrV.getObjKind() == RetEffect::CF);
2331 os << " "
2332 "Core Foundation objects are not automatically garbage collected.";
2333 }
2334 }
2335 else {
2336 assert (CurrV.isNotOwned());
2337 os << "+0 retain count (non-owning reference).";
2338 }
2339
Ted Kremenek8966bc12009-05-06 21:39:49 +00002340 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002341 return new PathDiagnosticEventPiece(Pos, os.str());
2342 }
2343
2344 // Gather up the effects that were performed on the object at this
2345 // program point
2346 llvm::SmallVector<ArgEffect, 2> AEffects;
2347
Ted Kremenek8966bc12009-05-06 21:39:49 +00002348 if (const RetainSummary *Summ =
2349 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002350 // We only have summaries attached to nodes after evaluating CallExpr and
2351 // ObjCMessageExprs.
2352 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2353
2354 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2355 // Iterate through the parameter expressions and see if the symbol
2356 // was ever passed as an argument.
2357 unsigned i = 0;
2358
2359 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2360 AI!=AE; ++AI, ++i) {
2361
2362 // Retrieve the value of the argument. Is it the symbol
2363 // we are interested in?
Ted Kremenekb65be702009-06-18 01:23:53 +00002364 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002365 continue;
2366
2367 // We have an argument. Get the effect!
2368 AEffects.push_back(Summ->getArg(i));
2369 }
2370 }
2371 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2372 if (Expr *receiver = ME->getReceiver())
Ted Kremenekb65be702009-06-18 01:23:53 +00002373 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002374 // The symbol we are tracking is the receiver.
2375 AEffects.push_back(Summ->getReceiverEffect());
2376 }
2377 }
2378 }
2379
2380 do {
2381 // Get the previous type state.
2382 RefVal PrevV = *PrevT;
2383
2384 // Specially handle -dealloc.
2385 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2386 // Determine if the object's reference count was pushed to zero.
2387 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2388 // We may not have transitioned to 'release' if we hit an error.
2389 // This case is handled elsewhere.
2390 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002391 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002392 os << "Object released by directly sending the '-dealloc' message";
2393 break;
2394 }
2395 }
2396
2397 // Specially handle CFMakeCollectable and friends.
2398 if (contains(AEffects, MakeCollectable)) {
2399 // Get the name of the function.
2400 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekb65be702009-06-18 01:23:53 +00002401 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
Ted Kremenekc887d132009-04-29 18:50:19 +00002402 const FunctionDecl* FD = X.getAsFunctionDecl();
2403 const std::string& FName = FD->getNameAsString();
2404
2405 if (TF.isGCEnabled()) {
2406 // Determine if the object's reference count was pushed to zero.
2407 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2408
2409 os << "In GC mode a call to '" << FName
2410 << "' decrements an object's retain count and registers the "
2411 "object with the garbage collector. ";
2412
2413 if (CurrV.getKind() == RefVal::Released) {
2414 assert(CurrV.getCount() == 0);
2415 os << "Since it now has a 0 retain count the object can be "
2416 "automatically collected by the garbage collector.";
2417 }
2418 else
2419 os << "An object must have a 0 retain count to be garbage collected. "
2420 "After this call its retain count is +" << CurrV.getCount()
2421 << '.';
2422 }
2423 else
2424 os << "When GC is not enabled a call to '" << FName
2425 << "' has no effect on its argument.";
2426
2427 // Nothing more to say.
2428 break;
2429 }
2430
2431 // Determine if the typestate has changed.
2432 if (!(PrevV == CurrV))
2433 switch (CurrV.getKind()) {
2434 case RefVal::Owned:
2435 case RefVal::NotOwned:
2436
Ted Kremenekf21332e2009-05-08 20:01:42 +00002437 if (PrevV.getCount() == CurrV.getCount()) {
2438 // Did an autorelease message get sent?
2439 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2440 return 0;
2441
Zhongxing Xu264e9372009-05-12 10:10:00 +00002442 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002443 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002444 break;
2445 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002446
2447 if (PrevV.getCount() > CurrV.getCount())
2448 os << "Reference count decremented.";
2449 else
2450 os << "Reference count incremented.";
2451
2452 if (unsigned Count = CurrV.getCount())
2453 os << " The object now has a +" << Count << " retain count.";
2454
2455 if (PrevV.getKind() == RefVal::Released) {
2456 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2457 os << " The object is not eligible for garbage collection until the "
2458 "retain count reaches 0 again.";
2459 }
2460
2461 break;
2462
2463 case RefVal::Released:
2464 os << "Object released.";
2465 break;
2466
2467 case RefVal::ReturnedOwned:
2468 os << "Object returned to caller as an owning reference (single retain "
2469 "count transferred to caller).";
2470 break;
2471
2472 case RefVal::ReturnedNotOwned:
2473 os << "Object returned to caller with a +0 (non-owning) retain count.";
2474 break;
2475
2476 default:
2477 return NULL;
2478 }
2479
2480 // Emit any remaining diagnostics for the argument effects (if any).
2481 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2482 E=AEffects.end(); I != E; ++I) {
2483
2484 // A bunch of things have alternate behavior under GC.
2485 if (TF.isGCEnabled())
2486 switch (*I) {
2487 default: break;
2488 case Autorelease:
2489 os << "In GC mode an 'autorelease' has no effect.";
2490 continue;
2491 case IncRefMsg:
2492 os << "In GC mode the 'retain' message has no effect.";
2493 continue;
2494 case DecRefMsg:
2495 os << "In GC mode the 'release' message has no effect.";
2496 continue;
2497 }
2498 }
2499 } while(0);
2500
2501 if (os.str().empty())
2502 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002503
2504 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek8966bc12009-05-06 21:39:49 +00002505 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002506 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2507
2508 // Add the range by scanning the children of the statement for any bindings
2509 // to Sym.
2510 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2511 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb65be702009-06-18 01:23:53 +00002512 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002513 P->addRange(Exp->getSourceRange());
2514 break;
2515 }
2516
2517 return P;
2518}
2519
2520namespace {
2521 class VISIBILITY_HIDDEN FindUniqueBinding :
2522 public StoreManager::BindingsHandler {
2523 SymbolRef Sym;
2524 const MemRegion* Binding;
2525 bool First;
2526
2527 public:
2528 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2529
2530 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2531 SVal val) {
2532
2533 SymbolRef SymV = val.getAsSymbol();
2534 if (!SymV || SymV != Sym)
2535 return true;
2536
2537 if (Binding) {
2538 First = false;
2539 return false;
2540 }
2541 else
2542 Binding = R;
2543
2544 return true;
2545 }
2546
2547 operator bool() { return First && Binding; }
2548 const MemRegion* getRegion() { return Binding; }
2549 };
2550}
2551
2552static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2553GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2554 SymbolRef Sym) {
2555
2556 // Find both first node that referred to the tracked symbol and the
2557 // memory location that value was store to.
2558 const ExplodedNode<GRState>* Last = N;
2559 const MemRegion* FirstBinding = 0;
2560
2561 while (N) {
2562 const GRState* St = N->getState();
2563 RefBindings B = St->get<RefBindings>();
2564
2565 if (!B.lookup(Sym))
2566 break;
2567
2568 FindUniqueBinding FB(Sym);
2569 StateMgr.iterBindings(St, FB);
2570 if (FB) FirstBinding = FB.getRegion();
2571
2572 Last = N;
2573 N = N->pred_empty() ? NULL : *(N->pred_begin());
2574 }
2575
2576 return std::make_pair(Last, FirstBinding);
2577}
2578
2579PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002580CFRefReport::getEndPath(BugReporterContext& BRC,
2581 const ExplodedNode<GRState>* EndN) {
2582 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002583 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002584 BRC.addNotableSymbol(Sym);
2585 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenekc887d132009-04-29 18:50:19 +00002586}
2587
2588PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002589CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2590 const ExplodedNode<GRState>* EndN){
Ted Kremenekc887d132009-04-29 18:50:19 +00002591
Ted Kremenek8966bc12009-05-06 21:39:49 +00002592 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002593 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002594 BRC.addNotableSymbol(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002595
2596 // We are reporting a leak. Walk up the graph to get to the first node where
2597 // the symbol appeared, and also get the first VarDecl that tracked object
2598 // is stored to.
2599 const ExplodedNode<GRState>* AllocNode = 0;
2600 const MemRegion* FirstBinding = 0;
2601
2602 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002603 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002604
2605 // Get the allocate site.
2606 assert(AllocNode);
2607 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2608
Ted Kremenek8966bc12009-05-06 21:39:49 +00002609 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002610 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2611
2612 // Compute an actual location for the leak. Sometimes a leak doesn't
2613 // occur at an actual statement (e.g., transition between blocks; end
2614 // of function) so we need to walk the graph and compute a real location.
2615 const ExplodedNode<GRState>* LeakN = EndN;
2616 PathDiagnosticLocation L;
2617
2618 while (LeakN) {
2619 ProgramPoint P = LeakN->getLocation();
2620
2621 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2622 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2623 break;
2624 }
2625 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2626 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2627 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2628 break;
2629 }
2630 }
2631
2632 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2633 }
2634
2635 if (!L.isValid()) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00002636 const Decl &D = BRC.getCodeDecl();
2637 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenekc887d132009-04-29 18:50:19 +00002638 }
2639
2640 std::string sbuf;
2641 llvm::raw_string_ostream os(sbuf);
2642
2643 os << "Object allocated on line " << AllocLine;
2644
2645 if (FirstBinding)
2646 os << " and stored into '" << FirstBinding->getString() << '\'';
2647
2648 // Get the retain count.
2649 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2650
2651 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2652 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2653 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2654 // to the caller for NS objects.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002655 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenekc887d132009-04-29 18:50:19 +00002656 os << " is returned from a method whose name ('"
Ted Kremeneka8833552009-04-29 23:03:22 +00002657 << MD.getSelector().getAsString()
Ted Kremenekc887d132009-04-29 18:50:19 +00002658 << "') does not contain 'copy' or otherwise starts with"
2659 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek8987a022009-04-29 22:25:52 +00002660 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002661 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002662 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2663 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2664 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002665 << "' is potentially leaked when using garbage collection. Callers "
2666 "of this method do not expect a returned object with a +1 retain "
2667 "count since they expect the object to be managed by the garbage "
2668 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002669 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002670 else
2671 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek8987a022009-04-29 22:25:52 +00002672 " +" << RV->getCount() << " (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002673
2674 return new PathDiagnosticEventPiece(L, os.str());
2675}
2676
Ted Kremenekc887d132009-04-29 18:50:19 +00002677CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2678 ExplodedNode<GRState> *n,
2679 SymbolRef sym, GRExprEngine& Eng)
2680: CFRefReport(D, tf, n, sym)
2681{
2682
2683 // Most bug reports are cached at the location where they occured.
2684 // With leaks, we want to unique them by the location where they were
2685 // allocated, and only report a single path. To do this, we need to find
2686 // the allocation site of a piece of tracked memory, which we do via a
2687 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2688 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2689 // that all ancestor nodes that represent the allocation site have the
2690 // same SourceLocation.
2691 const ExplodedNode<GRState>* AllocNode = 0;
2692
2693 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekf04dced2009-05-08 23:32:51 +00002694 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenekc887d132009-04-29 18:50:19 +00002695
2696 // Get the SourceLocation for the allocation site.
2697 ProgramPoint P = AllocNode->getLocation();
2698 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2699
2700 // Fill in the description of the bug.
2701 Description.clear();
2702 llvm::raw_string_ostream os(Description);
2703 SourceManager& SMgr = Eng.getContext().getSourceManager();
2704 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002705 os << "Potential leak ";
2706 if (tf.isGCEnabled()) {
2707 os << "(when using garbage collection) ";
2708 }
2709 os << "of an object allocated on line " << AllocLine;
Ted Kremenekc887d132009-04-29 18:50:19 +00002710
2711 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2712 if (AllocBinding)
2713 os << " and stored into '" << AllocBinding->getString() << '\'';
2714}
2715
2716//===----------------------------------------------------------------------===//
2717// Main checker logic.
2718//===----------------------------------------------------------------------===//
2719
Ted Kremenek553cf182008-06-25 21:21:56 +00002720/// GetReturnType - Used to get the return type of a message expression or
2721/// function call with the intention of affixing that type to a tracked symbol.
2722/// While the the return type can be queried directly from RetEx, when
2723/// invoking class methods we augment to the return type to be that of
2724/// a pointer to the class (as opposed it just being id).
2725static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2726
2727 QualType RetTy = RetE->getType();
2728
2729 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00002730 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002731 if (!PT)
2732 return RetTy;
2733
2734 // If RetEx is not a message expression just return its type.
2735 // If RetEx is a message expression, return its types if it is something
2736 /// more specific than id.
2737
2738 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2739
Steve Naroff389bf462009-02-12 17:52:19 +00002740 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00002741 return RetTy;
2742
2743 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2744
2745 // At this point we know the return type of the message expression is id.
2746 // If we have an ObjCInterceDecl, we know this is a call to a class method
2747 // whose type we can resolve. In such cases, promote the return type to
2748 // Class*.
2749 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2750}
2751
2752
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002753void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002754 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002755 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002756 Expr* Ex,
2757 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00002758 const RetainSummary& Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00002759 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002760 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002761
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002762 // Get the state.
Zhongxing Xu264e9372009-05-12 10:10:00 +00002763 GRStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekb65be702009-06-18 01:23:53 +00002764 const GRState *state = Builder.GetState(Pred);
Zhongxing Xu264e9372009-05-12 10:10:00 +00002765 ASTContext& Ctx = StateMgr.getContext();
2766 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek14993892008-05-06 02:41:27 +00002767
2768 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002769 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002770 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002771 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00002772 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002773
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002774 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002775 SVal V = state->getSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00002776 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002777
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002778 if (Sym)
Ted Kremenekb65be702009-06-18 01:23:53 +00002779 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002780 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002781 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002782 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002783 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002784 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00002785 }
2786 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002787 }
Ted Kremenek070a8252008-07-09 18:11:16 +00002788
Ted Kremenek94c96982009-03-03 22:06:47 +00002789 if (isa<Loc>(V)) {
2790 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002791 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenek070a8252008-07-09 18:11:16 +00002792 continue;
2793
2794 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002795
2796 // FIXME: Either this logic should also be replicated in GRSimpleVals
2797 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00002798
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002799 // FIXME: We can have collisions on the conjured symbol if the
2800 // expression *I also creates conjured symbols. We probably want
2801 // to identify conjured symbols by an expression pair: the enclosing
2802 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00002803 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00002804
Ted Kremenek993f1c72008-10-17 20:28:54 +00002805 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xuf82af1e2009-04-29 02:30:09 +00002806
Ted Kremenek42530512009-05-06 18:19:24 +00002807 if (R) {
2808 // Are we dealing with an ElementRegion? If the element type is
2809 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xu2e7c6782009-05-11 14:28:14 +00002810 // is a variable region then strip off the ElementRegion.
Ted Kremenek42530512009-05-06 18:19:24 +00002811 // FIXME: We really need to think about this for the general case
2812 // as sometimes we are reasoning about arrays and other times
2813 // about (char*), etc., is just a form of passing raw bytes.
2814 // e.g., void *p = alloca(); foo((char*)p);
2815 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2816 // Checking for 'integral type' is probably too promiscuous, but
2817 // we'll leave it in for now until we have a systematic way of
2818 // handling all of these cases. Eventually we need to come up
2819 // with an interface to StoreManager so that this logic can be
2820 // approriately delegated to the respective StoreManagers while
2821 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu264e9372009-05-12 10:10:00 +00002822 // invalidating reference counts), probably via callbacks.
Ted Kremenek109bf472009-05-11 22:55:17 +00002823 if (ER->getElementType()->isIntegralType()) {
2824 const MemRegion *superReg = ER->getSuperRegion();
2825 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2826 isa<ObjCIvarRegion>(superReg))
2827 R = cast<TypedRegion>(superReg);
2828 }
2829
Ted Kremenek42530512009-05-06 18:19:24 +00002830 // FIXME: What about layers of ElementRegions?
2831 }
2832
Ted Kremenek40e86d92008-12-18 23:34:57 +00002833 // Is the invalidated variable something that we were tracking?
Ted Kremenekb65be702009-06-18 01:23:53 +00002834 SymbolRef Sym = state->getSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00002835
Ted Kremenekd104a092009-03-04 22:56:43 +00002836 // Remove any existing reference-count binding.
Ted Kremenekb65be702009-06-18 01:23:53 +00002837 if (Sym) state = state->remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00002838
Ted Kremenekd104a092009-03-04 22:56:43 +00002839 if (R->isBoundable(Ctx)) {
2840 // Set the value of the variable to be a conjured symbol.
2841 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xua82d8aa2009-05-09 03:57:34 +00002842 QualType T = R->getValueType(Ctx);
Ted Kremenekd104a092009-03-04 22:56:43 +00002843
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002844 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002845 ValueManager &ValMgr = Eng.getValueManager();
2846 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Ted Kremenekb65be702009-06-18 01:23:53 +00002847 state = state->bindLoc(Loc::MakeVal(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002848 }
2849 else if (const RecordType *RT = T->getAsStructureType()) {
2850 // Handle structs in a not so awesome way. Here we just
2851 // eagerly bind new symbols to the fields. In reality we
2852 // should have the store manager handle this. The idea is just
2853 // to prototype some basic functionality here. All of this logic
2854 // should one day soon just go away.
2855 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2856
2857 // No record definition. There is nothing we can do.
2858 if (!RD)
2859 continue;
2860
Ted Kremenekb65be702009-06-18 01:23:53 +00002861 MemRegionManager &MRMgr =
2862 state->getStateManager().getRegionManager();
Ted Kremenekd104a092009-03-04 22:56:43 +00002863
2864 // Iterate through the fields and construct new symbols.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002865 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2866 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002867
2868 // For now just handle scalar fields.
2869 FieldDecl *FD = *FI;
2870 QualType FT = FD->getType();
2871
2872 if (Loc::IsLocType(FT) ||
Zhongxing Xu264e9372009-05-12 10:10:00 +00002873 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002874 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu264e9372009-05-12 10:10:00 +00002875
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002876 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Ted Kremenekb65be702009-06-18 01:23:53 +00002877 state = state->bindLoc(Loc::MakeVal(FR), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002878 }
2879 }
Zhongxing Xu264e9372009-05-12 10:10:00 +00002880 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2881 // Set the default value of the array to conjured symbol.
2882 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2883 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2884 Count);
Ted Kremenekb65be702009-06-18 01:23:53 +00002885 state = StoreMgr.setDefaultValue(state, R, V);
Zhongxing Xu264e9372009-05-12 10:10:00 +00002886 } else {
Ted Kremenekd104a092009-03-04 22:56:43 +00002887 // Just blast away other values.
Ted Kremenekb65be702009-06-18 01:23:53 +00002888 state = state->bindLoc(*MR, UnknownVal());
Ted Kremenekd104a092009-03-04 22:56:43 +00002889 }
Ted Kremenekfd301942008-10-17 22:23:12 +00002890 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002891 }
2892 else
Ted Kremenekb65be702009-06-18 01:23:53 +00002893 state = state->bindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002894 }
2895 else {
2896 // Nuke all other arguments passed by reference.
Ted Kremenekb65be702009-06-18 01:23:53 +00002897 state = state->unbindLoc(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002898 }
Ted Kremenekb8873552008-04-11 20:51:02 +00002899 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002900 else if (isa<nonloc::LocAsInteger>(V))
Ted Kremenekb65be702009-06-18 01:23:53 +00002901 state = state->unbindLoc(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002902 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002903
Ted Kremenek553cf182008-06-25 21:21:56 +00002904 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00002905 if (!ErrorExpr && Receiver) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002906 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002907 if (Sym) {
Ted Kremenekb65be702009-06-18 01:23:53 +00002908 if (const RefVal* T = state->get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002909 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002910 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00002911 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002912 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00002913 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002914 }
Ted Kremenek14993892008-05-06 02:41:27 +00002915 }
2916 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002917
Ted Kremenek553cf182008-06-25 21:21:56 +00002918 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002919 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002920 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002921 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002922 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002923 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002924
Ted Kremenek70a733e2008-07-18 17:24:20 +00002925 // Consult the summary for the return value.
Ted Kremenek7faca822009-05-04 04:57:00 +00002926 RetEffect RE = Summ.getRetEffect();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002927
Ted Kremenek78a35a32009-05-12 20:06:54 +00002928 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2929 assert(Receiver);
Ted Kremenekb65be702009-06-18 01:23:53 +00002930 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek78a35a32009-05-12 20:06:54 +00002931 bool found = false;
2932 if (SymbolRef Sym = V.getAsLocSymbol())
Ted Kremenekb65be702009-06-18 01:23:53 +00002933 if (state->get<RefBindings>(Sym)) {
Ted Kremenek78a35a32009-05-12 20:06:54 +00002934 found = true;
2935 RE = Summaries.getObjAllocRetEffect();
2936 }
2937
2938 if (!found)
2939 RE = RetEffect::MakeNoRet();
2940 }
2941
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002942 switch (RE.getKind()) {
2943 default:
2944 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002945
Ted Kremenekfd301942008-10-17 22:23:12 +00002946 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002947
Ted Kremenekf9561e52008-04-11 20:23:24 +00002948 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00002949 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2950 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00002951
Ted Kremenekfd301942008-10-17 22:23:12 +00002952 // FIXME: We eventually should handle structs and other compound types
2953 // that are returned by value.
2954
2955 QualType T = Ex->getType();
2956
Ted Kremenek062e2f92008-11-13 06:10:40 +00002957 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002958 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002959 ValueManager &ValMgr = Eng.getValueManager();
2960 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenekb65be702009-06-18 01:23:53 +00002961 state = state->bindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00002962 }
2963
Ted Kremenek940b1d82008-04-10 23:44:06 +00002964 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00002965 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002966
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002967 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00002968 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00002969 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002970 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb65be702009-06-18 01:23:53 +00002971 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
2972 state = state->bindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002973 break;
2974 }
2975
Ted Kremenek14993892008-05-06 02:41:27 +00002976 case RetEffect::ReceiverAlias: {
2977 assert (Receiver);
Ted Kremenekb65be702009-06-18 01:23:53 +00002978 SVal V = state->getSValAsScalarOrLoc(Receiver);
2979 state = state->bindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00002980 break;
2981 }
2982
Ted Kremeneka7344702008-06-23 18:02:52 +00002983 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002984 case RetEffect::OwnedSymbol: {
2985 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002986 ValueManager &ValMgr = Eng.getValueManager();
2987 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2988 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekb65be702009-06-18 01:23:53 +00002989 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
Ted Kremenek044b6f02009-04-09 16:13:17 +00002990 RetT));
Ted Kremenekb65be702009-06-18 01:23:53 +00002991 state = state->bindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002992
2993 // FIXME: Add a flag to the checker where allocations are assumed to
2994 // *not fail.
2995#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00002996 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2997 bool isFeasible;
2998 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2999 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
3000 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00003001#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00003002
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00003003 break;
3004 }
Ted Kremeneke798e7c2009-04-27 19:14:45 +00003005
3006 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00003007 case RetEffect::NotOwnedSymbol: {
3008 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00003009 ValueManager &ValMgr = Eng.getValueManager();
3010 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
3011 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekb65be702009-06-18 01:23:53 +00003012 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
Ted Kremenek044b6f02009-04-09 16:13:17 +00003013 RetT));
Ted Kremenekb65be702009-06-18 01:23:53 +00003014 state = state->bindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00003015 break;
3016 }
3017 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003018
Ted Kremenekf5b34b12009-02-18 02:00:25 +00003019 // Generate a sink node if we are at the end of a path.
3020 GRExprEngine::NodeTy *NewNode =
Ted Kremenek7faca822009-05-04 04:57:00 +00003021 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
3022 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekf5b34b12009-02-18 02:00:25 +00003023
3024 // Annotate the edge with summary we used.
Ted Kremenek7faca822009-05-04 04:57:00 +00003025 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003026}
3027
3028
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003029void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003030 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003031 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00003032 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003033 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00003034 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek7faca822009-05-04 04:57:00 +00003035 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xu369f4472009-04-20 05:24:46 +00003036 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003037
Ted Kremenek7faca822009-05-04 04:57:00 +00003038 assert(Summ);
3039 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00003040 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00003041}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003042
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003043void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00003044 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003045 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00003046 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003047 ExplodedNode<GRState>* Pred) {
Ted Kremenek7faca822009-05-04 04:57:00 +00003048 RetainSummary* Summ = 0;
Ted Kremenek9040c652008-05-01 21:31:50 +00003049
Ted Kremenek553cf182008-06-25 21:21:56 +00003050 if (Expr* Receiver = ME->getReceiver()) {
3051 // We need the type-information of the tracked receiver object
3052 // Retrieve it from the state.
Ted Kremenek70b6a832009-05-13 18:16:01 +00003053 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek553cf182008-06-25 21:21:56 +00003054
3055 // FIXME: Wouldn't it be great if this code could be reduced? It's just
3056 // a chain of lookups.
Ted Kremenek8711c032009-04-29 05:04:30 +00003057 // FIXME: Is this really working as expected? There are cases where
3058 // we just use the 'ID' from the message expression.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003059 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00003060 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00003061
Ted Kremenek94c96982009-03-03 22:06:47 +00003062 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00003063 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003064 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00003065 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00003066
3067 if (const PointerType* PT = Ty->getAsPointerType()) {
3068 QualType PointeeTy = PT->getPointeeType();
3069
3070 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
3071 ID = IT->getDecl();
3072 }
3073 }
3074 }
Ted Kremenek70b6a832009-05-13 18:16:01 +00003075
3076 // FIXME: this is a hack. This may or may not be the actual method
3077 // that is called.
3078 if (!ID) {
3079 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
3080 if (const ObjCInterfaceType *p =
3081 PT->getPointeeType()->getAsObjCInterfaceType())
3082 ID = p->getDecl();
3083 }
3084
Ted Kremenekce8a41d2009-04-29 17:09:14 +00003085 // FIXME: The receiver could be a reference to a class, meaning that
3086 // we should use the class method.
3087 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00003088
Ted Kremenek896cd9d2008-10-23 01:56:15 +00003089 // Special-case: are we sending a mesage to "self"?
3090 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek885c27b2009-05-04 05:31:22 +00003091 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
3092 if (Expr* Receiver = ME->getReceiver()) {
3093 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
3094 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
3095 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
3096 // Update the summary to make the default argument effect
3097 // 'StopTracking'.
3098 Summ = Summaries.copySummary(Summ);
3099 Summ->setDefaultArgEffect(StopTracking);
3100 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00003101 }
3102 }
Ted Kremenek553cf182008-06-25 21:21:56 +00003103 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003104 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00003105 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003106
Ted Kremenek7faca822009-05-04 04:57:00 +00003107 if (!Summ)
3108 Summ = Summaries.getDefaultSummary();
Ted Kremenekde4d5332009-04-24 17:50:11 +00003109
Ted Kremenek7faca822009-05-04 04:57:00 +00003110 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenekb3095252008-05-06 04:20:12 +00003111 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00003112}
Ted Kremenek5216ad72009-02-14 03:16:10 +00003113
3114namespace {
3115class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
Ted Kremenek3a772032009-06-18 00:49:02 +00003116 const GRState *state;
Ted Kremenek5216ad72009-02-14 03:16:10 +00003117public:
Ted Kremenek3a772032009-06-18 00:49:02 +00003118 StopTrackingCallback(const GRState *st) : state(st) {}
3119 const GRState *getState() const { return state; }
Ted Kremenek5216ad72009-02-14 03:16:10 +00003120
3121 bool VisitSymbol(SymbolRef sym) {
Ted Kremenek3a772032009-06-18 00:49:02 +00003122 state = state->remove<RefBindings>(sym);
Ted Kremenek5216ad72009-02-14 03:16:10 +00003123 return true;
3124 }
Ted Kremenek5216ad72009-02-14 03:16:10 +00003125};
3126} // end anonymous namespace
3127
3128
Ted Kremenek41573eb2009-02-14 01:43:44 +00003129void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00003130 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00003131 bool escapes = false;
3132
Ted Kremeneka496d162008-10-18 03:49:51 +00003133 // A value escapes in three possible cases (this may change):
3134 //
3135 // (1) we are binding to something that is not a memory region.
3136 // (2) we are binding to a memregion that does not have stack storage
3137 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00003138 // does not understand.
Ted Kremenek3a772032009-06-18 00:49:02 +00003139 const GRState *state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00003140
Ted Kremenek41573eb2009-02-14 01:43:44 +00003141 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00003142 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00003143 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00003144 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3145 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00003146
3147 if (!escapes) {
3148 // To test (3), generate a new state with the binding removed. If it is
3149 // the same state, then it escapes (since the store cannot represent
3150 // the binding).
Ted Kremenekb65be702009-06-18 01:23:53 +00003151 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00003152 }
Ted Kremenek9e240492008-10-04 05:50:14 +00003153 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00003154
Ted Kremenek5216ad72009-02-14 03:16:10 +00003155 // If our store can represent the binding and we aren't storing to something
3156 // that doesn't have local storage then just return and have the simulation
3157 // state continue as is.
3158 if (!escapes)
3159 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00003160
Ted Kremenek5216ad72009-02-14 03:16:10 +00003161 // Otherwise, find all symbols referenced by 'val' that we are tracking
3162 // and stop tracking them.
Ted Kremenek3a772032009-06-18 00:49:02 +00003163 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00003164}
3165
Ted Kremenek4fd88972008-04-17 18:12:53 +00003166 // Return statements.
3167
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003168void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00003169 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003170 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00003171 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003172 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003173
3174 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00003175 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00003176 return;
3177
Ted Kremenekb65be702009-06-18 01:23:53 +00003178 const GRState *state = Builder.GetState(Pred);
3179 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00003180
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00003181 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00003182 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003183
Ted Kremenek4fd88972008-04-17 18:12:53 +00003184 // Get the reference count binding (if any).
Ted Kremenekb65be702009-06-18 01:23:53 +00003185 const RefVal* T = state->get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00003186
3187 if (!T)
3188 return;
3189
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003190 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00003191 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003192
Ted Kremenek78a35a32009-05-12 20:06:54 +00003193 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003194 case RefVal::Owned: {
3195 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003196 assert (cnt > 0);
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003197 X.setCount(cnt - 1);
3198 X = X ^ RefVal::ReturnedOwned;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003199 break;
3200 }
3201
3202 case RefVal::NotOwned: {
3203 unsigned cnt = X.getCount();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003204 if (cnt) {
3205 X.setCount(cnt - 1);
3206 X = X ^ RefVal::ReturnedOwned;
3207 }
3208 else {
3209 X = X ^ RefVal::ReturnedNotOwned;
3210 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003211 break;
3212 }
3213
3214 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00003215 return;
3216 }
3217
3218 // Update the binding.
Ted Kremenekb65be702009-06-18 01:23:53 +00003219 state = state->set<RefBindings>(Sym, X);
Ted Kremenekc887d132009-04-29 18:50:19 +00003220 Pred = Builder.MakeNode(Dst, S, Pred, state);
3221
Ted Kremenek9f246b62009-04-30 05:51:50 +00003222 // Did we cache out?
3223 if (!Pred)
3224 return;
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003225
3226 // Update the autorelease counts.
3227 static unsigned autoreleasetag = 0;
3228 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3229 bool stop = false;
3230 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3231 X, stop);
3232
3233 // Did we cache out?
3234 if (!Pred || stop)
3235 return;
3236
3237 // Get the updated binding.
Ted Kremenekb65be702009-06-18 01:23:53 +00003238 T = state->get<RefBindings>(Sym);
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003239 assert(T);
3240 X = *T;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003241
Ted Kremenekc887d132009-04-29 18:50:19 +00003242 // Any leaks or other errors?
3243 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003244 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremeneka8833552009-04-29 23:03:22 +00003245 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00003246 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003247 RetEffect RE = Summ.getRetEffect();
3248 bool hasError = false;
3249
Ted Kremenekfae664a2009-05-16 01:38:01 +00003250 if (RE.getKind() != RetEffect::NoRet) {
3251 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3252 // Things are more complicated with garbage collection. If the
3253 // returned object is suppose to be an Objective-C object, we have
3254 // a leak (as the caller expects a GC'ed object) because no
3255 // method should return ownership unless it returns a CF object.
3256 X = X ^ RefVal::ErrorGCLeakReturned;
3257
3258 // Keep this false until this is properly tested.
3259 hasError = true;
3260 }
3261 else if (!RE.isOwned()) {
3262 // Either we are using GC and the returned object is a CF type
3263 // or we aren't using GC. In either case, we expect that the
3264 // enclosing method is expected to return ownership.
3265 hasError = true;
3266 X = X ^ RefVal::ErrorLeakReturned;
3267 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003268 }
3269
3270 if (hasError) {
Ted Kremenekc887d132009-04-29 18:50:19 +00003271 // Generate an error node.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003272 static int ReturnOwnLeakTag = 0;
Ted Kremenekb65be702009-06-18 01:23:53 +00003273 state = state->set<RefBindings>(Sym, X);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003274 ExplodedNode<GRState> *N =
3275 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3276 if (N) {
3277 CFRefReport *report =
Ted Kremenek9f246b62009-04-30 05:51:50 +00003278 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3279 N, Sym, Eng);
3280 BR->EmitReport(report);
3281 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003282 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003283 }
3284 }
3285 else if (X.isReturnedNotOwned()) {
3286 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3287 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3288 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3289 if (Summ.getRetEffect().isOwned()) {
3290 // Trying to return a not owned object to a caller expecting an
3291 // owned object.
3292
3293 static int ReturnNotOwnedForOwnedTag = 0;
Ted Kremenekb65be702009-06-18 01:23:53 +00003294 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003295 if (ExplodedNode<GRState> *N =
3296 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3297 state, Pred)) {
3298 CFRefReport *report =
3299 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3300 *this, N, Sym);
3301 BR->EmitReport(report);
3302 }
3303 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003304 }
3305 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003306}
3307
Ted Kremenekcb612922008-04-18 19:23:43 +00003308// Assumptions.
3309
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003310const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
Ted Kremenekb65be702009-06-18 01:23:53 +00003311 const GRState* state,
3312 SVal Cond, bool Assumption,
3313 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003314
3315 // FIXME: We may add to the interface of EvalAssume the list of symbols
3316 // whose assumptions have changed. For now we just iterate through the
3317 // bindings and check if any of the tracked symbols are NULL. This isn't
3318 // too bad since the number of symbols we will track in practice are
3319 // probably small and EvalAssume is only called at branches and a few
3320 // other places.
Ted Kremenekb65be702009-06-18 01:23:53 +00003321 RefBindings B = state->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003322
3323 if (B.isEmpty())
Ted Kremenekb65be702009-06-18 01:23:53 +00003324 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003325
Ted Kremenekb65be702009-06-18 01:23:53 +00003326 bool changed = false;
3327 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003328
3329 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003330 // Check if the symbol is null (or equal to any constant).
3331 // If this is the case, stop tracking the symbol.
Ted Kremenekb65be702009-06-18 01:23:53 +00003332 if (VMgr.getSymVal(state, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003333 changed = true;
3334 B = RefBFactory.Remove(B, I.getKey());
3335 }
3336 }
3337
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003338 if (changed)
Ted Kremenekb65be702009-06-18 01:23:53 +00003339 state = state->set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00003340
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003341 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003342}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003343
Ted Kremenekb65be702009-06-18 01:23:53 +00003344const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003345 RefVal V, ArgEffect E,
3346 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00003347
3348 // In GC mode [... release] and [... retain] do nothing.
3349 switch (E) {
3350 default: break;
3351 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3352 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00003353 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00003354 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3355 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003356 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003357
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003358 // Handle all use-after-releases.
3359 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3360 V = V ^ RefVal::ErrorUseAfterRelease;
3361 hasErr = V.getKind();
Ted Kremenekb65be702009-06-18 01:23:53 +00003362 return state->set<RefBindings>(sym, V);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003363 }
3364
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003365 switch (E) {
3366 default:
3367 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003368
3369 case Dealloc:
3370 // Any use of -dealloc in GC is *bad*.
3371 if (isGCEnabled()) {
3372 V = V ^ RefVal::ErrorDeallocGC;
3373 hasErr = V.getKind();
3374 break;
3375 }
3376
3377 switch (V.getKind()) {
3378 default:
3379 assert(false && "Invalid case.");
3380 case RefVal::Owned:
3381 // The object immediately transitions to the released state.
3382 V = V ^ RefVal::Released;
3383 V.clearCounts();
Ted Kremenekb65be702009-06-18 01:23:53 +00003384 return state->set<RefBindings>(sym, V);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003385 case RefVal::NotOwned:
3386 V = V ^ RefVal::ErrorDeallocNotOwned;
3387 hasErr = V.getKind();
3388 break;
3389 }
3390 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003391
Ted Kremenek35790732009-02-25 23:11:49 +00003392 case NewAutoreleasePool:
3393 assert(!isGCEnabled());
Ted Kremenekb65be702009-06-18 01:23:53 +00003394 return state->add<AutoreleaseStack>(sym);
Ted Kremenek35790732009-02-25 23:11:49 +00003395
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003396 case MayEscape:
3397 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00003398 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003399 break;
3400 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003401
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003402 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00003403
Ted Kremenek070a8252008-07-09 18:11:16 +00003404 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003405 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003406 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00003407
Ted Kremenekabf43972009-01-28 21:44:40 +00003408 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003409 if (isGCEnabled())
3410 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00003411
3412 // Update the autorelease counts.
3413 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf21332e2009-05-08 20:01:42 +00003414 V = V.autorelease();
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003415 break;
Ted Kremenek369de562009-05-09 00:10:05 +00003416
Ted Kremenek14993892008-05-06 02:41:27 +00003417 case StopTracking:
Ted Kremenekb65be702009-06-18 01:23:53 +00003418 return state->remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003419
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003420 case IncRef:
3421 switch (V.getKind()) {
3422 default:
3423 assert(false);
3424
3425 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003426 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00003427 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003428 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003429 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003430 // Non-GC cases are handled above.
3431 assert(isGCEnabled());
3432 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003433 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003434 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003435 break;
3436
Ted Kremenek553cf182008-06-25 21:21:56 +00003437 case SelfOwn:
3438 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003439 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003440 case DecRef:
3441 switch (V.getKind()) {
3442 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003443 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003444 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003445
Ted Kremenek553cf182008-06-25 21:21:56 +00003446 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00003447 assert(V.getCount() > 0);
3448 if (V.getCount() == 1) V = V ^ RefVal::Released;
3449 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003450 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003451
Ted Kremenek553cf182008-06-25 21:21:56 +00003452 case RefVal::NotOwned:
3453 if (V.getCount() > 0)
3454 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00003455 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00003456 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003457 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00003458 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003459 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003460
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003461 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003462 // Non-GC cases are handled above.
3463 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00003464 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003465 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003466 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003467 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003468 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003469 }
Ted Kremenekb65be702009-06-18 01:23:53 +00003470 return state->set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003471}
3472
Ted Kremenekfa34b332008-04-09 01:10:13 +00003473//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003474// Handle dead symbols and end-of-path.
3475//===----------------------------------------------------------------------===//
3476
Ted Kremenekb65be702009-06-18 01:23:53 +00003477std::pair<ExplodedNode<GRState>*, const GRState *>
3478CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Ted Kremenekf04dced2009-05-08 23:32:51 +00003479 ExplodedNode<GRState>* Pred,
Ted Kremenek369de562009-05-09 00:10:05 +00003480 GRExprEngine &Eng,
3481 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekf04dced2009-05-08 23:32:51 +00003482
Ted Kremenek369de562009-05-09 00:10:05 +00003483 unsigned ACnt = V.getAutoreleaseCount();
3484 stop = false;
3485
3486 // No autorelease counts? Nothing to be done.
3487 if (!ACnt)
3488 return std::make_pair(Pred, state);
3489
3490 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3491 unsigned Cnt = V.getCount();
3492
Ted Kremenek95d3b902009-05-11 15:26:06 +00003493 // FIXME: Handle sending 'autorelease' to already released object.
3494
3495 if (V.getKind() == RefVal::ReturnedOwned)
3496 ++Cnt;
3497
Ted Kremenek369de562009-05-09 00:10:05 +00003498 if (ACnt <= Cnt) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003499 if (ACnt == Cnt) {
3500 V.clearCounts();
Ted Kremenek95d3b902009-05-11 15:26:06 +00003501 if (V.getKind() == RefVal::ReturnedOwned)
3502 V = V ^ RefVal::ReturnedNotOwned;
3503 else
3504 V = V ^ RefVal::NotOwned;
Ted Kremenek80c24182009-05-09 00:44:07 +00003505 }
Ted Kremenek95d3b902009-05-11 15:26:06 +00003506 else {
Ted Kremenek80c24182009-05-09 00:44:07 +00003507 V.setCount(Cnt - ACnt);
3508 V.setAutoreleaseCount(0);
3509 }
Ted Kremenekb65be702009-06-18 01:23:53 +00003510 state = state->set<RefBindings>(Sym, V);
Ted Kremenek369de562009-05-09 00:10:05 +00003511 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3512 stop = (N == 0);
3513 return std::make_pair(N, state);
3514 }
3515
3516 // Woah! More autorelease counts then retain counts left.
3517 // Emit hard error.
3518 stop = true;
3519 V = V ^ RefVal::ErrorOverAutorelease;
Ted Kremenekb65be702009-06-18 01:23:53 +00003520 state = state->set<RefBindings>(Sym, V);
Ted Kremenek369de562009-05-09 00:10:05 +00003521
3522 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003523 N->markAsSink();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003524
3525 std::string sbuf;
3526 llvm::raw_string_ostream os(sbuf);
Ted Kremenekdaec1452009-05-15 06:02:08 +00003527 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003528 if (V.getAutoreleaseCount() > 1)
3529 os << V.getAutoreleaseCount() << " times";
3530 os << " but the object has ";
3531 if (V.getCount() == 0)
3532 os << "zero (locally visible)";
3533 else
3534 os << "+" << V.getCount();
3535 os << " retain counts";
3536
Ted Kremenek369de562009-05-09 00:10:05 +00003537 CFRefReport *report =
3538 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003539 *this, N, Sym, os.str().c_str());
Ted Kremenek369de562009-05-09 00:10:05 +00003540 BR->EmitReport(report);
3541 }
3542
3543 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekf04dced2009-05-08 23:32:51 +00003544}
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003545
Ted Kremenekb65be702009-06-18 01:23:53 +00003546const GRState *
3547CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003548 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3549
3550 bool hasLeak = V.isOwned() ||
3551 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3552
3553 if (!hasLeak)
Ted Kremenekb65be702009-06-18 01:23:53 +00003554 return state->remove<RefBindings>(sid);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003555
3556 Leaked.push_back(sid);
Ted Kremenekb65be702009-06-18 01:23:53 +00003557 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003558}
3559
3560ExplodedNode<GRState>*
Ted Kremenekb65be702009-06-18 01:23:53 +00003561CFRefCount::ProcessLeaks(const GRState * state,
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003562 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3563 GenericNodeBuilder &Builder,
3564 GRExprEngine& Eng,
3565 ExplodedNode<GRState> *Pred) {
3566
3567 if (Leaked.empty())
3568 return Pred;
3569
Ted Kremenekf04dced2009-05-08 23:32:51 +00003570 // Generate an intermediate node representing the leak point.
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003571 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003572
3573 if (N) {
3574 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3575 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3576
3577 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3578 : leakAtReturn);
3579 assert(BT && "BugType not initialized.");
3580 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3581 BR->EmitReport(report);
3582 }
3583 }
3584
3585 return N;
3586}
3587
Ted Kremenekcf701772009-02-05 06:50:21 +00003588void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3589 GREndPathNodeBuilder<GRState>& Builder) {
3590
Ted Kremenekb65be702009-06-18 01:23:53 +00003591 const GRState *state = Builder.getState();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003592 GenericNodeBuilder Bd(Builder);
Ted Kremenekb65be702009-06-18 01:23:53 +00003593 RefBindings B = state->get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003594 ExplodedNode<GRState> *Pred = 0;
3595
3596 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek369de562009-05-09 00:10:05 +00003597 bool stop = false;
3598 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3599 (*I).first,
3600 (*I).second, stop);
3601
3602 if (stop)
3603 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003604 }
3605
Ted Kremenekb65be702009-06-18 01:23:53 +00003606 B = state->get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003607 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003608
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003609 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3610 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3611
Ted Kremenekf04dced2009-05-08 23:32:51 +00003612 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003613}
3614
3615void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3616 GRExprEngine& Eng,
3617 GRStmtNodeBuilder<GRState>& Builder,
3618 ExplodedNode<GRState>* Pred,
3619 Stmt* S,
Ted Kremenekb65be702009-06-18 01:23:53 +00003620 const GRState* state,
Ted Kremenekcf701772009-02-05 06:50:21 +00003621 SymbolReaper& SymReaper) {
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003622
Ted Kremenekb65be702009-06-18 01:23:53 +00003623 RefBindings B = state->get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003624
3625 // Update counts from autorelease pools
3626 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3627 E = SymReaper.dead_end(); I != E; ++I) {
3628 SymbolRef Sym = *I;
3629 if (const RefVal* T = B.lookup(Sym)){
3630 // Use the symbol as the tag.
3631 // FIXME: This might not be as unique as we would like.
3632 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek369de562009-05-09 00:10:05 +00003633 bool stop = false;
3634 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3635 Sym, *T, stop);
3636 if (stop)
3637 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003638 }
3639 }
3640
Ted Kremenekb65be702009-06-18 01:23:53 +00003641 B = state->get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003642 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003643
3644 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003645 E = SymReaper.dead_end(); I != E; ++I) {
3646 if (const RefVal* T = B.lookup(*I))
3647 state = HandleSymbolDeath(state, *I, *T, Leaked);
3648 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003649
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003650 static unsigned LeakPPTag = 0;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003651 {
3652 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3653 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3654 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003655
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003656 // Did we cache out?
3657 if (!Pred)
3658 return;
Ted Kremenek33b6f632009-02-19 23:47:02 +00003659
3660 // Now generate a new node that nukes the old bindings.
Ted Kremenekb65be702009-06-18 01:23:53 +00003661 RefBindings::Factory& F = state->get_context<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003662
Ted Kremenek33b6f632009-02-19 23:47:02 +00003663 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003664 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3665
Ted Kremenekb65be702009-06-18 01:23:53 +00003666 state = state->set<RefBindings>(B);
Ted Kremenek33b6f632009-02-19 23:47:02 +00003667 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003668}
3669
3670void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3671 GRStmtNodeBuilder<GRState>& Builder,
3672 Expr* NodeExpr, Expr* ErrorExpr,
3673 ExplodedNode<GRState>* Pred,
3674 const GRState* St,
3675 RefVal::Kind hasErr, SymbolRef Sym) {
3676 Builder.BuildSinks = true;
3677 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3678
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003679 if (!N)
3680 return;
Ted Kremenekcf701772009-02-05 06:50:21 +00003681
3682 CFRefBug *BT = 0;
3683
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003684 switch (hasErr) {
3685 default:
3686 assert(false && "Unhandled error.");
3687 return;
3688 case RefVal::ErrorUseAfterRelease:
3689 BT = static_cast<CFRefBug*>(useAfterRelease);
3690 break;
3691 case RefVal::ErrorReleaseNotOwned:
3692 BT = static_cast<CFRefBug*>(releaseNotOwned);
3693 break;
3694 case RefVal::ErrorDeallocGC:
3695 BT = static_cast<CFRefBug*>(deallocGC);
3696 break;
3697 case RefVal::ErrorDeallocNotOwned:
3698 BT = static_cast<CFRefBug*>(deallocNotOwned);
3699 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003700 }
3701
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003702 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003703 report->addRange(ErrorExpr->getSourceRange());
3704 BR->EmitReport(report);
3705}
3706
3707//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003708// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003709//===----------------------------------------------------------------------===//
3710
Ted Kremenek072192b2008-04-30 23:47:44 +00003711GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3712 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003713 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003714}