blob: 4b2c394c88a989509726442974e4f6b1e644cf64 [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenekc3bc6c82009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
Ted Kremenek314b1952009-04-29 23:03:22 +0000152static const ObjCMethodDecl*
153ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
154 ObjCInterfaceDecl *ID =
155 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
156
157 return MD->isInstanceMethod()
158 ? ID->lookupInstanceMethod(Context, MD->getSelector())
159 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000160}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000161
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000162namespace {
163class VISIBILITY_HIDDEN GenericNodeBuilder {
164 GRStmtNodeBuilder<GRState> *SNB;
165 Stmt *S;
166 const void *tag;
167 GREndPathNodeBuilder<GRState> *ENB;
168public:
169 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
170 const void *t)
171 : SNB(&snb), S(s), tag(t), ENB(0) {}
172 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
173 : SNB(0), S(0), tag(0), ENB(&enb) {}
174
175 ExplodedNode<GRState> *MakeNode(const GRState *state,
176 ExplodedNode<GRState> *Pred) {
177 if (SNB)
Ted Kremenek3e3328d2009-05-09 01:50:57 +0000178 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000179
180 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000181 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000182 }
183};
184} // end anonymous namespace
185
Ted Kremenek7d421f32008-04-09 23:49:11 +0000186//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000187// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000188//===----------------------------------------------------------------------===//
189
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000190static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000191 IdentifierInfo* II = &Ctx.Idents.get(name);
192 return Ctx.Selectors.getSelector(0, &II);
193}
194
Ted Kremenek0e344d42008-05-06 00:30:21 +0000195static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
196 IdentifierInfo* II = &Ctx.Idents.get(name);
197 return Ctx.Selectors.getSelector(1, &II);
198}
199
Ted Kremenek272aa852008-06-25 21:21:56 +0000200//===----------------------------------------------------------------------===//
201// Type querying functions.
202//===----------------------------------------------------------------------===//
203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204static bool hasPrefix(const char* s, const char* prefix) {
205 if (!prefix)
206 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000207
Ted Kremenek17144e82009-01-12 21:45:02 +0000208 char c = *s;
209 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000210
Ted Kremenek17144e82009-01-12 21:45:02 +0000211 while (c != '\0' && cP != '\0') {
212 if (c != cP) break;
213 c = *(++s);
214 cP = *(++prefix);
215 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000216
Ted Kremenek17144e82009-01-12 21:45:02 +0000217 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000218}
219
Ted Kremenek17144e82009-01-12 21:45:02 +0000220static bool hasSuffix(const char* s, const char* suffix) {
221 const char* loc = strstr(s, suffix);
222 return loc && strcmp(suffix, loc) == 0;
223}
224
225static bool isRefType(QualType RetTy, const char* prefix,
226 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000227
Ted Kremenek2f289b62009-05-12 04:53:03 +0000228 // Recursively walk the typedef stack, allowing typedefs of reference types.
229 while (1) {
230 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
231 const char* TDName = TD->getDecl()->getIdentifier()->getName();
232 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
233 return true;
234
235 RetTy = TD->getDecl()->getUnderlyingType();
236 continue;
237 }
238 break;
Ted Kremenek17144e82009-01-12 21:45:02 +0000239 }
240
241 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000242 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000243
244 // Is the type void*?
245 const PointerType* PT = RetTy->getAsPointerType();
246 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000247 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000248
249 // Does the name start with the prefix?
250 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000251}
252
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000253//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000254// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000255//===----------------------------------------------------------------------===//
256
Ted Kremenek272aa852008-06-25 21:21:56 +0000257/// ArgEffect is used to summarize a function/method call's effect on a
258/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000259enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
260 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
261 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000262
Ted Kremeneka7338b42008-03-11 06:39:11 +0000263namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000264template <> struct FoldingSetTrait<ArgEffect> {
265static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
266 ID.AddInteger((unsigned) X);
267}
Ted Kremenek272aa852008-06-25 21:21:56 +0000268};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000269} // end llvm namespace
270
Ted Kremeneka56ae162009-05-03 05:20:50 +0000271/// ArgEffects summarizes the effects of a function/method call on all of
272/// its arguments.
273typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
274
Ted Kremeneka7338b42008-03-11 06:39:11 +0000275namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000276
277/// RetEffect is used to summarize a function/method call's behavior with
278/// respect to its return value.
279class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000280public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000281 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000282 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
283 OwnedWhenTrackedReceiver };
Ted Kremenek68621b92009-01-28 05:56:51 +0000284
285 enum ObjKind { CF, ObjC, AnyObj };
286
Ted Kremeneka7338b42008-03-11 06:39:11 +0000287private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000288 Kind K;
289 ObjKind O;
290 unsigned index;
291
292 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
293 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000294
Ted Kremeneka7338b42008-03-11 06:39:11 +0000295public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000296 Kind getKind() const { return K; }
297
298 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000299
300 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000301 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000302 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000303 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000304
Ted Kremenek314b1952009-04-29 23:03:22 +0000305 bool isOwned() const {
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000306 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
307 K == OwnedWhenTrackedReceiver;
Ted Kremenek314b1952009-04-29 23:03:22 +0000308 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +0000309
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000310 static RetEffect MakeOwnedWhenTrackedReceiver() {
311 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
312 }
313
Ted Kremenek272aa852008-06-25 21:21:56 +0000314 static RetEffect MakeAlias(unsigned Idx) {
315 return RetEffect(Alias, Idx);
316 }
317 static RetEffect MakeReceiverAlias() {
318 return RetEffect(ReceiverAlias);
319 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000320 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
321 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000322 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000323 static RetEffect MakeNotOwned(ObjKind o) {
324 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000325 }
326 static RetEffect MakeGCNotOwned() {
327 return RetEffect(GCNotOwnedSymbol, ObjC);
328 }
329
Ted Kremenek272aa852008-06-25 21:21:56 +0000330 static RetEffect MakeNoRet() {
331 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000332 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000333
Ted Kremenek272aa852008-06-25 21:21:56 +0000334 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000335 ID.AddInteger((unsigned)K);
336 ID.AddInteger((unsigned)O);
337 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000338 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000339};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000340
Ted Kremenek272aa852008-06-25 21:21:56 +0000341
Ted Kremenek2f226732009-05-04 05:31:22 +0000342class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000343 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
344 /// specifies the argument (starting from 0). This can be sparsely
345 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000346 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000347
348 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
349 /// do not have an entry in Args.
350 ArgEffect DefaultArgEffect;
351
Ted Kremenek272aa852008-06-25 21:21:56 +0000352 /// Receiver - If this summary applies to an Objective-C message expression,
353 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000354 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000355
356 /// Ret - The effect on the return value. Used to indicate if the
357 /// function/method call returns a new tracked symbol, returns an
358 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000359 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000360
Ted Kremenekf2717b02008-07-18 17:24:20 +0000361 /// EndPath - Indicates that execution of this method/function should
362 /// terminate the simulation of a path.
363 bool EndPath;
364
Ted Kremeneka7338b42008-03-11 06:39:11 +0000365public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000366 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000367 ArgEffect ReceiverEff, bool endpath = false)
368 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
369 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370
Ted Kremenek272aa852008-06-25 21:21:56 +0000371 /// getArg - Return the argument effect on the argument specified by
372 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000373 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000374 if (const ArgEffect *AE = Args.lookup(idx))
375 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000376
Ted Kremenekbcaff792008-05-06 15:44:25 +0000377 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000378 }
379
Ted Kremenek2f226732009-05-04 05:31:22 +0000380 /// setDefaultArgEffect - Set the default argument effect.
381 void setDefaultArgEffect(ArgEffect E) {
382 DefaultArgEffect = E;
383 }
384
385 /// setArg - Set the argument effect on the argument specified by idx.
386 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
387 Args = AF.Add(Args, idx, E);
388 }
389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000391 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000392
Ted Kremenek2f226732009-05-04 05:31:22 +0000393 /// setRetEffect - Set the effect of the return value of the call.
394 void setRetEffect(RetEffect E) { Ret = E; }
395
Ted Kremenekf2717b02008-07-18 17:24:20 +0000396 /// isEndPath - Returns true if executing the given method/function should
397 /// terminate the path.
398 bool isEndPath() const { return EndPath; }
399
Ted Kremenek272aa852008-06-25 21:21:56 +0000400 /// getReceiverEffect - Returns the effect on the receiver of the call.
401 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000402 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000403
Ted Kremenek2f226732009-05-04 05:31:22 +0000404 /// setReceiverEffect - Set the effect on the receiver of the call.
405 void setReceiverEffect(ArgEffect E) { Receiver = E; }
406
Ted Kremeneka56ae162009-05-03 05:20:50 +0000407 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000408
Ted Kremeneka56ae162009-05-03 05:20:50 +0000409 ExprIterator begin_args() const { return Args.begin(); }
410 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000411
Ted Kremeneka56ae162009-05-03 05:20:50 +0000412 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000413 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000414 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000415 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000416 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000417 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000418 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000419 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000420 }
421
422 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000423 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000424 }
425};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000426} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000427
Ted Kremenek272aa852008-06-25 21:21:56 +0000428//===----------------------------------------------------------------------===//
429// Data structures for constructing summaries.
430//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000431
Ted Kremenek272aa852008-06-25 21:21:56 +0000432namespace {
433class VISIBILITY_HIDDEN ObjCSummaryKey {
434 IdentifierInfo* II;
435 Selector S;
436public:
437 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
438 : II(ii), S(s) {}
439
Ted Kremenek314b1952009-04-29 23:03:22 +0000440 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000441 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +0000442
443 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
444 : II(d ? d->getIdentifier() : ii), S(s) {}
Ted Kremenek272aa852008-06-25 21:21:56 +0000445
446 ObjCSummaryKey(Selector s)
447 : II(0), S(s) {}
448
449 IdentifierInfo* getIdentifier() const { return II; }
450 Selector getSelector() const { return S; }
451};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000452}
453
454namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000455template <> struct DenseMapInfo<ObjCSummaryKey> {
456 static inline ObjCSummaryKey getEmptyKey() {
457 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
458 DenseMapInfo<Selector>::getEmptyKey());
459 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000460
Ted Kremenek272aa852008-06-25 21:21:56 +0000461 static inline ObjCSummaryKey getTombstoneKey() {
462 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
463 DenseMapInfo<Selector>::getTombstoneKey());
464 }
465
466 static unsigned getHashValue(const ObjCSummaryKey &V) {
467 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
468 & 0x88888888)
469 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
470 & 0x55555555);
471 }
472
473 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
474 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
475 RHS.getIdentifier()) &&
476 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
477 RHS.getSelector());
478 }
479
480 static bool isPod() {
481 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
482 DenseMapInfo<Selector>::isPod();
483 }
484};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000485} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000486
Ted Kremenek84f010c2008-06-23 23:30:29 +0000487namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000488class VISIBILITY_HIDDEN ObjCSummaryCache {
489 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
490 MapTy M;
491public:
492 ObjCSummaryCache() {}
493
494 typedef MapTy::iterator iterator;
495
Ted Kremenek314b1952009-04-29 23:03:22 +0000496 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
497 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000498 // Lookup the method using the decl for the class @interface. If we
499 // have no decl, lookup using the class name.
500 return D ? find(D, S) : find(ClsName, S);
501 }
502
Ted Kremenek314b1952009-04-29 23:03:22 +0000503 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000504 // Do a lookup with the (D,S) pair. If we find a match return
505 // the iterator.
506 ObjCSummaryKey K(D, S);
507 MapTy::iterator I = M.find(K);
508
509 if (I != M.end() || !D)
510 return I;
511
512 // Walk the super chain. If we find a hit with a parent, we'll end
513 // up returning that summary. We actually allow that key (null,S), as
514 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
515 // generate initial summaries without having to worry about NSObject
516 // being declared.
517 // FIXME: We may change this at some point.
518 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
519 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
520 break;
521
522 if (!C)
523 return I;
524 }
525
526 // Cache the summary with original key to make the next lookup faster
527 // and return the iterator.
528 M[K] = I->second;
529 return I;
530 }
531
Ted Kremenek9449ca92008-08-12 20:41:56 +0000532
Ted Kremenek272aa852008-06-25 21:21:56 +0000533 iterator find(Expr* Receiver, Selector S) {
534 return find(getReceiverDecl(Receiver), S);
535 }
536
537 iterator find(IdentifierInfo* II, Selector S) {
538 // FIXME: Class method lookup. Right now we dont' have a good way
539 // of going between IdentifierInfo* and the class hierarchy.
540 iterator I = M.find(ObjCSummaryKey(II, S));
541 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
542 }
543
544 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
545
546 const PointerType* PT = E->getType()->getAsPointerType();
547 if (!PT) return 0;
548
549 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
550 if (!OI) return 0;
551
552 return OI ? OI->getDecl() : 0;
553 }
554
555 iterator end() { return M.end(); }
556
557 RetainSummary*& operator[](ObjCMessageExpr* ME) {
558
559 Selector S = ME->getSelector();
560
561 if (Expr* Receiver = ME->getReceiver()) {
562 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
563 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
564 }
565
566 return M[ObjCSummaryKey(ME->getClassName(), S)];
567 }
568
569 RetainSummary*& operator[](ObjCSummaryKey K) {
570 return M[K];
571 }
572
573 RetainSummary*& operator[](Selector S) {
574 return M[ ObjCSummaryKey(S) ];
575 }
576};
577} // end anonymous namespace
578
579//===----------------------------------------------------------------------===//
580// Data structures for managing collections of summaries.
581//===----------------------------------------------------------------------===//
582
583namespace {
584class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000585
586 //==-----------------------------------------------------------------==//
587 // Typedefs.
588 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000589
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000590 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
591 FuncSummariesTy;
592
Ted Kremenek84f010c2008-06-23 23:30:29 +0000593 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000594
595 //==-----------------------------------------------------------------==//
596 // Data.
597 //==-----------------------------------------------------------------==//
598
Ted Kremenek272aa852008-06-25 21:21:56 +0000599 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000600 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000601
Ted Kremenekede40b72008-07-09 18:11:16 +0000602 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
603 /// "CFDictionaryCreate".
604 IdentifierInfo* CFDictionaryCreateII;
605
Ted Kremenek272aa852008-06-25 21:21:56 +0000606 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000607 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000608
Ted Kremenek272aa852008-06-25 21:21:56 +0000609 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000610 FuncSummariesTy FuncSummaries;
611
Ted Kremenek272aa852008-06-25 21:21:56 +0000612 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
613 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000614 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000615
Ted Kremenek272aa852008-06-25 21:21:56 +0000616 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000617 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000618
Ted Kremenek272aa852008-06-25 21:21:56 +0000619 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
620 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000621 llvm::BumpPtrAllocator BPAlloc;
622
Ted Kremeneka56ae162009-05-03 05:20:50 +0000623 /// AF - A factory for ArgEffects objects.
624 ArgEffects::Factory AF;
625
Ted Kremenek272aa852008-06-25 21:21:56 +0000626 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000627 ArgEffects ScratchArgs;
628
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000629 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
630 /// objects.
631 RetEffect ObjCAllocRetE;
632
Ted Kremenek286e9852009-05-04 04:57:00 +0000633 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000634 RetainSummary* StopSummary;
635
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000636 //==-----------------------------------------------------------------==//
637 // Methods.
638 //==-----------------------------------------------------------------==//
639
Ted Kremenek272aa852008-06-25 21:21:56 +0000640 /// getArgEffects - Returns a persistent ArgEffects object based on the
641 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000642 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000643
Ted Kremenek562c1302008-05-05 16:51:50 +0000644 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000645
646public:
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000647 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
648
Ted Kremenek2f226732009-05-04 05:31:22 +0000649 RetainSummary *getDefaultSummary() {
650 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
651 return new (Summ) RetainSummary(DefaultSummary);
652 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000653
Ted Kremenek064ef322009-02-23 16:51:39 +0000654 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000655
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000656 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
657 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000658 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000659
Ted Kremeneka56ae162009-05-03 05:20:50 +0000660 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000661 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000662 ArgEffect DefaultEff = MayEscape,
663 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000664
Ted Kremenek266d8b62008-05-06 02:26:56 +0000665 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000666 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000667 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000668 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000669 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000670
Ted Kremeneka821b792009-04-29 05:04:30 +0000671 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000672 if (StopSummary)
673 return StopSummary;
674
675 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
676 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000677
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000678 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000679 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000680
Ted Kremeneka821b792009-04-29 05:04:30 +0000681 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000682
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000683 void InitializeClassMethodSummaries();
684 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000685
Ted Kremenek9b42e062009-05-03 04:42:10 +0000686 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000687 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000688
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000689private:
690
Ted Kremenekf2717b02008-07-18 17:24:20 +0000691 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
692 RetainSummary* Summ) {
693 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
694 }
695
Ted Kremenek272aa852008-06-25 21:21:56 +0000696 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
697 ObjCClassMethodSummaries[S] = Summ;
698 }
699
700 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
701 ObjCMethodSummaries[S] = Summ;
702 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000703
704 void addClassMethSummary(const char* Cls, const char* nullaryName,
705 RetainSummary *Summ) {
706 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
707 Selector S = GetNullarySelector(nullaryName, Ctx);
708 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
709 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000710
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000711 void addInstMethSummary(const char* Cls, const char* nullaryName,
712 RetainSummary *Summ) {
713 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
714 Selector S = GetNullarySelector(nullaryName, Ctx);
715 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
716 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000717
718 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000719 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000720
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000721 while (const char* s = va_arg(argp, const char*))
722 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000723
724 return Ctx.Selectors.getSelector(II.size(), &II[0]);
725 }
726
727 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
728 RetainSummary* Summ, va_list argp) {
729 Selector S = generateSelector(argp);
730 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000731 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000732
733 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
734 va_list argp;
735 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000736 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000737 va_end(argp);
738 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000739
740 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
741 va_list argp;
742 va_start(argp, Summ);
743 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
744 va_end(argp);
745 }
746
747 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
748 va_list argp;
749 va_start(argp, Summ);
750 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
751 va_end(argp);
752 }
753
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000754 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000755 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
756 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000757 DoNothing, DoNothing, true);
758 va_list argp;
759 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000760 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000761 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000762 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000763
Ted Kremeneka7338b42008-03-11 06:39:11 +0000764public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000765
766 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000767 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000768 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000769 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000770 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
771 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000772 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
773 RetEffect::MakeNoRet() /* return effect */,
Ted Kremeneka13b0862009-05-11 18:30:24 +0000774 MayEscape, /* default argument effect */
775 DoNothing /* receiver effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000776 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000777
778 InitializeClassMethodSummaries();
779 InitializeMethodSummaries();
780 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000781
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000782 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000783
Ted Kremenekd13c1872008-06-24 03:56:45 +0000784 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000785
Ted Kremenek314b1952009-04-29 23:03:22 +0000786 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
787 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000788 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000789 ID, ME->getMethodDecl(), ME->getType());
790 }
791
Ted Kremenek04e00302009-04-29 17:09:14 +0000792 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000793 const ObjCInterfaceDecl* ID,
794 const ObjCMethodDecl *MD,
795 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000796
797 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000798 const ObjCInterfaceDecl *ID,
799 const ObjCMethodDecl *MD,
800 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000801
802 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
803 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
804 ME->getClassInfo().first,
805 ME->getMethodDecl(), ME->getType());
806 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000807
808 /// getMethodSummary - This version of getMethodSummary is used to query
809 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000810 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
811 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000812 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000813 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000814 IdentifierInfo *ClsName = ID->getIdentifier();
815 QualType ResultTy = MD->getResultType();
816
Ted Kremenek81eb4642009-04-30 05:47:23 +0000817 // Resolve the method decl last.
818 if (const ObjCMethodDecl *InterfaceMD =
819 ResolveToInterfaceMethodDecl(MD, Ctx))
820 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000821
Ted Kremenek91b89a42009-04-29 17:17:48 +0000822 if (MD->isInstanceMethod())
823 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
824 else
825 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
826 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000827
Ted Kremenek314b1952009-04-29 23:03:22 +0000828 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
829 Selector S, QualType RetTy);
830
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000831 void updateSummaryFromAnnotations(RetainSummary &Summ,
832 const ObjCMethodDecl *MD);
833
834 void updateSummaryFromAnnotations(RetainSummary &Summ,
835 const FunctionDecl *FD);
836
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000837 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000838
839 RetainSummary *copySummary(RetainSummary *OldSumm) {
840 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
841 new (Summ) RetainSummary(*OldSumm);
842 return Summ;
843 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000844};
845
846} // end anonymous namespace
847
848//===----------------------------------------------------------------------===//
849// Implementation of checker data structures.
850//===----------------------------------------------------------------------===//
851
Ted Kremeneka56ae162009-05-03 05:20:50 +0000852RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000853
Ted Kremeneka56ae162009-05-03 05:20:50 +0000854ArgEffects RetainSummaryManager::getArgEffects() {
855 ArgEffects AE = ScratchArgs;
856 ScratchArgs = AF.GetEmptyMap();
857 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000858}
859
Ted Kremenek266d8b62008-05-06 02:26:56 +0000860RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000861RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000862 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000863 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000864 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000865 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000866 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000867 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000868 return Summ;
869}
870
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000871//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000872// Predicates.
873//===----------------------------------------------------------------------===//
874
Ted Kremenek9b42e062009-05-03 04:42:10 +0000875bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000876 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000877 return false;
878
Ted Kremenek0d813552009-04-23 22:11:07 +0000879 // We assume that id<..>, id, and "Class" all represent tracked objects.
880 const PointerType *PT = Ty->getAsPointerType();
881 if (PT == 0)
882 return true;
883
884 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000885
886 // We assume that id<..>, id, and "Class" all represent tracked objects.
887 if (!OT)
888 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000889
890 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000891 // FIXME: We can memoize here if this gets too expensive.
892 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
893 ObjCInterfaceDecl* ID = OT->getDecl();
894
895 for ( ; ID ; ID = ID->getSuperClass())
896 if (ID->getIdentifier() == NSObjectII)
897 return true;
898
899 return false;
900}
901
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000902bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
903 return isRefType(T, "CF") || // Core Foundation.
904 isRefType(T, "CG") || // Core Graphics.
905 isRefType(T, "DADisk") || // Disk Arbitration API.
906 isRefType(T, "DADissenter") ||
907 isRefType(T, "DASessionRef");
908}
909
Ted Kremenek35920ed2009-01-07 00:39:56 +0000910//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000911// Summary creation for functions (largely uses of Core Foundation).
912//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000913
Ted Kremenek17144e82009-01-12 21:45:02 +0000914static bool isRetain(FunctionDecl* FD, const char* FName) {
915 const char* loc = strstr(FName, "Retain");
916 return loc && loc[sizeof("Retain")-1] == '\0';
917}
918
919static bool isRelease(FunctionDecl* FD, const char* FName) {
920 const char* loc = strstr(FName, "Release");
921 return loc && loc[sizeof("Release")-1] == '\0';
922}
923
Ted Kremenekd13c1872008-06-24 03:56:45 +0000924RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000925 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000926 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000927 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000928 return I->second;
929
Ted Kremenek64cddf12009-05-04 15:34:07 +0000930 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000931 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000932
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000933 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000934 // We generate "stop" summaries for implicitly defined functions.
935 if (FD->isImplicit()) {
936 S = getPersistentStopSummary();
937 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000938 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000939
Ted Kremenek064ef322009-02-23 16:51:39 +0000940 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000941 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000942 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000943 const char* FName = FD->getIdentifier()->getName();
944
Ted Kremenek38c6f022009-03-05 22:11:14 +0000945 // Strip away preceding '_'. Doing this here will effect all the checks
946 // down below.
947 while (*FName == '_') ++FName;
948
Ted Kremenek17144e82009-01-12 21:45:02 +0000949 // Inspect the result type.
950 QualType RetTy = FT->getResultType();
951
952 // FIXME: This should all be refactored into a chain of "summary lookup"
953 // filters.
954 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
955 // FIXES: <rdar://problem/6326900>
956 // This should be addressed using a API table. This strcmp is also
957 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000958 assert (ScratchArgs.isEmpty());
959 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000960 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
961 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000962 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000963
964 // Enable this code once the semantics of NSDeallocateObject are resolved
965 // for GC. <rdar://problem/6619988>
966#if 0
967 // Handle: NSDeallocateObject(id anObject);
968 // This method does allow 'nil' (although we don't check it now).
969 if (strcmp(FName, "NSDeallocateObject") == 0) {
970 return RetTy == Ctx.VoidTy
971 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
972 : getPersistentStopSummary();
973 }
974#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000975
976 // Handle: id NSMakeCollectable(CFTypeRef)
977 if (strcmp(FName, "NSMakeCollectable") == 0) {
978 S = (RetTy == Ctx.getObjCIdType())
979 ? getUnarySummary(FT, cfmakecollectable)
980 : getPersistentStopSummary();
981
982 break;
983 }
984
985 if (RetTy->isPointerType()) {
986 // For CoreFoundation ('CF') types.
987 if (isRefType(RetTy, "CF", &Ctx, FName)) {
988 if (isRetain(FD, FName))
989 S = getUnarySummary(FT, cfretain);
990 else if (strstr(FName, "MakeCollectable"))
991 S = getUnarySummary(FT, cfmakecollectable);
992 else
993 S = getCFCreateGetRuleSummary(FD, FName);
994
995 break;
996 }
997
998 // For CoreGraphics ('CG') types.
999 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1000 if (isRetain(FD, FName))
1001 S = getUnarySummary(FT, cfretain);
1002 else
1003 S = getCFCreateGetRuleSummary(FD, FName);
1004
1005 break;
1006 }
1007
1008 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1009 if (isRefType(RetTy, "DADisk") ||
1010 isRefType(RetTy, "DADissenter") ||
1011 isRefType(RetTy, "DASessionRef")) {
1012 S = getCFCreateGetRuleSummary(FD, FName);
1013 break;
1014 }
1015
1016 break;
1017 }
1018
1019 // Check for release functions, the only kind of functions that we care
1020 // about that don't return a pointer type.
1021 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001022 // Test for 'CGCF'.
1023 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1024 FName += 4;
1025 else
1026 FName += 2;
1027
1028 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001029 S = getUnarySummary(FT, cfrelease);
1030 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001031 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001032 // Remaining CoreFoundation and CoreGraphics functions.
1033 // We use to assume that they all strictly followed the ownership idiom
1034 // and that ownership cannot be transferred. While this is technically
1035 // correct, many methods allow a tracked object to escape. For example:
1036 //
1037 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1038 // CFDictionaryAddValue(y, key, x);
1039 // CFRelease(x);
1040 // ... it is okay to use 'x' since 'y' has a reference to it
1041 //
1042 // We handle this and similar cases with the follow heuristic. If the
1043 // function name contains "InsertValue", "SetValue" or "AddValue" then
1044 // we assume that arguments may "escape."
1045 //
1046 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1047 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001048 CStrInCStrNoCase(FName, "SetValue") ||
1049 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001050 ? MayEscape : DoNothing;
1051
1052 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001053 }
1054 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001055 }
1056 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001057
1058 if (!S)
1059 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001060
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001061 // Annotations override defaults.
1062 assert(S);
1063 updateSummaryFromAnnotations(*S, FD);
1064
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001065 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001066 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001067}
1068
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001069RetainSummary*
1070RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1071 const char* FName) {
1072
Ted Kremenek562c1302008-05-05 16:51:50 +00001073 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1074 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001075
Ted Kremenek562c1302008-05-05 16:51:50 +00001076 if (strstr(FName, "Get"))
1077 return getCFSummaryGetRule(FD);
1078
Ted Kremenek286e9852009-05-04 04:57:00 +00001079 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001080}
1081
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001082RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001083RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1084 UnaryFuncKind func) {
1085
Ted Kremenek17144e82009-01-12 21:45:02 +00001086 // Sanity check that this is *really* a unary function. This can
1087 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001088 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001089 if (!FTP || FTP->getNumArgs() != 1)
1090 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001091
Ted Kremeneka56ae162009-05-03 05:20:50 +00001092 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001093
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001094 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001095 case cfretain: {
1096 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001097 return getPersistentSummary(RetEffect::MakeAlias(0),
1098 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001099 }
1100
1101 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001102 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001103 return getPersistentSummary(RetEffect::MakeNoRet(),
1104 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001105 }
1106
1107 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001108 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001109 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001110 }
1111
1112 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001113 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001114 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001115 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001116}
1117
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001118RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001119 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001120
1121 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001122 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1123 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001124 }
1125
Ted Kremenek68621b92009-01-28 05:56:51 +00001126 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001127}
1128
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001129RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001130 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001131 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1132 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001133}
1134
Ted Kremeneka7338b42008-03-11 06:39:11 +00001135//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001136// Summary creation for Selectors.
1137//===----------------------------------------------------------------------===//
1138
Ted Kremenekbcaff792008-05-06 15:44:25 +00001139RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001140RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001141 assert(ScratchArgs.isEmpty());
1142 // 'init' methods conceptually return a newly allocated object and claim
1143 // the receiver.
1144 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
1145 return getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1146 DecRefMsg);
1147
1148 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001149}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001150
1151void
1152RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1153 const FunctionDecl *FD) {
1154 if (!FD)
1155 return;
1156
1157 // Determine if there is a special return effect for this method.
1158 if (isTrackedObjCObjectType(FD->getResultType())) {
1159 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1160 Summ.setRetEffect(ObjCAllocRetE);
1161 }
1162 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1163 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1164 }
1165 }
1166}
1167
1168void
1169RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1170 const ObjCMethodDecl *MD) {
1171 if (!MD)
1172 return;
1173
1174 // Determine if there is a special return effect for this method.
1175 if (isTrackedObjCObjectType(MD->getResultType())) {
1176 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1177 Summ.setRetEffect(ObjCAllocRetE);
1178 }
1179 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1180 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1181 }
1182 }
1183}
1184
Ted Kremenekbcaff792008-05-06 15:44:25 +00001185RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001186RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1187 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001188
Ted Kremenek578498a2009-04-29 00:42:39 +00001189 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001190 // Scan the method decl for 'void*' arguments. These should be treated
1191 // as 'StopTracking' because they are often used with delegates.
1192 // Delegates are a frequent form of false positives with the retain
1193 // count checker.
1194 unsigned i = 0;
1195 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1196 E = MD->param_end(); I != E; ++I, ++i)
1197 if (ParmVarDecl *PD = *I) {
1198 QualType Ty = Ctx.getCanonicalType(PD->getType());
1199 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001200 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001201 }
1202 }
1203
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001204 // Any special effect for the receiver?
1205 ArgEffect ReceiverEff = DoNothing;
1206
1207 // If one of the arguments in the selector has the keyword 'delegate' we
1208 // should stop tracking the reference count for the receiver. This is
1209 // because the reference count is quite possibly handled by a delegate
1210 // method.
1211 if (S.isKeywordSelector()) {
1212 const std::string &str = S.getAsString();
1213 assert(!str.empty());
1214 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1215 }
1216
Ted Kremenek174a0772009-04-23 23:08:22 +00001217 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001218 if (isTrackedObjCObjectType(RetTy)) {
1219 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1220 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001221 RetEffect E =
1222 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001223 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001224
1225 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001226 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001227
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001228 // Look for methods that return an owned core foundation object.
1229 if (isTrackedCFObjectType(RetTy)) {
1230 RetEffect E =
1231 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1232 ? RetEffect::MakeOwned(RetEffect::CF, true)
1233 : RetEffect::MakeNotOwned(RetEffect::CF);
1234
1235 return getPersistentSummary(E, ReceiverEff, MayEscape);
1236 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001237
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001238 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001239 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001240
Ted Kremenek2f226732009-05-04 05:31:22 +00001241 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001242}
1243
1244RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001245RetainSummaryManager::getInstanceMethodSummary(Selector S,
1246 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001247 const ObjCInterfaceDecl* ID,
1248 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001249 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001250
Ted Kremeneka821b792009-04-29 05:04:30 +00001251 // Look up a summary in our summary cache.
1252 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001253
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001254 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001255 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001256
Ted Kremeneka56ae162009-05-03 05:20:50 +00001257 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001258 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001259
Ted Kremenek2f226732009-05-04 05:31:22 +00001260 // "initXXX": pass-through for receiver.
1261 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1262 == InitRule)
1263 Summ = getInitMethodSummary(RetTy);
1264 else
1265 Summ = getCommonMethodSummary(MD, S, RetTy);
1266
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001267 // Annotations override defaults.
1268 updateSummaryFromAnnotations(*Summ, MD);
1269
Ted Kremenek2f226732009-05-04 05:31:22 +00001270 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001271 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001272 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001273}
1274
Ted Kremeneka7722b72008-05-06 21:26:51 +00001275RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001276RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001277 const ObjCInterfaceDecl *ID,
1278 const ObjCMethodDecl *MD,
1279 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001280
Ted Kremenek578498a2009-04-29 00:42:39 +00001281 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001282 ObjCMethodSummariesTy::iterator I =
1283 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001284
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001285 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001286 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001287
1288 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001289
1290 // Annotations override defaults.
1291 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001292
Ted Kremenek2f226732009-05-04 05:31:22 +00001293 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001294 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001295 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001296}
1297
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001298void RetainSummaryManager::InitializeClassMethodSummaries() {
1299 assert(ScratchArgs.isEmpty());
1300 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001301
Ted Kremenek272aa852008-06-25 21:21:56 +00001302 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1303 // NSObject and its derivatives.
1304 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1305 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1306 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001307
1308 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001309 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001310 GetNullarySelector("currentHandler", Ctx),
1311 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001312
1313 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001314 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001315 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1316 GetUnarySelector("addObject", Ctx),
1317 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001318 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001319
1320 // Create the summaries for [NSObject performSelector...]. We treat
1321 // these as 'stop tracking' for the arguments because they are often
1322 // used for delegates that can release the object. When we have better
1323 // inter-procedural analysis we can potentially do something better. This
1324 // workaround is to remove false positives.
1325 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1326 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1327 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1328 "afterDelay", NULL);
1329 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1330 "afterDelay", "inModes", NULL);
1331 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1332 "withObject", "waitUntilDone", NULL);
1333 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1334 "withObject", "waitUntilDone", "modes", NULL);
1335 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1336 "withObject", "waitUntilDone", NULL);
1337 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1338 "withObject", "waitUntilDone", "modes", NULL);
1339 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1340 "withObject", NULL);
Ted Kremenekdf100482009-05-14 21:29:16 +00001341
1342 // Specially handle NSData.
1343 RetainSummary *dataWithBytesNoCopySumm =
1344 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1345 DoNothing);
1346 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1347 "dataWithBytesNoCopy", "length", NULL);
1348 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1349 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001350}
1351
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001352void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001353
Ted Kremeneka56ae162009-05-03 05:20:50 +00001354 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001355
Ted Kremeneka7722b72008-05-06 21:26:51 +00001356 // Create the "init" selector. It just acts as a pass-through for the
1357 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001358 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
1359 getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1360 DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001361
1362 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001363 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001364
1365 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001366 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1367
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001368 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001369 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001370
Ted Kremenek266d8b62008-05-06 02:26:56 +00001371 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001372 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001373 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001374 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001375
1376 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001377 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001378 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001379
1380 // Create the "drain" selector.
1381 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001382 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001383
1384 // Create the -dealloc summary.
1385 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1386 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001387
1388 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001389 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001390 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001391
Ted Kremenekaac82832009-02-23 17:45:03 +00001392 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001393 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001394 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001395 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001396
Ted Kremenek45642a42008-08-12 18:48:50 +00001397 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001398 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1399 // self-own themselves. However, they only do this once they are displayed.
1400 // Thus, we need to track an NSWindow's display status.
1401 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001402 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001403 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1404 StopTracking,
1405 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001406
1407 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1408
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001409#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001410 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001411 "styleMask", "backing", "defer", NULL);
1412
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001413 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001414 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001415#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001416
Ted Kremenek45642a42008-08-12 18:48:50 +00001417 // For NSPanel (which subclasses NSWindow), allocated objects are not
1418 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001419 // FIXME: For now we don't track NSPanels. object for the same reason
1420 // as for NSWindow objects.
1421 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1422
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001423#if 0
1424 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001425 "styleMask", "backing", "defer", NULL);
1426
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001427 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001428 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001429#endif
Ted Kremenek272aa852008-06-25 21:21:56 +00001430
Ted Kremenekf2717b02008-07-18 17:24:20 +00001431 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001432 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1433 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001434
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001435 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1436 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001437}
1438
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001439//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001440// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001441//===----------------------------------------------------------------------===//
1442
Ted Kremeneka7338b42008-03-11 06:39:11 +00001443namespace {
1444
Ted Kremenek7d421f32008-04-09 23:49:11 +00001445class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001446public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001447 enum Kind {
1448 Owned = 0, // Owning reference.
1449 NotOwned, // Reference is not owned by still valid (not freed).
1450 Released, // Object has been released.
1451 ReturnedOwned, // Returned object passes ownership to caller.
1452 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001453 ERROR_START,
1454 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1455 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001456 ErrorUseAfterRelease, // Object used after released.
1457 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001458 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001459 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001460 ErrorLeakReturned, // A memory leak due to the returning method not having
1461 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001462 ErrorGCLeakReturned,
1463 ErrorOverAutorelease,
1464 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001465 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001466
1467private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001468 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001469 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001470 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001471 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001472 QualType T;
1473
Ted Kremenek4d99d342009-05-08 20:01:42 +00001474 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1475 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001476
Ted Kremenek68621b92009-01-28 05:56:51 +00001477 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001478 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001479
1480public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001481 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001482
1483 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001484
Ted Kremenek4d99d342009-05-08 20:01:42 +00001485 unsigned getCount() const { return Cnt; }
1486 unsigned getAutoreleaseCount() const { return ACnt; }
1487 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1488 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001489 void setCount(unsigned i) { Cnt = i; }
1490 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001491
Ted Kremenek272aa852008-06-25 21:21:56 +00001492 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001493
1494 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001495
Ted Kremenek6537a642009-03-17 19:42:23 +00001496 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001497
Ted Kremenek6537a642009-03-17 19:42:23 +00001498 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001499
Ted Kremenekffefc352008-04-11 22:25:11 +00001500 bool isOwned() const {
1501 return getKind() == Owned;
1502 }
1503
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001504 bool isNotOwned() const {
1505 return getKind() == NotOwned;
1506 }
1507
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001508 bool isReturnedOwned() const {
1509 return getKind() == ReturnedOwned;
1510 }
1511
1512 bool isReturnedNotOwned() const {
1513 return getKind() == ReturnedNotOwned;
1514 }
1515
1516 bool isNonLeakError() const {
1517 Kind k = getKind();
1518 return isError(k) && !isLeak(k);
1519 }
1520
Ted Kremenek68621b92009-01-28 05:56:51 +00001521 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1522 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001523 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001524 }
1525
Ted Kremenek68621b92009-01-28 05:56:51 +00001526 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1527 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001528 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001529 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001530
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001531 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001532
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001533 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001534 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001535 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001536
Ted Kremenek272aa852008-06-25 21:21:56 +00001537 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001538 return RefVal(getKind(), getObjKind(), getCount() - i,
1539 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001540 }
1541
1542 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001543 return RefVal(getKind(), getObjKind(), getCount() + i,
1544 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001545 }
1546
1547 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001548 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1549 getType());
1550 }
1551
1552 RefVal autorelease() const {
1553 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1554 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001555 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001556
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001557 void Profile(llvm::FoldingSetNodeID& ID) const {
1558 ID.AddInteger((unsigned) kind);
1559 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001560 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001561 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001562 }
1563
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001564 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001565};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001566
1567void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001568 if (!T.isNull())
1569 Out << "Tracked Type:" << T.getAsString() << '\n';
1570
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001571 switch (getKind()) {
1572 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001573 case Owned: {
1574 Out << "Owned";
1575 unsigned cnt = getCount();
1576 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001577 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001578 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001579
Ted Kremenekc4f81022008-04-10 23:09:18 +00001580 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001581 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001582 unsigned cnt = getCount();
1583 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001584 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001585 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001586
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001587 case ReturnedOwned: {
1588 Out << "ReturnedOwned";
1589 unsigned cnt = getCount();
1590 if (cnt) Out << " (+ " << cnt << ")";
1591 break;
1592 }
1593
1594 case ReturnedNotOwned: {
1595 Out << "ReturnedNotOwned";
1596 unsigned cnt = getCount();
1597 if (cnt) Out << " (+ " << cnt << ")";
1598 break;
1599 }
1600
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001601 case Released:
1602 Out << "Released";
1603 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001604
1605 case ErrorDeallocGC:
1606 Out << "-dealloc (GC)";
1607 break;
1608
1609 case ErrorDeallocNotOwned:
1610 Out << "-dealloc (not-owned)";
1611 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001612
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001613 case ErrorLeak:
1614 Out << "Leaked";
1615 break;
1616
Ted Kremenek311f3d42008-10-22 23:56:21 +00001617 case ErrorLeakReturned:
1618 Out << "Leaked (Bad naming)";
1619 break;
1620
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001621 case ErrorGCLeakReturned:
1622 Out << "Leaked (GC-ed at return)";
1623 break;
1624
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001625 case ErrorUseAfterRelease:
1626 Out << "Use-After-Release [ERROR]";
1627 break;
1628
1629 case ErrorReleaseNotOwned:
1630 Out << "Release of Not-Owned [ERROR]";
1631 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001632
1633 case RefVal::ErrorOverAutorelease:
1634 Out << "Over autoreleased";
1635 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001636
1637 case RefVal::ErrorReturnedNotOwned:
1638 Out << "Non-owned object returned instead of owned";
1639 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001640 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001641
1642 if (ACnt) {
1643 Out << " [ARC +" << ACnt << ']';
1644 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001645}
Ted Kremenek0d721572008-03-11 17:48:22 +00001646
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001647} // end anonymous namespace
1648
1649//===----------------------------------------------------------------------===//
1650// RefBindings - State used to track object reference counts.
1651//===----------------------------------------------------------------------===//
1652
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001653typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001654static int RefBIndex = 0;
1655
1656namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001657 template<>
1658 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1659 static inline void* GDMIndex() { return &RefBIndex; }
1660 };
1661}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001662
1663//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001664// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001665//===----------------------------------------------------------------------===//
1666
Ted Kremenekb6578942009-02-24 19:15:11 +00001667typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1668typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1669typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001670
Ted Kremenekb6578942009-02-24 19:15:11 +00001671static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001672static int AutoRBIndex = 0;
1673
Ted Kremenekb6578942009-02-24 19:15:11 +00001674namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001675namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001676
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001677namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001678template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001679 : public GRStatePartialTrait<ARStack> {
1680 static inline void* GDMIndex() { return &AutoRBIndex; }
1681};
1682
1683template<> struct GRStateTrait<AutoreleasePoolContents>
1684 : public GRStatePartialTrait<ARPoolContents> {
1685 static inline void* GDMIndex() { return &AutoRCIndex; }
1686};
1687} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001688
Ted Kremenek681fb352009-03-20 17:34:15 +00001689static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1690 ARStack stack = state->get<AutoreleaseStack>();
1691 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1692}
1693
1694static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1695 SymbolRef sym) {
1696
1697 SymbolRef pool = GetCurrentAutoreleasePool(state);
1698 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1699 ARCounts newCnts(0);
1700
1701 if (cnts) {
1702 const unsigned *cnt = (*cnts).lookup(sym);
1703 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1704 }
1705 else
1706 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1707
1708 return state.set<AutoreleasePoolContents>(pool, newCnts);
1709}
1710
Ted Kremenek7aef4842008-04-16 20:40:59 +00001711//===----------------------------------------------------------------------===//
1712// Transfer functions.
1713//===----------------------------------------------------------------------===//
1714
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001715namespace {
1716
Ted Kremenek7d421f32008-04-09 23:49:11 +00001717class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001718public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001719 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001720 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001721 virtual void Print(std::ostream& Out, const GRState* state,
1722 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001723 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001724
1725private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001726 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1727 SummaryLogTy;
1728
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001729 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001730 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001731 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001732 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001733
Ted Kremenek708af042009-02-05 06:50:21 +00001734 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001735 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001736 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001737 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001738 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001739 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001740
Ted Kremenekb6578942009-02-24 19:15:11 +00001741 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1742 RefVal::Kind& hasErr);
1743
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001744 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1745 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001746 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001747 ExplodedNode<GRState>* Pred,
1748 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001749 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001750
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001751 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1752 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1753
1754 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1755 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1756 GenericNodeBuilder &Builder,
1757 GRExprEngine &Eng,
1758 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001759
Ted Kremenekb6578942009-02-24 19:15:11 +00001760public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001761 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001762 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001763 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1764 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001765 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1766 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001767
Ted Kremenek708af042009-02-05 06:50:21 +00001768 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001769
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001770 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001771
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001772 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1773 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001774 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001775
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001776 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001777 const LangOptions& getLangOptions() const { return LOpts; }
1778
Ted Kremenekc26c4692009-02-18 03:48:14 +00001779 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1780 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1781 return I == SummaryLog.end() ? 0 : I->second;
1782 }
1783
Ted Kremeneka7338b42008-03-11 06:39:11 +00001784 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001785
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001786 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001787 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001788 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001789 Expr* Ex,
1790 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001791 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001792 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001793 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001794
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001795 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001796 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001797 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001798 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001799 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001800
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001801
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001802 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001803 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001804 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001805 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001806 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001807
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001808 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001809 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001810 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001811 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001812 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001813
Ted Kremeneka42be302009-02-14 01:43:44 +00001814 // Stores.
1815 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1816
Ted Kremenekffefc352008-04-11 22:25:11 +00001817 // End-of-path.
1818
1819 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001820 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001821
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001822 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001823 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001824 GRStmtNodeBuilder<GRState>& Builder,
1825 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001826 Stmt* S, const GRState* state,
1827 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001828
1829 std::pair<ExplodedNode<GRState>*, GRStateRef>
1830 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001831 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1832 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001833 // Return statements.
1834
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001835 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001836 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001837 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001838 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001839 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001840
1841 // Assumptions.
1842
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001843 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001844 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001845 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001846};
1847
1848} // end anonymous namespace
1849
Ted Kremenek681fb352009-03-20 17:34:15 +00001850static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1851 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001852 if (Sym)
1853 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001854 else
1855 Out << "<pool>";
1856 Out << ":{";
1857
1858 // Get the contents of the pool.
1859 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1860 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1861 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1862
1863 Out << '}';
1864}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001865
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001866void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1867 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001868
1869
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001870
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001871 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001872
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001873 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001874 Out << sep << nl;
1875
1876 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1877 Out << (*I).first << " : ";
1878 (*I).second.print(Out);
1879 Out << nl;
1880 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001881
1882 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001883 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001884 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001885
Ted Kremenek681fb352009-03-20 17:34:15 +00001886 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1887 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1888 PrintPool(Out, *I, state);
1889
1890 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001891}
1892
Ted Kremenek47a72422009-04-29 18:50:19 +00001893//===----------------------------------------------------------------------===//
1894// Error reporting.
1895//===----------------------------------------------------------------------===//
1896
1897namespace {
1898
1899 //===-------------===//
1900 // Bug Descriptions. //
1901 //===-------------===//
1902
1903 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1904 protected:
1905 CFRefCount& TF;
1906
1907 CFRefBug(CFRefCount* tf, const char* name)
1908 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1909 public:
1910
1911 CFRefCount& getTF() { return TF; }
1912 const CFRefCount& getTF() const { return TF; }
1913
1914 // FIXME: Eventually remove.
1915 virtual const char* getDescription() const = 0;
1916
1917 virtual bool isLeak() const { return false; }
1918 };
1919
1920 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1921 public:
1922 UseAfterRelease(CFRefCount* tf)
1923 : CFRefBug(tf, "Use-after-release") {}
1924
1925 const char* getDescription() const {
1926 return "Reference-counted object is used after it is released";
1927 }
1928 };
1929
1930 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1931 public:
1932 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1933
1934 const char* getDescription() const {
1935 return "Incorrect decrement of the reference count of an "
1936 "object is not owned at this point by the caller";
1937 }
1938 };
1939
1940 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1941 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001942 DeallocGC(CFRefCount *tf)
1943 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001944
1945 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001946 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001947 }
1948 };
1949
1950 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1951 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001952 DeallocNotOwned(CFRefCount *tf)
1953 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001954
1955 const char *getDescription() const {
1956 return "-dealloc sent to object that may be referenced elsewhere";
1957 }
1958 };
1959
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001960 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1961 public:
1962 OverAutorelease(CFRefCount *tf) :
1963 CFRefBug(tf, "Object sent -autorelease too many times") {}
1964
1965 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001966 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001967 }
1968 };
1969
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001970 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1971 public:
1972 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1973 CFRefBug(tf, "Method should return an owned object") {}
1974
1975 const char *getDescription() const {
1976 return "Object with +0 retain counts returned to caller where a +1 "
1977 "(owning) retain count is expected";
1978 }
1979 };
1980
Ted Kremenek47a72422009-04-29 18:50:19 +00001981 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1982 const bool isReturn;
1983 protected:
1984 Leak(CFRefCount* tf, const char* name, bool isRet)
1985 : CFRefBug(tf, name), isReturn(isRet) {}
1986 public:
1987
1988 const char* getDescription() const { return ""; }
1989
1990 bool isLeak() const { return true; }
1991 };
1992
1993 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1994 public:
1995 LeakAtReturn(CFRefCount* tf, const char* name)
1996 : Leak(tf, name, true) {}
1997 };
1998
1999 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2000 public:
2001 LeakWithinFunction(CFRefCount* tf, const char* name)
2002 : Leak(tf, name, false) {}
2003 };
2004
2005 //===---------===//
2006 // Bug Reports. //
2007 //===---------===//
2008
2009 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2010 protected:
2011 SymbolRef Sym;
2012 const CFRefCount &TF;
2013 public:
2014 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2015 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002016 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2017
2018 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2019 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002020 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002021
2022 virtual ~CFRefReport() {}
2023
2024 CFRefBug& getBugType() {
2025 return (CFRefBug&) RangedBugReport::getBugType();
2026 }
2027 const CFRefBug& getBugType() const {
2028 return (const CFRefBug&) RangedBugReport::getBugType();
2029 }
2030
2031 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2032 const SourceRange*& end) {
2033
2034 if (!getBugType().isLeak())
2035 RangedBugReport::getRanges(BR, beg, end);
2036 else
2037 beg = end = 0;
2038 }
2039
2040 SymbolRef getSymbol() const { return Sym; }
2041
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002042 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002043 const ExplodedNode<GRState>* N);
2044
2045 std::pair<const char**,const char**> getExtraDescriptiveText();
2046
2047 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2048 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002049 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002050 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002051
Ted Kremenek47a72422009-04-29 18:50:19 +00002052 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2053 SourceLocation AllocSite;
2054 const MemRegion* AllocBinding;
2055 public:
2056 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2057 ExplodedNode<GRState> *n, SymbolRef sym,
2058 GRExprEngine& Eng);
2059
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002060 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002061 const ExplodedNode<GRState>* N);
2062
2063 SourceLocation getLocation() const { return AllocSite; }
2064 };
2065} // end anonymous namespace
2066
2067void CFRefCount::RegisterChecks(BugReporter& BR) {
2068 useAfterRelease = new UseAfterRelease(this);
2069 BR.Register(useAfterRelease);
2070
2071 releaseNotOwned = new BadRelease(this);
2072 BR.Register(releaseNotOwned);
2073
2074 deallocGC = new DeallocGC(this);
2075 BR.Register(deallocGC);
2076
2077 deallocNotOwned = new DeallocNotOwned(this);
2078 BR.Register(deallocNotOwned);
2079
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002080 overAutorelease = new OverAutorelease(this);
2081 BR.Register(overAutorelease);
2082
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002083 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2084 BR.Register(returnNotOwnedForOwned);
2085
Ted Kremenek47a72422009-04-29 18:50:19 +00002086 // First register "return" leaks.
2087 const char* name = 0;
2088
2089 if (isGCEnabled())
2090 name = "Leak of returned object when using garbage collection";
2091 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2092 name = "Leak of returned object when not using garbage collection (GC) in "
2093 "dual GC/non-GC code";
2094 else {
2095 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2096 name = "Leak of returned object";
2097 }
2098
2099 leakAtReturn = new LeakAtReturn(this, name);
2100 BR.Register(leakAtReturn);
2101
2102 // Second, register leaks within a function/method.
2103 if (isGCEnabled())
2104 name = "Leak of object when using garbage collection";
2105 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2106 name = "Leak of object when not using garbage collection (GC) in "
2107 "dual GC/non-GC code";
2108 else {
2109 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2110 name = "Leak";
2111 }
2112
2113 leakWithinFunction = new LeakWithinFunction(this, name);
2114 BR.Register(leakWithinFunction);
2115
2116 // Save the reference to the BugReporter.
2117 this->BR = &BR;
2118}
2119
2120static const char* Msgs[] = {
2121 // GC only
2122 "Code is compiled to only use garbage collection",
2123 // No GC.
2124 "Code is compiled to use reference counts",
2125 // Hybrid, with GC.
2126 "Code is compiled to use either garbage collection (GC) or reference counts"
2127 " (non-GC). The bug occurs with GC enabled",
2128 // Hybrid, without GC
2129 "Code is compiled to use either garbage collection (GC) or reference counts"
2130 " (non-GC). The bug occurs in non-GC mode"
2131};
2132
2133std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2134 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2135
2136 switch (TF.getLangOptions().getGCMode()) {
2137 default:
2138 assert(false);
2139
2140 case LangOptions::GCOnly:
2141 assert (TF.isGCEnabled());
2142 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2143
2144 case LangOptions::NonGC:
2145 assert (!TF.isGCEnabled());
2146 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2147
2148 case LangOptions::HybridGC:
2149 if (TF.isGCEnabled())
2150 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2151 else
2152 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2153 }
2154}
2155
2156static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2157 ArgEffect X) {
2158 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2159 I!=E; ++I)
2160 if (*I == X) return true;
2161
2162 return false;
2163}
2164
2165PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2166 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002167 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002168
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002169 if (!isa<PostStmt>(N->getLocation()))
2170 return NULL;
2171
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002172 // Check if the type state has changed.
2173 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002174 GRStateRef PrevSt(PrevN->getState(), StMgr);
2175 GRStateRef CurrSt(N->getState(), StMgr);
2176
2177 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2178 if (!CurrT) return NULL;
2179
2180 const RefVal& CurrV = *CurrT;
2181 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2182
2183 // Create a string buffer to constain all the useful things we want
2184 // to tell the user.
2185 std::string sbuf;
2186 llvm::raw_string_ostream os(sbuf);
2187
2188 // This is the allocation site since the previous node had no bindings
2189 // for this symbol.
2190 if (!PrevT) {
2191 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2192
2193 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2194 // Get the name of the callee (if it is available).
2195 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2196 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2197 os << "Call to function '" << FD->getNameAsString() <<'\'';
2198 else
2199 os << "function call";
2200 }
2201 else {
2202 assert (isa<ObjCMessageExpr>(S));
2203 os << "Method";
2204 }
2205
2206 if (CurrV.getObjKind() == RetEffect::CF) {
2207 os << " returns a Core Foundation object with a ";
2208 }
2209 else {
2210 assert (CurrV.getObjKind() == RetEffect::ObjC);
2211 os << " returns an Objective-C object with a ";
2212 }
2213
2214 if (CurrV.isOwned()) {
2215 os << "+1 retain count (owning reference).";
2216
2217 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2218 assert(CurrV.getObjKind() == RetEffect::CF);
2219 os << " "
2220 "Core Foundation objects are not automatically garbage collected.";
2221 }
2222 }
2223 else {
2224 assert (CurrV.isNotOwned());
2225 os << "+0 retain count (non-owning reference).";
2226 }
2227
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002228 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002229 return new PathDiagnosticEventPiece(Pos, os.str());
2230 }
2231
2232 // Gather up the effects that were performed on the object at this
2233 // program point
2234 llvm::SmallVector<ArgEffect, 2> AEffects;
2235
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002236 if (const RetainSummary *Summ =
2237 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002238 // We only have summaries attached to nodes after evaluating CallExpr and
2239 // ObjCMessageExprs.
2240 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2241
2242 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2243 // Iterate through the parameter expressions and see if the symbol
2244 // was ever passed as an argument.
2245 unsigned i = 0;
2246
2247 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2248 AI!=AE; ++AI, ++i) {
2249
2250 // Retrieve the value of the argument. Is it the symbol
2251 // we are interested in?
2252 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2253 continue;
2254
2255 // We have an argument. Get the effect!
2256 AEffects.push_back(Summ->getArg(i));
2257 }
2258 }
2259 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2260 if (Expr *receiver = ME->getReceiver())
2261 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2262 // The symbol we are tracking is the receiver.
2263 AEffects.push_back(Summ->getReceiverEffect());
2264 }
2265 }
2266 }
2267
2268 do {
2269 // Get the previous type state.
2270 RefVal PrevV = *PrevT;
2271
2272 // Specially handle -dealloc.
2273 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2274 // Determine if the object's reference count was pushed to zero.
2275 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2276 // We may not have transitioned to 'release' if we hit an error.
2277 // This case is handled elsewhere.
2278 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002279 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002280 os << "Object released by directly sending the '-dealloc' message";
2281 break;
2282 }
2283 }
2284
2285 // Specially handle CFMakeCollectable and friends.
2286 if (contains(AEffects, MakeCollectable)) {
2287 // Get the name of the function.
2288 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2289 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2290 const FunctionDecl* FD = X.getAsFunctionDecl();
2291 const std::string& FName = FD->getNameAsString();
2292
2293 if (TF.isGCEnabled()) {
2294 // Determine if the object's reference count was pushed to zero.
2295 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2296
2297 os << "In GC mode a call to '" << FName
2298 << "' decrements an object's retain count and registers the "
2299 "object with the garbage collector. ";
2300
2301 if (CurrV.getKind() == RefVal::Released) {
2302 assert(CurrV.getCount() == 0);
2303 os << "Since it now has a 0 retain count the object can be "
2304 "automatically collected by the garbage collector.";
2305 }
2306 else
2307 os << "An object must have a 0 retain count to be garbage collected. "
2308 "After this call its retain count is +" << CurrV.getCount()
2309 << '.';
2310 }
2311 else
2312 os << "When GC is not enabled a call to '" << FName
2313 << "' has no effect on its argument.";
2314
2315 // Nothing more to say.
2316 break;
2317 }
2318
2319 // Determine if the typestate has changed.
2320 if (!(PrevV == CurrV))
2321 switch (CurrV.getKind()) {
2322 case RefVal::Owned:
2323 case RefVal::NotOwned:
2324
Ted Kremenek4d99d342009-05-08 20:01:42 +00002325 if (PrevV.getCount() == CurrV.getCount()) {
2326 // Did an autorelease message get sent?
2327 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2328 return 0;
2329
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002330 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002331 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002332 break;
2333 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002334
2335 if (PrevV.getCount() > CurrV.getCount())
2336 os << "Reference count decremented.";
2337 else
2338 os << "Reference count incremented.";
2339
2340 if (unsigned Count = CurrV.getCount())
2341 os << " The object now has a +" << Count << " retain count.";
2342
2343 if (PrevV.getKind() == RefVal::Released) {
2344 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2345 os << " The object is not eligible for garbage collection until the "
2346 "retain count reaches 0 again.";
2347 }
2348
2349 break;
2350
2351 case RefVal::Released:
2352 os << "Object released.";
2353 break;
2354
2355 case RefVal::ReturnedOwned:
2356 os << "Object returned to caller as an owning reference (single retain "
2357 "count transferred to caller).";
2358 break;
2359
2360 case RefVal::ReturnedNotOwned:
2361 os << "Object returned to caller with a +0 (non-owning) retain count.";
2362 break;
2363
2364 default:
2365 return NULL;
2366 }
2367
2368 // Emit any remaining diagnostics for the argument effects (if any).
2369 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2370 E=AEffects.end(); I != E; ++I) {
2371
2372 // A bunch of things have alternate behavior under GC.
2373 if (TF.isGCEnabled())
2374 switch (*I) {
2375 default: break;
2376 case Autorelease:
2377 os << "In GC mode an 'autorelease' has no effect.";
2378 continue;
2379 case IncRefMsg:
2380 os << "In GC mode the 'retain' message has no effect.";
2381 continue;
2382 case DecRefMsg:
2383 os << "In GC mode the 'release' message has no effect.";
2384 continue;
2385 }
2386 }
2387 } while(0);
2388
2389 if (os.str().empty())
2390 return 0; // We have nothing to say!
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002391
2392 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002393 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002394 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2395
2396 // Add the range by scanning the children of the statement for any bindings
2397 // to Sym.
2398 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2399 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2400 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2401 P->addRange(Exp->getSourceRange());
2402 break;
2403 }
2404
2405 return P;
2406}
2407
2408namespace {
2409 class VISIBILITY_HIDDEN FindUniqueBinding :
2410 public StoreManager::BindingsHandler {
2411 SymbolRef Sym;
2412 const MemRegion* Binding;
2413 bool First;
2414
2415 public:
2416 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2417
2418 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2419 SVal val) {
2420
2421 SymbolRef SymV = val.getAsSymbol();
2422 if (!SymV || SymV != Sym)
2423 return true;
2424
2425 if (Binding) {
2426 First = false;
2427 return false;
2428 }
2429 else
2430 Binding = R;
2431
2432 return true;
2433 }
2434
2435 operator bool() { return First && Binding; }
2436 const MemRegion* getRegion() { return Binding; }
2437 };
2438}
2439
2440static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2441GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2442 SymbolRef Sym) {
2443
2444 // Find both first node that referred to the tracked symbol and the
2445 // memory location that value was store to.
2446 const ExplodedNode<GRState>* Last = N;
2447 const MemRegion* FirstBinding = 0;
2448
2449 while (N) {
2450 const GRState* St = N->getState();
2451 RefBindings B = St->get<RefBindings>();
2452
2453 if (!B.lookup(Sym))
2454 break;
2455
2456 FindUniqueBinding FB(Sym);
2457 StateMgr.iterBindings(St, FB);
2458 if (FB) FirstBinding = FB.getRegion();
2459
2460 Last = N;
2461 N = N->pred_empty() ? NULL : *(N->pred_begin());
2462 }
2463
2464 return std::make_pair(Last, FirstBinding);
2465}
2466
2467PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002468CFRefReport::getEndPath(BugReporterContext& BRC,
2469 const ExplodedNode<GRState>* EndN) {
2470 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002471 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002472 BRC.addNotableSymbol(Sym);
2473 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002474}
2475
2476PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002477CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2478 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002479
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002480 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002481 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002482 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002483
2484 // We are reporting a leak. Walk up the graph to get to the first node where
2485 // the symbol appeared, and also get the first VarDecl that tracked object
2486 // is stored to.
2487 const ExplodedNode<GRState>* AllocNode = 0;
2488 const MemRegion* FirstBinding = 0;
2489
2490 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002491 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002492
2493 // Get the allocate site.
2494 assert(AllocNode);
2495 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2496
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002497 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002498 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2499
2500 // Compute an actual location for the leak. Sometimes a leak doesn't
2501 // occur at an actual statement (e.g., transition between blocks; end
2502 // of function) so we need to walk the graph and compute a real location.
2503 const ExplodedNode<GRState>* LeakN = EndN;
2504 PathDiagnosticLocation L;
2505
2506 while (LeakN) {
2507 ProgramPoint P = LeakN->getLocation();
2508
2509 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2510 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2511 break;
2512 }
2513 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2514 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2515 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2516 break;
2517 }
2518 }
2519
2520 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2521 }
2522
2523 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002524 const Decl &D = BRC.getCodeDecl();
2525 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002526 }
2527
2528 std::string sbuf;
2529 llvm::raw_string_ostream os(sbuf);
2530
2531 os << "Object allocated on line " << AllocLine;
2532
2533 if (FirstBinding)
2534 os << " and stored into '" << FirstBinding->getString() << '\'';
2535
2536 // Get the retain count.
2537 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2538
2539 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2540 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2541 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2542 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002543 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002544 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002545 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002546 << "') does not contain 'copy' or otherwise starts with"
2547 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002548 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002549 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002550 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2551 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2552 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002553 << "' is potentially leaked when using garbage collection. Callers "
2554 "of this method do not expect a returned object with a +1 retain "
2555 "count since they expect the object to be managed by the garbage "
2556 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002557 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002558 else
2559 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002560 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002561
2562 return new PathDiagnosticEventPiece(L, os.str());
2563}
2564
Ted Kremenek47a72422009-04-29 18:50:19 +00002565CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2566 ExplodedNode<GRState> *n,
2567 SymbolRef sym, GRExprEngine& Eng)
2568: CFRefReport(D, tf, n, sym)
2569{
2570
2571 // Most bug reports are cached at the location where they occured.
2572 // With leaks, we want to unique them by the location where they were
2573 // allocated, and only report a single path. To do this, we need to find
2574 // the allocation site of a piece of tracked memory, which we do via a
2575 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2576 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2577 // that all ancestor nodes that represent the allocation site have the
2578 // same SourceLocation.
2579 const ExplodedNode<GRState>* AllocNode = 0;
2580
2581 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002582 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002583
2584 // Get the SourceLocation for the allocation site.
2585 ProgramPoint P = AllocNode->getLocation();
2586 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2587
2588 // Fill in the description of the bug.
2589 Description.clear();
2590 llvm::raw_string_ostream os(Description);
2591 SourceManager& SMgr = Eng.getContext().getSourceManager();
2592 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002593 os << "Potential leak ";
2594 if (tf.isGCEnabled()) {
2595 os << "(when using garbage collection) ";
2596 }
2597 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002598
2599 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2600 if (AllocBinding)
2601 os << " and stored into '" << AllocBinding->getString() << '\'';
2602}
2603
2604//===----------------------------------------------------------------------===//
2605// Main checker logic.
2606//===----------------------------------------------------------------------===//
2607
Ted Kremenek272aa852008-06-25 21:21:56 +00002608/// GetReturnType - Used to get the return type of a message expression or
2609/// function call with the intention of affixing that type to a tracked symbol.
2610/// While the the return type can be queried directly from RetEx, when
2611/// invoking class methods we augment to the return type to be that of
2612/// a pointer to the class (as opposed it just being id).
2613static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2614
2615 QualType RetTy = RetE->getType();
2616
2617 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002618 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002619 if (!PT)
2620 return RetTy;
2621
2622 // If RetEx is not a message expression just return its type.
2623 // If RetEx is a message expression, return its types if it is something
2624 /// more specific than id.
2625
2626 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2627
Steve Naroff17c03822009-02-12 17:52:19 +00002628 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002629 return RetTy;
2630
2631 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2632
2633 // At this point we know the return type of the message expression is id.
2634 // If we have an ObjCInterceDecl, we know this is a call to a class method
2635 // whose type we can resolve. In such cases, promote the return type to
2636 // Class*.
2637 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2638}
2639
2640
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002641void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002642 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002643 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002644 Expr* Ex,
2645 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002646 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002647 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002648 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002649
Ted Kremeneka7338b42008-03-11 06:39:11 +00002650 // Get the state.
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002651 GRStateManager& StateMgr = Eng.getStateManager();
2652 GRStateRef state(Builder.GetState(Pred), StateMgr);
2653 ASTContext& Ctx = StateMgr.getContext();
2654 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek227c5372008-05-06 02:41:27 +00002655
2656 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002657 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002658 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002659 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002660 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002661
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002662 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002663 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002664 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002665
Ted Kremenek74556a12009-03-26 03:35:11 +00002666 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002667 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002668 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002669 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002670 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002671 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002672 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002673 }
2674 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002675 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002676
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002677 if (isa<Loc>(V)) {
2678 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002679 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002680 continue;
2681
2682 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002683
2684 // FIXME: Either this logic should also be replicated in GRSimpleVals
2685 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002686
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002687 // FIXME: We can have collisions on the conjured symbol if the
2688 // expression *I also creates conjured symbols. We probably want
2689 // to identify conjured symbols by an expression pair: the enclosing
2690 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002691 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002692
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002693 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002694
Ted Kremenek73ec7732009-05-06 18:19:24 +00002695 if (R) {
2696 // Are we dealing with an ElementRegion? If the element type is
2697 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xuea6851b2009-05-11 14:28:14 +00002698 // is a variable region then strip off the ElementRegion.
Ted Kremenek73ec7732009-05-06 18:19:24 +00002699 // FIXME: We really need to think about this for the general case
2700 // as sometimes we are reasoning about arrays and other times
2701 // about (char*), etc., is just a form of passing raw bytes.
2702 // e.g., void *p = alloca(); foo((char*)p);
2703 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2704 // Checking for 'integral type' is probably too promiscuous, but
2705 // we'll leave it in for now until we have a systematic way of
2706 // handling all of these cases. Eventually we need to come up
2707 // with an interface to StoreManager so that this logic can be
2708 // approriately delegated to the respective StoreManagers while
2709 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002710 // invalidating reference counts), probably via callbacks.
Ted Kremenek1cba5772009-05-11 22:55:17 +00002711 if (ER->getElementType()->isIntegralType()) {
2712 const MemRegion *superReg = ER->getSuperRegion();
2713 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2714 isa<ObjCIvarRegion>(superReg))
2715 R = cast<TypedRegion>(superReg);
2716 }
2717
Ted Kremenek73ec7732009-05-06 18:19:24 +00002718 // FIXME: What about layers of ElementRegions?
2719 }
2720
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002721 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002722 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002723
Ted Kremenek53b24182009-03-04 22:56:43 +00002724 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002725 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002726
Ted Kremenek53b24182009-03-04 22:56:43 +00002727 if (R->isBoundable(Ctx)) {
2728 // Set the value of the variable to be a conjured symbol.
2729 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002730 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002731
Zhongxing Xu079dc352009-04-09 06:03:54 +00002732 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002733 ValueManager &ValMgr = Eng.getValueManager();
2734 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002735 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002736 }
2737 else if (const RecordType *RT = T->getAsStructureType()) {
2738 // Handle structs in a not so awesome way. Here we just
2739 // eagerly bind new symbols to the fields. In reality we
2740 // should have the store manager handle this. The idea is just
2741 // to prototype some basic functionality here. All of this logic
2742 // should one day soon just go away.
2743 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2744
2745 // No record definition. There is nothing we can do.
2746 if (!RD)
2747 continue;
2748
2749 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2750
2751 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002752 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2753 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002754
2755 // For now just handle scalar fields.
2756 FieldDecl *FD = *FI;
2757 QualType FT = FD->getType();
2758
2759 if (Loc::IsLocType(FT) ||
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002760 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002761 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002762
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002763 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002764 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002765 }
2766 }
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002767 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2768 // Set the default value of the array to conjured symbol.
2769 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2770 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2771 Count);
2772 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2773 StateMgr);
2774 } else {
Ted Kremenek53b24182009-03-04 22:56:43 +00002775 // Just blast away other values.
2776 state = state.BindLoc(*MR, UnknownVal());
2777 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002778 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002779 }
2780 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002781 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002782 }
2783 else {
2784 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002785 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002786 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002787 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002788 else if (isa<nonloc::LocAsInteger>(V))
2789 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002790 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002791
Ted Kremenek272aa852008-06-25 21:21:56 +00002792 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002793 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002794 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002795 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002796 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002797 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002798 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002799 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002800 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002801 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002802 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002803 }
2804 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002805
Ted Kremenek272aa852008-06-25 21:21:56 +00002806 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002807 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002808 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002809 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002810 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002811 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002812
Ted Kremenekf2717b02008-07-18 17:24:20 +00002813 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002814 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002815
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002816 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2817 assert(Receiver);
2818 SVal V = state.GetSValAsScalarOrLoc(Receiver);
2819 bool found = false;
2820 if (SymbolRef Sym = V.getAsLocSymbol())
2821 if (state.get<RefBindings>(Sym)) {
2822 found = true;
2823 RE = Summaries.getObjAllocRetEffect();
2824 }
2825
2826 if (!found)
2827 RE = RetEffect::MakeNoRet();
2828 }
2829
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002830 switch (RE.getKind()) {
2831 default:
2832 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002833
Ted Kremenek8f90e712008-10-17 22:23:12 +00002834 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002835
Ted Kremenek455dd862008-04-11 20:23:24 +00002836 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002837 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2838 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002839
Ted Kremenek8f90e712008-10-17 22:23:12 +00002840 // FIXME: We eventually should handle structs and other compound types
2841 // that are returned by value.
2842
2843 QualType T = Ex->getType();
2844
Ted Kremenek79413a52008-11-13 06:10:40 +00002845 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002846 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002847 ValueManager &ValMgr = Eng.getValueManager();
2848 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002849 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002850 }
2851
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002852 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002853 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002854
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002855 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002856 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002857 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002858 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002859 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002860 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002861 break;
2862 }
2863
Ted Kremenek227c5372008-05-06 02:41:27 +00002864 case RetEffect::ReceiverAlias: {
2865 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002866 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002867 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002868 break;
2869 }
2870
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002871 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002872 case RetEffect::OwnedSymbol: {
2873 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002874 ValueManager &ValMgr = Eng.getValueManager();
2875 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2876 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2877 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2878 RetT));
2879 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002880
2881 // FIXME: Add a flag to the checker where allocations are assumed to
2882 // *not fail.
2883#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002884 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2885 bool isFeasible;
2886 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2887 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2888 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002889#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002890
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002891 break;
2892 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002893
2894 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002895 case RetEffect::NotOwnedSymbol: {
2896 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002897 ValueManager &ValMgr = Eng.getValueManager();
2898 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2899 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2900 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2901 RetT));
2902 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002903 break;
2904 }
2905 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002906
Ted Kremenek0dd65012009-02-18 02:00:25 +00002907 // Generate a sink node if we are at the end of a path.
2908 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002909 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2910 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002911
2912 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002913 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002914}
2915
2916
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002917void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002918 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002919 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002920 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002921 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002922 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002923 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002924 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002925
Ted Kremenek286e9852009-05-04 04:57:00 +00002926 assert(Summ);
2927 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002928 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002929}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002930
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002931void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002932 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002933 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002934 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002935 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002936 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002937
Ted Kremenek272aa852008-06-25 21:21:56 +00002938 if (Expr* Receiver = ME->getReceiver()) {
2939 // We need the type-information of the tracked receiver object
2940 // Retrieve it from the state.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002941 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek272aa852008-06-25 21:21:56 +00002942
2943 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2944 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002945 // FIXME: Is this really working as expected? There are cases where
2946 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002947 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002948 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002949
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002950 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002951 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002952 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002953 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002954
2955 if (const PointerType* PT = Ty->getAsPointerType()) {
2956 QualType PointeeTy = PT->getPointeeType();
2957
2958 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2959 ID = IT->getDecl();
2960 }
2961 }
2962 }
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002963
2964 // FIXME: this is a hack. This may or may not be the actual method
2965 // that is called.
2966 if (!ID) {
2967 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
2968 if (const ObjCInterfaceType *p =
2969 PT->getPointeeType()->getAsObjCInterfaceType())
2970 ID = p->getDecl();
2971 }
2972
Ted Kremenek04e00302009-04-29 17:09:14 +00002973 // FIXME: The receiver could be a reference to a class, meaning that
2974 // we should use the class method.
2975 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002976
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002977 // Special-case: are we sending a mesage to "self"?
2978 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002979 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2980 if (Expr* Receiver = ME->getReceiver()) {
2981 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2982 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2983 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2984 // Update the summary to make the default argument effect
2985 // 'StopTracking'.
2986 Summ = Summaries.copySummary(Summ);
2987 Summ->setDefaultArgEffect(StopTracking);
2988 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002989 }
2990 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002991 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002992 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002993 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002994
Ted Kremenek286e9852009-05-04 04:57:00 +00002995 if (!Summ)
2996 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002997
Ted Kremenek286e9852009-05-04 04:57:00 +00002998 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002999 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00003000}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003001
3002namespace {
3003class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
3004 GRStateRef state;
3005public:
3006 StopTrackingCallback(GRStateRef st) : state(st) {}
3007 GRStateRef getState() { return state; }
3008
3009 bool VisitSymbol(SymbolRef sym) {
3010 state = state.remove<RefBindings>(sym);
3011 return true;
3012 }
Ted Kremenek926abf22008-05-06 04:20:12 +00003013
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003014 const GRState* getState() const { return state.getState(); }
3015};
3016} // end anonymous namespace
3017
3018
Ted Kremeneka42be302009-02-14 01:43:44 +00003019void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00003020 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00003021 bool escapes = false;
3022
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003023 // A value escapes in three possible cases (this may change):
3024 //
3025 // (1) we are binding to something that is not a memory region.
3026 // (2) we are binding to a memregion that does not have stack storage
3027 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003028 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00003029 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003030
Ted Kremeneka42be302009-02-14 01:43:44 +00003031 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003032 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003033 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003034 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3035 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003036
3037 if (!escapes) {
3038 // To test (3), generate a new state with the binding removed. If it is
3039 // the same state, then it escapes (since the store cannot represent
3040 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00003041 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003042 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003043 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003044
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003045 // If our store can represent the binding and we aren't storing to something
3046 // that doesn't have local storage then just return and have the simulation
3047 // state continue as is.
3048 if (!escapes)
3049 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003050
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003051 // Otherwise, find all symbols referenced by 'val' that we are tracking
3052 // and stop tracking them.
3053 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003054}
3055
Ted Kremenek541db372008-04-24 23:57:27 +00003056
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003057 // Return statements.
3058
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003059void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003060 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003061 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003062 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003063 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003064
3065 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003066 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003067 return;
3068
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003069 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00003070 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003071
Ted Kremenek74556a12009-03-26 03:35:11 +00003072 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003073 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003074
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003075 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003076 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003077
3078 if (!T)
3079 return;
3080
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003081 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003082 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003083
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003084 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003085 case RefVal::Owned: {
3086 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003087 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003088 X.setCount(cnt - 1);
3089 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003090 break;
3091 }
3092
3093 case RefVal::NotOwned: {
3094 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003095 if (cnt) {
3096 X.setCount(cnt - 1);
3097 X = X ^ RefVal::ReturnedOwned;
3098 }
3099 else {
3100 X = X ^ RefVal::ReturnedNotOwned;
3101 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003102 break;
3103 }
3104
3105 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003106 return;
3107 }
3108
3109 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003110 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003111 Pred = Builder.MakeNode(Dst, S, Pred, state);
3112
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003113 // Did we cache out?
3114 if (!Pred)
3115 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003116
3117 // Update the autorelease counts.
3118 static unsigned autoreleasetag = 0;
3119 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3120 bool stop = false;
3121 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3122 X, stop);
3123
3124 // Did we cache out?
3125 if (!Pred || stop)
3126 return;
3127
3128 // Get the updated binding.
3129 T = state.get<RefBindings>(Sym);
3130 assert(T);
3131 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003132
Ted Kremenek47a72422009-04-29 18:50:19 +00003133 // Any leaks or other errors?
3134 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003135 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003136 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003137 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003138 RetEffect RE = Summ.getRetEffect();
3139 bool hasError = false;
3140
3141 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3142 // Things are more complicated with garbage collection. If the
3143 // returned object is suppose to be an Objective-C object, we have
Ted Kremenekeaea6582009-05-10 16:52:15 +00003144 // a leak (as the caller expects a GC'ed object) because no
3145 // method should return ownership unless it returns a CF object.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003146 X = X ^ RefVal::ErrorGCLeakReturned;
3147
3148 // Keep this false until this is properly tested.
Ted Kremenekeaea6582009-05-10 16:52:15 +00003149 hasError = true;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003150 }
3151 else if (!RE.isOwned()) {
3152 // Either we are using GC and the returned object is a CF type
3153 // or we aren't using GC. In either case, we expect that the
3154 // enclosing method is expected to return ownership.
3155 hasError = true;
3156 X = X ^ RefVal::ErrorLeakReturned;
3157 }
3158
3159 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003160 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003161 static int ReturnOwnLeakTag = 0;
3162 state = state.set<RefBindings>(Sym, X);
3163 ExplodedNode<GRState> *N =
3164 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3165 if (N) {
3166 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003167 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3168 N, Sym, Eng);
3169 BR->EmitReport(report);
3170 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003171 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003172 }
3173 }
3174 else if (X.isReturnedNotOwned()) {
3175 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3176 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3177 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3178 if (Summ.getRetEffect().isOwned()) {
3179 // Trying to return a not owned object to a caller expecting an
3180 // owned object.
3181
3182 static int ReturnNotOwnedForOwnedTag = 0;
3183 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3184 if (ExplodedNode<GRState> *N =
3185 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3186 state, Pred)) {
3187 CFRefReport *report =
3188 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3189 *this, N, Sym);
3190 BR->EmitReport(report);
3191 }
3192 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003193 }
3194 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003195}
3196
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003197// Assumptions.
3198
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003199const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3200 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003201 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003202 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003203
3204 // FIXME: We may add to the interface of EvalAssume the list of symbols
3205 // whose assumptions have changed. For now we just iterate through the
3206 // bindings and check if any of the tracked symbols are NULL. This isn't
3207 // too bad since the number of symbols we will track in practice are
3208 // probably small and EvalAssume is only called at branches and a few
3209 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003210 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003211
3212 if (B.isEmpty())
3213 return St;
3214
3215 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003216
3217 GRStateRef state(St, VMgr);
3218 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003219
3220 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003221 // Check if the symbol is null (or equal to any constant).
3222 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003223 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003224 changed = true;
3225 B = RefBFactory.Remove(B, I.getKey());
3226 }
3227 }
3228
Ted Kremenek91781202008-08-17 03:20:02 +00003229 if (changed)
3230 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003231
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003232 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003233}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003234
Ted Kremenekb6578942009-02-24 19:15:11 +00003235GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3236 RefVal V, ArgEffect E,
3237 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003238
3239 // In GC mode [... release] and [... retain] do nothing.
3240 switch (E) {
3241 default: break;
3242 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3243 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003244 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003245 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3246 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003247 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003248
Ted Kremenek6537a642009-03-17 19:42:23 +00003249 // Handle all use-after-releases.
3250 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3251 V = V ^ RefVal::ErrorUseAfterRelease;
3252 hasErr = V.getKind();
3253 return state.set<RefBindings>(sym, V);
3254 }
3255
Ted Kremenek0d721572008-03-11 17:48:22 +00003256 switch (E) {
3257 default:
3258 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003259
3260 case Dealloc:
3261 // Any use of -dealloc in GC is *bad*.
3262 if (isGCEnabled()) {
3263 V = V ^ RefVal::ErrorDeallocGC;
3264 hasErr = V.getKind();
3265 break;
3266 }
3267
3268 switch (V.getKind()) {
3269 default:
3270 assert(false && "Invalid case.");
3271 case RefVal::Owned:
3272 // The object immediately transitions to the released state.
3273 V = V ^ RefVal::Released;
3274 V.clearCounts();
3275 return state.set<RefBindings>(sym, V);
3276 case RefVal::NotOwned:
3277 V = V ^ RefVal::ErrorDeallocNotOwned;
3278 hasErr = V.getKind();
3279 break;
3280 }
3281 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003282
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003283 case NewAutoreleasePool:
3284 assert(!isGCEnabled());
3285 return state.add<AutoreleaseStack>(sym);
3286
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003287 case MayEscape:
3288 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003289 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003290 break;
3291 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003292
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003293 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003294
Ted Kremenekede40b72008-07-09 18:11:16 +00003295 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003296 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003297 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003298
Ted Kremenek9b112d22009-01-28 21:44:40 +00003299 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003300 if (isGCEnabled())
3301 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003302
3303 // Update the autorelease counts.
3304 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003305 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003306 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003307
Ted Kremenek227c5372008-05-06 02:41:27 +00003308 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003309 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003310
Ted Kremenek0d721572008-03-11 17:48:22 +00003311 case IncRef:
3312 switch (V.getKind()) {
3313 default:
3314 assert(false);
3315
3316 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003317 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003318 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003319 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003320 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003321 // Non-GC cases are handled above.
3322 assert(isGCEnabled());
3323 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003324 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003325 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003326 break;
3327
Ted Kremenek272aa852008-06-25 21:21:56 +00003328 case SelfOwn:
3329 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003330 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003331 case DecRef:
3332 switch (V.getKind()) {
3333 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003334 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003335 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003336
Ted Kremenek272aa852008-06-25 21:21:56 +00003337 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003338 assert(V.getCount() > 0);
3339 if (V.getCount() == 1) V = V ^ RefVal::Released;
3340 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003341 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003342
Ted Kremenek272aa852008-06-25 21:21:56 +00003343 case RefVal::NotOwned:
3344 if (V.getCount() > 0)
3345 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003346 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003347 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003348 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003349 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003350 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003351
Ted Kremenek0d721572008-03-11 17:48:22 +00003352 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003353 // Non-GC cases are handled above.
3354 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003355 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003356 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003357 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003358 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003359 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003360 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003361 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003362}
3363
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003364//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003365// Handle dead symbols and end-of-path.
3366//===----------------------------------------------------------------------===//
3367
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003368std::pair<ExplodedNode<GRState>*, GRStateRef>
3369CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3370 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003371 GRExprEngine &Eng,
3372 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003373
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003374 unsigned ACnt = V.getAutoreleaseCount();
3375 stop = false;
3376
3377 // No autorelease counts? Nothing to be done.
3378 if (!ACnt)
3379 return std::make_pair(Pred, state);
3380
3381 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3382 unsigned Cnt = V.getCount();
3383
Ted Kremenek0603cf52009-05-11 15:26:06 +00003384 // FIXME: Handle sending 'autorelease' to already released object.
3385
3386 if (V.getKind() == RefVal::ReturnedOwned)
3387 ++Cnt;
3388
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003389 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003390 if (ACnt == Cnt) {
3391 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003392 if (V.getKind() == RefVal::ReturnedOwned)
3393 V = V ^ RefVal::ReturnedNotOwned;
3394 else
3395 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003396 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003397 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003398 V.setCount(Cnt - ACnt);
3399 V.setAutoreleaseCount(0);
3400 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003401 state = state.set<RefBindings>(Sym, V);
3402 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3403 stop = (N == 0);
3404 return std::make_pair(N, state);
3405 }
3406
3407 // Woah! More autorelease counts then retain counts left.
3408 // Emit hard error.
3409 stop = true;
3410 V = V ^ RefVal::ErrorOverAutorelease;
3411 state = state.set<RefBindings>(Sym, V);
3412
3413 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003414 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003415
3416 std::string sbuf;
3417 llvm::raw_string_ostream os(sbuf);
3418 os << "Object over-autoreleased: object was sent -autorelease " ;
3419 if (V.getAutoreleaseCount() > 1)
3420 os << V.getAutoreleaseCount() << " times";
3421 os << " but the object has ";
3422 if (V.getCount() == 0)
3423 os << "zero (locally visible)";
3424 else
3425 os << "+" << V.getCount();
3426 os << " retain counts";
3427
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003428 CFRefReport *report =
3429 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003430 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003431 BR->EmitReport(report);
3432 }
3433
3434 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003435}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003436
3437GRStateRef
3438CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3439 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3440
3441 bool hasLeak = V.isOwned() ||
3442 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3443
3444 if (!hasLeak)
3445 return state.remove<RefBindings>(sid);
3446
3447 Leaked.push_back(sid);
3448 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3449}
3450
3451ExplodedNode<GRState>*
3452CFRefCount::ProcessLeaks(GRStateRef state,
3453 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3454 GenericNodeBuilder &Builder,
3455 GRExprEngine& Eng,
3456 ExplodedNode<GRState> *Pred) {
3457
3458 if (Leaked.empty())
3459 return Pred;
3460
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003461 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003462 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003463
3464 if (N) {
3465 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3466 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3467
3468 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3469 : leakAtReturn);
3470 assert(BT && "BugType not initialized.");
3471 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3472 BR->EmitReport(report);
3473 }
3474 }
3475
3476 return N;
3477}
3478
Ted Kremenek708af042009-02-05 06:50:21 +00003479void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3480 GREndPathNodeBuilder<GRState>& Builder) {
3481
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003482 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003483 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003484 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003485 ExplodedNode<GRState> *Pred = 0;
3486
3487 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003488 bool stop = false;
3489 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3490 (*I).first,
3491 (*I).second, stop);
3492
3493 if (stop)
3494 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003495 }
3496
3497 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003498 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003499
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003500 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3501 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3502
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003503 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003504}
3505
3506void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3507 GRExprEngine& Eng,
3508 GRStmtNodeBuilder<GRState>& Builder,
3509 ExplodedNode<GRState>* Pred,
3510 Stmt* S,
3511 const GRState* St,
3512 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003513
3514 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003515 RefBindings B = state.get<RefBindings>();
3516
3517 // Update counts from autorelease pools
3518 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3519 E = SymReaper.dead_end(); I != E; ++I) {
3520 SymbolRef Sym = *I;
3521 if (const RefVal* T = B.lookup(Sym)){
3522 // Use the symbol as the tag.
3523 // FIXME: This might not be as unique as we would like.
3524 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003525 bool stop = false;
3526 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3527 Sym, *T, stop);
3528 if (stop)
3529 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003530 }
3531 }
3532
3533 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003534 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003535
3536 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003537 E = SymReaper.dead_end(); I != E; ++I) {
3538 if (const RefVal* T = B.lookup(*I))
3539 state = HandleSymbolDeath(state, *I, *T, Leaked);
3540 }
Ted Kremenek708af042009-02-05 06:50:21 +00003541
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003542 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003543 {
3544 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3545 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3546 }
Ted Kremenek708af042009-02-05 06:50:21 +00003547
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003548 // Did we cache out?
3549 if (!Pred)
3550 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003551
3552 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003553 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003554
Ted Kremenek876d8df2009-02-19 23:47:02 +00003555 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003556 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3557
Ted Kremenek876d8df2009-02-19 23:47:02 +00003558 state = state.set<RefBindings>(B);
3559 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003560}
3561
3562void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3563 GRStmtNodeBuilder<GRState>& Builder,
3564 Expr* NodeExpr, Expr* ErrorExpr,
3565 ExplodedNode<GRState>* Pred,
3566 const GRState* St,
3567 RefVal::Kind hasErr, SymbolRef Sym) {
3568 Builder.BuildSinks = true;
3569 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3570
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003571 if (!N)
3572 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003573
3574 CFRefBug *BT = 0;
3575
Ted Kremenek6537a642009-03-17 19:42:23 +00003576 switch (hasErr) {
3577 default:
3578 assert(false && "Unhandled error.");
3579 return;
3580 case RefVal::ErrorUseAfterRelease:
3581 BT = static_cast<CFRefBug*>(useAfterRelease);
3582 break;
3583 case RefVal::ErrorReleaseNotOwned:
3584 BT = static_cast<CFRefBug*>(releaseNotOwned);
3585 break;
3586 case RefVal::ErrorDeallocGC:
3587 BT = static_cast<CFRefBug*>(deallocGC);
3588 break;
3589 case RefVal::ErrorDeallocNotOwned:
3590 BT = static_cast<CFRefBug*>(deallocNotOwned);
3591 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003592 }
3593
Ted Kremenekc26c4692009-02-18 03:48:14 +00003594 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003595 report->addRange(ErrorExpr->getSourceRange());
3596 BR->EmitReport(report);
3597}
3598
3599//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003600// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003601//===----------------------------------------------------------------------===//
3602
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003603GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3604 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003605 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003606}