blob: fc6de6003219c5863f8f19cdc3db6b6d660ac975 [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) {}
442
443 ObjCSummaryKey(Selector s)
444 : II(0), S(s) {}
445
446 IdentifierInfo* getIdentifier() const { return II; }
447 Selector getSelector() const { return S; }
448};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000449}
450
451namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000452template <> struct DenseMapInfo<ObjCSummaryKey> {
453 static inline ObjCSummaryKey getEmptyKey() {
454 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
455 DenseMapInfo<Selector>::getEmptyKey());
456 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000457
Ted Kremenek272aa852008-06-25 21:21:56 +0000458 static inline ObjCSummaryKey getTombstoneKey() {
459 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
460 DenseMapInfo<Selector>::getTombstoneKey());
461 }
462
463 static unsigned getHashValue(const ObjCSummaryKey &V) {
464 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
465 & 0x88888888)
466 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
467 & 0x55555555);
468 }
469
470 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
471 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
472 RHS.getIdentifier()) &&
473 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
474 RHS.getSelector());
475 }
476
477 static bool isPod() {
478 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
479 DenseMapInfo<Selector>::isPod();
480 }
481};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000482} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000483
Ted Kremenek84f010c2008-06-23 23:30:29 +0000484namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000485class VISIBILITY_HIDDEN ObjCSummaryCache {
486 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
487 MapTy M;
488public:
489 ObjCSummaryCache() {}
490
491 typedef MapTy::iterator iterator;
492
Ted Kremenek314b1952009-04-29 23:03:22 +0000493 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
494 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000495 // Lookup the method using the decl for the class @interface. If we
496 // have no decl, lookup using the class name.
497 return D ? find(D, S) : find(ClsName, S);
498 }
499
Ted Kremenek314b1952009-04-29 23:03:22 +0000500 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000501 // Do a lookup with the (D,S) pair. If we find a match return
502 // the iterator.
503 ObjCSummaryKey K(D, S);
504 MapTy::iterator I = M.find(K);
505
506 if (I != M.end() || !D)
507 return I;
508
509 // Walk the super chain. If we find a hit with a parent, we'll end
510 // up returning that summary. We actually allow that key (null,S), as
511 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
512 // generate initial summaries without having to worry about NSObject
513 // being declared.
514 // FIXME: We may change this at some point.
515 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
516 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
517 break;
518
519 if (!C)
520 return I;
521 }
522
523 // Cache the summary with original key to make the next lookup faster
524 // and return the iterator.
525 M[K] = I->second;
526 return I;
527 }
528
Ted Kremenek9449ca92008-08-12 20:41:56 +0000529
Ted Kremenek272aa852008-06-25 21:21:56 +0000530 iterator find(Expr* Receiver, Selector S) {
531 return find(getReceiverDecl(Receiver), S);
532 }
533
534 iterator find(IdentifierInfo* II, Selector S) {
535 // FIXME: Class method lookup. Right now we dont' have a good way
536 // of going between IdentifierInfo* and the class hierarchy.
537 iterator I = M.find(ObjCSummaryKey(II, S));
538 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
539 }
540
541 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
542
543 const PointerType* PT = E->getType()->getAsPointerType();
544 if (!PT) return 0;
545
546 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
547 if (!OI) return 0;
548
549 return OI ? OI->getDecl() : 0;
550 }
551
552 iterator end() { return M.end(); }
553
554 RetainSummary*& operator[](ObjCMessageExpr* ME) {
555
556 Selector S = ME->getSelector();
557
558 if (Expr* Receiver = ME->getReceiver()) {
559 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
560 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
561 }
562
563 return M[ObjCSummaryKey(ME->getClassName(), S)];
564 }
565
566 RetainSummary*& operator[](ObjCSummaryKey K) {
567 return M[K];
568 }
569
570 RetainSummary*& operator[](Selector S) {
571 return M[ ObjCSummaryKey(S) ];
572 }
573};
574} // end anonymous namespace
575
576//===----------------------------------------------------------------------===//
577// Data structures for managing collections of summaries.
578//===----------------------------------------------------------------------===//
579
580namespace {
581class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000582
583 //==-----------------------------------------------------------------==//
584 // Typedefs.
585 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000586
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000587 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
588 FuncSummariesTy;
589
Ted Kremenek84f010c2008-06-23 23:30:29 +0000590 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000591
592 //==-----------------------------------------------------------------==//
593 // Data.
594 //==-----------------------------------------------------------------==//
595
Ted Kremenek272aa852008-06-25 21:21:56 +0000596 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000597 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000598
Ted Kremenekede40b72008-07-09 18:11:16 +0000599 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
600 /// "CFDictionaryCreate".
601 IdentifierInfo* CFDictionaryCreateII;
602
Ted Kremenek272aa852008-06-25 21:21:56 +0000603 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000604 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000605
Ted Kremenek272aa852008-06-25 21:21:56 +0000606 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000607 FuncSummariesTy FuncSummaries;
608
Ted Kremenek272aa852008-06-25 21:21:56 +0000609 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
610 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000611 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000612
Ted Kremenek272aa852008-06-25 21:21:56 +0000613 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000614 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000615
Ted Kremenek272aa852008-06-25 21:21:56 +0000616 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
617 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000618 llvm::BumpPtrAllocator BPAlloc;
619
Ted Kremeneka56ae162009-05-03 05:20:50 +0000620 /// AF - A factory for ArgEffects objects.
621 ArgEffects::Factory AF;
622
Ted Kremenek272aa852008-06-25 21:21:56 +0000623 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000624 ArgEffects ScratchArgs;
625
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000626 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
627 /// objects.
628 RetEffect ObjCAllocRetE;
629
Ted Kremenek286e9852009-05-04 04:57:00 +0000630 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000631 RetainSummary* StopSummary;
632
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000633 //==-----------------------------------------------------------------==//
634 // Methods.
635 //==-----------------------------------------------------------------==//
636
Ted Kremenek272aa852008-06-25 21:21:56 +0000637 /// getArgEffects - Returns a persistent ArgEffects object based on the
638 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000639 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000640
Ted Kremenek562c1302008-05-05 16:51:50 +0000641 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000642
643public:
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000644 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
645
Ted Kremenek2f226732009-05-04 05:31:22 +0000646 RetainSummary *getDefaultSummary() {
647 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
648 return new (Summ) RetainSummary(DefaultSummary);
649 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000650
Ted Kremenek064ef322009-02-23 16:51:39 +0000651 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000652
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000653 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
654 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000655 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000656
Ted Kremeneka56ae162009-05-03 05:20:50 +0000657 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000658 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000659 ArgEffect DefaultEff = MayEscape,
660 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000661
Ted Kremenek266d8b62008-05-06 02:26:56 +0000662 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000663 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000664 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000665 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000666 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000667
Ted Kremeneka821b792009-04-29 05:04:30 +0000668 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000669 if (StopSummary)
670 return StopSummary;
671
672 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
673 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000674
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000675 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000676 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000677
Ted Kremeneka821b792009-04-29 05:04:30 +0000678 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000679
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000680 void InitializeClassMethodSummaries();
681 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000682
Ted Kremenek9b42e062009-05-03 04:42:10 +0000683 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000684 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000685
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000686private:
687
Ted Kremenekf2717b02008-07-18 17:24:20 +0000688 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
689 RetainSummary* Summ) {
690 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
691 }
692
Ted Kremenek272aa852008-06-25 21:21:56 +0000693 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
694 ObjCClassMethodSummaries[S] = Summ;
695 }
696
697 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
698 ObjCMethodSummaries[S] = Summ;
699 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000700
701 void addClassMethSummary(const char* Cls, const char* nullaryName,
702 RetainSummary *Summ) {
703 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
704 Selector S = GetNullarySelector(nullaryName, Ctx);
705 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
706 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000707
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000708 void addInstMethSummary(const char* Cls, const char* nullaryName,
709 RetainSummary *Summ) {
710 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
711 Selector S = GetNullarySelector(nullaryName, Ctx);
712 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
713 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000714
715 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000716 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000717
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000718 while (const char* s = va_arg(argp, const char*))
719 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000720
721 return Ctx.Selectors.getSelector(II.size(), &II[0]);
722 }
723
724 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
725 RetainSummary* Summ, va_list argp) {
726 Selector S = generateSelector(argp);
727 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000728 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000729
730 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
731 va_list argp;
732 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000733 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000734 va_end(argp);
735 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000736
737 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
738 va_list argp;
739 va_start(argp, Summ);
740 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
741 va_end(argp);
742 }
743
744 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
745 va_list argp;
746 va_start(argp, Summ);
747 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
748 va_end(argp);
749 }
750
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000751 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000752 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
753 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000754 DoNothing, DoNothing, true);
755 va_list argp;
756 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000757 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000758 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000759 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000760
Ted Kremeneka7338b42008-03-11 06:39:11 +0000761public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000762
763 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000764 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000765 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000766 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000767 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
768 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000769 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
770 RetEffect::MakeNoRet() /* return effect */,
Ted Kremeneka13b0862009-05-11 18:30:24 +0000771 MayEscape, /* default argument effect */
772 DoNothing /* receiver effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000773 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000774
775 InitializeClassMethodSummaries();
776 InitializeMethodSummaries();
777 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000778
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000779 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000780
Ted Kremenekd13c1872008-06-24 03:56:45 +0000781 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000782
Ted Kremenek314b1952009-04-29 23:03:22 +0000783 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
784 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000785 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000786 ID, ME->getMethodDecl(), ME->getType());
787 }
788
Ted Kremenek04e00302009-04-29 17:09:14 +0000789 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000790 const ObjCInterfaceDecl* ID,
791 const ObjCMethodDecl *MD,
792 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000793
794 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000795 const ObjCInterfaceDecl *ID,
796 const ObjCMethodDecl *MD,
797 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000798
799 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
800 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
801 ME->getClassInfo().first,
802 ME->getMethodDecl(), ME->getType());
803 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000804
805 /// getMethodSummary - This version of getMethodSummary is used to query
806 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000807 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
808 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000809 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000810 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000811 IdentifierInfo *ClsName = ID->getIdentifier();
812 QualType ResultTy = MD->getResultType();
813
Ted Kremenek81eb4642009-04-30 05:47:23 +0000814 // Resolve the method decl last.
815 if (const ObjCMethodDecl *InterfaceMD =
816 ResolveToInterfaceMethodDecl(MD, Ctx))
817 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000818
Ted Kremenek91b89a42009-04-29 17:17:48 +0000819 if (MD->isInstanceMethod())
820 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
821 else
822 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
823 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000824
Ted Kremenek314b1952009-04-29 23:03:22 +0000825 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
826 Selector S, QualType RetTy);
827
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000828 void updateSummaryFromAnnotations(RetainSummary &Summ,
829 const ObjCMethodDecl *MD);
830
831 void updateSummaryFromAnnotations(RetainSummary &Summ,
832 const FunctionDecl *FD);
833
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000834 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000835
836 RetainSummary *copySummary(RetainSummary *OldSumm) {
837 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
838 new (Summ) RetainSummary(*OldSumm);
839 return Summ;
840 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000841};
842
843} // end anonymous namespace
844
845//===----------------------------------------------------------------------===//
846// Implementation of checker data structures.
847//===----------------------------------------------------------------------===//
848
Ted Kremeneka56ae162009-05-03 05:20:50 +0000849RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000850
Ted Kremeneka56ae162009-05-03 05:20:50 +0000851ArgEffects RetainSummaryManager::getArgEffects() {
852 ArgEffects AE = ScratchArgs;
853 ScratchArgs = AF.GetEmptyMap();
854 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000855}
856
Ted Kremenek266d8b62008-05-06 02:26:56 +0000857RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000858RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000859 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000860 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000861 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000862 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000863 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000864 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000865 return Summ;
866}
867
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000868//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000869// Predicates.
870//===----------------------------------------------------------------------===//
871
Ted Kremenek9b42e062009-05-03 04:42:10 +0000872bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000873 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000874 return false;
875
Ted Kremenek0d813552009-04-23 22:11:07 +0000876 // We assume that id<..>, id, and "Class" all represent tracked objects.
877 const PointerType *PT = Ty->getAsPointerType();
878 if (PT == 0)
879 return true;
880
881 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000882
883 // We assume that id<..>, id, and "Class" all represent tracked objects.
884 if (!OT)
885 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000886
887 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000888 // FIXME: We can memoize here if this gets too expensive.
889 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
890 ObjCInterfaceDecl* ID = OT->getDecl();
891
892 for ( ; ID ; ID = ID->getSuperClass())
893 if (ID->getIdentifier() == NSObjectII)
894 return true;
895
896 return false;
897}
898
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000899bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
900 return isRefType(T, "CF") || // Core Foundation.
901 isRefType(T, "CG") || // Core Graphics.
902 isRefType(T, "DADisk") || // Disk Arbitration API.
903 isRefType(T, "DADissenter") ||
904 isRefType(T, "DASessionRef");
905}
906
Ted Kremenek35920ed2009-01-07 00:39:56 +0000907//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000908// Summary creation for functions (largely uses of Core Foundation).
909//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000910
Ted Kremenek17144e82009-01-12 21:45:02 +0000911static bool isRetain(FunctionDecl* FD, const char* FName) {
912 const char* loc = strstr(FName, "Retain");
913 return loc && loc[sizeof("Retain")-1] == '\0';
914}
915
916static bool isRelease(FunctionDecl* FD, const char* FName) {
917 const char* loc = strstr(FName, "Release");
918 return loc && loc[sizeof("Release")-1] == '\0';
919}
920
Ted Kremenekd13c1872008-06-24 03:56:45 +0000921RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000922 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000923 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000924 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000925 return I->second;
926
Ted Kremenek64cddf12009-05-04 15:34:07 +0000927 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000928 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000929
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000930 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000931 // We generate "stop" summaries for implicitly defined functions.
932 if (FD->isImplicit()) {
933 S = getPersistentStopSummary();
934 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000935 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000936
Ted Kremenek064ef322009-02-23 16:51:39 +0000937 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000938 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000939 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000940 const char* FName = FD->getIdentifier()->getName();
941
Ted Kremenek38c6f022009-03-05 22:11:14 +0000942 // Strip away preceding '_'. Doing this here will effect all the checks
943 // down below.
944 while (*FName == '_') ++FName;
945
Ted Kremenek17144e82009-01-12 21:45:02 +0000946 // Inspect the result type.
947 QualType RetTy = FT->getResultType();
948
949 // FIXME: This should all be refactored into a chain of "summary lookup"
950 // filters.
951 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
952 // FIXES: <rdar://problem/6326900>
953 // This should be addressed using a API table. This strcmp is also
954 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000955 assert (ScratchArgs.isEmpty());
956 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000957 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
958 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000959 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000960
961 // Enable this code once the semantics of NSDeallocateObject are resolved
962 // for GC. <rdar://problem/6619988>
963#if 0
964 // Handle: NSDeallocateObject(id anObject);
965 // This method does allow 'nil' (although we don't check it now).
966 if (strcmp(FName, "NSDeallocateObject") == 0) {
967 return RetTy == Ctx.VoidTy
968 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
969 : getPersistentStopSummary();
970 }
971#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000972
973 // Handle: id NSMakeCollectable(CFTypeRef)
974 if (strcmp(FName, "NSMakeCollectable") == 0) {
975 S = (RetTy == Ctx.getObjCIdType())
976 ? getUnarySummary(FT, cfmakecollectable)
977 : getPersistentStopSummary();
978
979 break;
980 }
981
982 if (RetTy->isPointerType()) {
983 // For CoreFoundation ('CF') types.
984 if (isRefType(RetTy, "CF", &Ctx, FName)) {
985 if (isRetain(FD, FName))
986 S = getUnarySummary(FT, cfretain);
987 else if (strstr(FName, "MakeCollectable"))
988 S = getUnarySummary(FT, cfmakecollectable);
989 else
990 S = getCFCreateGetRuleSummary(FD, FName);
991
992 break;
993 }
994
995 // For CoreGraphics ('CG') types.
996 if (isRefType(RetTy, "CG", &Ctx, FName)) {
997 if (isRetain(FD, FName))
998 S = getUnarySummary(FT, cfretain);
999 else
1000 S = getCFCreateGetRuleSummary(FD, FName);
1001
1002 break;
1003 }
1004
1005 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1006 if (isRefType(RetTy, "DADisk") ||
1007 isRefType(RetTy, "DADissenter") ||
1008 isRefType(RetTy, "DASessionRef")) {
1009 S = getCFCreateGetRuleSummary(FD, FName);
1010 break;
1011 }
1012
1013 break;
1014 }
1015
1016 // Check for release functions, the only kind of functions that we care
1017 // about that don't return a pointer type.
1018 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001019 // Test for 'CGCF'.
1020 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1021 FName += 4;
1022 else
1023 FName += 2;
1024
1025 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001026 S = getUnarySummary(FT, cfrelease);
1027 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001028 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001029 // Remaining CoreFoundation and CoreGraphics functions.
1030 // We use to assume that they all strictly followed the ownership idiom
1031 // and that ownership cannot be transferred. While this is technically
1032 // correct, many methods allow a tracked object to escape. For example:
1033 //
1034 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1035 // CFDictionaryAddValue(y, key, x);
1036 // CFRelease(x);
1037 // ... it is okay to use 'x' since 'y' has a reference to it
1038 //
1039 // We handle this and similar cases with the follow heuristic. If the
1040 // function name contains "InsertValue", "SetValue" or "AddValue" then
1041 // we assume that arguments may "escape."
1042 //
1043 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1044 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001045 CStrInCStrNoCase(FName, "SetValue") ||
1046 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001047 ? MayEscape : DoNothing;
1048
1049 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001050 }
1051 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001052 }
1053 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001054
1055 if (!S)
1056 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001057
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001058 // Annotations override defaults.
1059 assert(S);
1060 updateSummaryFromAnnotations(*S, FD);
1061
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001062 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001063 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001064}
1065
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001066RetainSummary*
1067RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1068 const char* FName) {
1069
Ted Kremenek562c1302008-05-05 16:51:50 +00001070 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1071 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001072
Ted Kremenek562c1302008-05-05 16:51:50 +00001073 if (strstr(FName, "Get"))
1074 return getCFSummaryGetRule(FD);
1075
Ted Kremenek286e9852009-05-04 04:57:00 +00001076 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001077}
1078
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001079RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001080RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1081 UnaryFuncKind func) {
1082
Ted Kremenek17144e82009-01-12 21:45:02 +00001083 // Sanity check that this is *really* a unary function. This can
1084 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001085 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001086 if (!FTP || FTP->getNumArgs() != 1)
1087 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001088
Ted Kremeneka56ae162009-05-03 05:20:50 +00001089 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001090
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001091 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001092 case cfretain: {
1093 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001094 return getPersistentSummary(RetEffect::MakeAlias(0),
1095 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001096 }
1097
1098 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001099 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001100 return getPersistentSummary(RetEffect::MakeNoRet(),
1101 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001102 }
1103
1104 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001105 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001106 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001107 }
1108
1109 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001110 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001111 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001112 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001113}
1114
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001115RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001116 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001117
1118 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001119 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1120 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001121 }
1122
Ted Kremenek68621b92009-01-28 05:56:51 +00001123 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001124}
1125
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001126RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001127 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001128 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1129 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001130}
1131
Ted Kremeneka7338b42008-03-11 06:39:11 +00001132//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001133// Summary creation for Selectors.
1134//===----------------------------------------------------------------------===//
1135
Ted Kremenekbcaff792008-05-06 15:44:25 +00001136RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001137RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001138 assert(ScratchArgs.isEmpty());
1139 // 'init' methods conceptually return a newly allocated object and claim
1140 // the receiver.
1141 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
1142 return getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1143 DecRefMsg);
1144
1145 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001146}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001147
1148void
1149RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1150 const FunctionDecl *FD) {
1151 if (!FD)
1152 return;
1153
1154 // Determine if there is a special return effect for this method.
1155 if (isTrackedObjCObjectType(FD->getResultType())) {
1156 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1157 Summ.setRetEffect(ObjCAllocRetE);
1158 }
1159 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1160 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1161 }
1162 }
1163}
1164
1165void
1166RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1167 const ObjCMethodDecl *MD) {
1168 if (!MD)
1169 return;
1170
1171 // Determine if there is a special return effect for this method.
1172 if (isTrackedObjCObjectType(MD->getResultType())) {
1173 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1174 Summ.setRetEffect(ObjCAllocRetE);
1175 }
1176 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1177 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1178 }
1179 }
1180}
1181
Ted Kremenekbcaff792008-05-06 15:44:25 +00001182RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001183RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1184 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001185
Ted Kremenek578498a2009-04-29 00:42:39 +00001186 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001187 // Scan the method decl for 'void*' arguments. These should be treated
1188 // as 'StopTracking' because they are often used with delegates.
1189 // Delegates are a frequent form of false positives with the retain
1190 // count checker.
1191 unsigned i = 0;
1192 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1193 E = MD->param_end(); I != E; ++I, ++i)
1194 if (ParmVarDecl *PD = *I) {
1195 QualType Ty = Ctx.getCanonicalType(PD->getType());
1196 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001197 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001198 }
1199 }
1200
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001201 // Any special effect for the receiver?
1202 ArgEffect ReceiverEff = DoNothing;
1203
1204 // If one of the arguments in the selector has the keyword 'delegate' we
1205 // should stop tracking the reference count for the receiver. This is
1206 // because the reference count is quite possibly handled by a delegate
1207 // method.
1208 if (S.isKeywordSelector()) {
1209 const std::string &str = S.getAsString();
1210 assert(!str.empty());
1211 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1212 }
1213
Ted Kremenek174a0772009-04-23 23:08:22 +00001214 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001215 if (isTrackedObjCObjectType(RetTy)) {
1216 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1217 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001218 RetEffect E =
1219 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001220 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001221
1222 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001223 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001224
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001225 // Look for methods that return an owned core foundation object.
1226 if (isTrackedCFObjectType(RetTy)) {
1227 RetEffect E =
1228 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1229 ? RetEffect::MakeOwned(RetEffect::CF, true)
1230 : RetEffect::MakeNotOwned(RetEffect::CF);
1231
1232 return getPersistentSummary(E, ReceiverEff, MayEscape);
1233 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001234
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001235 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001236 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001237
Ted Kremenek2f226732009-05-04 05:31:22 +00001238 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001239}
1240
1241RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001242RetainSummaryManager::getInstanceMethodSummary(Selector S,
1243 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001244 const ObjCInterfaceDecl* ID,
1245 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001246 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001247
Ted Kremeneka821b792009-04-29 05:04:30 +00001248 // Look up a summary in our summary cache.
1249 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001250
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001251 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001252 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001253
Ted Kremeneka56ae162009-05-03 05:20:50 +00001254 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001255 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001256
Ted Kremenek2f226732009-05-04 05:31:22 +00001257 // "initXXX": pass-through for receiver.
1258 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1259 == InitRule)
1260 Summ = getInitMethodSummary(RetTy);
1261 else
1262 Summ = getCommonMethodSummary(MD, S, RetTy);
1263
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001264 // Annotations override defaults.
1265 updateSummaryFromAnnotations(*Summ, MD);
1266
Ted Kremenek2f226732009-05-04 05:31:22 +00001267 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001268 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001269 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001270}
1271
Ted Kremeneka7722b72008-05-06 21:26:51 +00001272RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001273RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001274 const ObjCInterfaceDecl *ID,
1275 const ObjCMethodDecl *MD,
1276 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001277
Ted Kremenek578498a2009-04-29 00:42:39 +00001278 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001279 ObjCMethodSummariesTy::iterator I =
1280 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001281
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001282 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001283 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001284
1285 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001286
1287 // Annotations override defaults.
1288 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001289
Ted Kremenek2f226732009-05-04 05:31:22 +00001290 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001291 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001292 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001293}
1294
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001295void RetainSummaryManager::InitializeClassMethodSummaries() {
1296 assert(ScratchArgs.isEmpty());
1297 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001298
Ted Kremenek272aa852008-06-25 21:21:56 +00001299 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1300 // NSObject and its derivatives.
1301 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1302 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1303 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001304
1305 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001306 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001307 GetNullarySelector("currentHandler", Ctx),
1308 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001309
1310 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001311 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001312 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1313 GetUnarySelector("addObject", Ctx),
1314 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001315 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001316
1317 // Create the summaries for [NSObject performSelector...]. We treat
1318 // these as 'stop tracking' for the arguments because they are often
1319 // used for delegates that can release the object. When we have better
1320 // inter-procedural analysis we can potentially do something better. This
1321 // workaround is to remove false positives.
1322 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1323 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1324 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1325 "afterDelay", NULL);
1326 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1327 "afterDelay", "inModes", NULL);
1328 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1329 "withObject", "waitUntilDone", NULL);
1330 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1331 "withObject", "waitUntilDone", "modes", NULL);
1332 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1333 "withObject", "waitUntilDone", NULL);
1334 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1335 "withObject", "waitUntilDone", "modes", NULL);
1336 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1337 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001338}
1339
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001340void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001341
Ted Kremeneka56ae162009-05-03 05:20:50 +00001342 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001343
Ted Kremeneka7722b72008-05-06 21:26:51 +00001344 // Create the "init" selector. It just acts as a pass-through for the
1345 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001346 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
1347 getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1348 DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001349
1350 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001351 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001352
1353 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001354 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1355
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001356 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001357 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001358
Ted Kremenek266d8b62008-05-06 02:26:56 +00001359 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001360 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001361 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001362 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001363
1364 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001365 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001366 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001367
1368 // Create the "drain" selector.
1369 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001370 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001371
1372 // Create the -dealloc summary.
1373 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1374 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001375
1376 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001377 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001378 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001379
Ted Kremenekaac82832009-02-23 17:45:03 +00001380 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001381 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001382 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001383 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001384
Ted Kremenek45642a42008-08-12 18:48:50 +00001385 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001386 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1387 // self-own themselves. However, they only do this once they are displayed.
1388 // Thus, we need to track an NSWindow's display status.
1389 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001390 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001391 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1392 StopTracking,
1393 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001394
1395 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1396
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001397#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001398 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001399 "styleMask", "backing", "defer", NULL);
1400
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001401 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001402 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001403#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001404
Ted Kremenek45642a42008-08-12 18:48:50 +00001405 // For NSPanel (which subclasses NSWindow), allocated objects are not
1406 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001407 // FIXME: For now we don't track NSPanels. object for the same reason
1408 // as for NSWindow objects.
1409 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1410
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001411#if 0
1412 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001413 "styleMask", "backing", "defer", NULL);
1414
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001415 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001416 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001417#endif
Ted Kremenek272aa852008-06-25 21:21:56 +00001418
Ted Kremenekf2717b02008-07-18 17:24:20 +00001419 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001420 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1421 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001422
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001423 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1424 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001425}
1426
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001427//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001428// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001429//===----------------------------------------------------------------------===//
1430
Ted Kremeneka7338b42008-03-11 06:39:11 +00001431namespace {
1432
Ted Kremenek7d421f32008-04-09 23:49:11 +00001433class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001434public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001435 enum Kind {
1436 Owned = 0, // Owning reference.
1437 NotOwned, // Reference is not owned by still valid (not freed).
1438 Released, // Object has been released.
1439 ReturnedOwned, // Returned object passes ownership to caller.
1440 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001441 ERROR_START,
1442 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1443 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001444 ErrorUseAfterRelease, // Object used after released.
1445 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001446 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001447 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001448 ErrorLeakReturned, // A memory leak due to the returning method not having
1449 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001450 ErrorGCLeakReturned,
1451 ErrorOverAutorelease,
1452 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001453 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001454
1455private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001456 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001457 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001458 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001459 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001460 QualType T;
1461
Ted Kremenek4d99d342009-05-08 20:01:42 +00001462 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1463 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001464
Ted Kremenek68621b92009-01-28 05:56:51 +00001465 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001466 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001467
1468public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001469 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001470
1471 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001472
Ted Kremenek4d99d342009-05-08 20:01:42 +00001473 unsigned getCount() const { return Cnt; }
1474 unsigned getAutoreleaseCount() const { return ACnt; }
1475 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1476 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001477 void setCount(unsigned i) { Cnt = i; }
1478 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001479
Ted Kremenek272aa852008-06-25 21:21:56 +00001480 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001481
1482 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001483
Ted Kremenek6537a642009-03-17 19:42:23 +00001484 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001485
Ted Kremenek6537a642009-03-17 19:42:23 +00001486 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001487
Ted Kremenekffefc352008-04-11 22:25:11 +00001488 bool isOwned() const {
1489 return getKind() == Owned;
1490 }
1491
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001492 bool isNotOwned() const {
1493 return getKind() == NotOwned;
1494 }
1495
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001496 bool isReturnedOwned() const {
1497 return getKind() == ReturnedOwned;
1498 }
1499
1500 bool isReturnedNotOwned() const {
1501 return getKind() == ReturnedNotOwned;
1502 }
1503
1504 bool isNonLeakError() const {
1505 Kind k = getKind();
1506 return isError(k) && !isLeak(k);
1507 }
1508
Ted Kremenek68621b92009-01-28 05:56:51 +00001509 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1510 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001511 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001512 }
1513
Ted Kremenek68621b92009-01-28 05:56:51 +00001514 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1515 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001516 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001517 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001518
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001519 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001520
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001521 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001522 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001523 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001524
Ted Kremenek272aa852008-06-25 21:21:56 +00001525 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001526 return RefVal(getKind(), getObjKind(), getCount() - i,
1527 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001528 }
1529
1530 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001531 return RefVal(getKind(), getObjKind(), getCount() + i,
1532 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001533 }
1534
1535 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001536 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1537 getType());
1538 }
1539
1540 RefVal autorelease() const {
1541 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1542 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001543 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001544
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001545 void Profile(llvm::FoldingSetNodeID& ID) const {
1546 ID.AddInteger((unsigned) kind);
1547 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001548 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001549 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001550 }
1551
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001552 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001553};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001554
1555void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001556 if (!T.isNull())
1557 Out << "Tracked Type:" << T.getAsString() << '\n';
1558
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001559 switch (getKind()) {
1560 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001561 case Owned: {
1562 Out << "Owned";
1563 unsigned cnt = getCount();
1564 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001565 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001566 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001567
Ted Kremenekc4f81022008-04-10 23:09:18 +00001568 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001569 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001570 unsigned cnt = getCount();
1571 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001572 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001573 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001574
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001575 case ReturnedOwned: {
1576 Out << "ReturnedOwned";
1577 unsigned cnt = getCount();
1578 if (cnt) Out << " (+ " << cnt << ")";
1579 break;
1580 }
1581
1582 case ReturnedNotOwned: {
1583 Out << "ReturnedNotOwned";
1584 unsigned cnt = getCount();
1585 if (cnt) Out << " (+ " << cnt << ")";
1586 break;
1587 }
1588
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001589 case Released:
1590 Out << "Released";
1591 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001592
1593 case ErrorDeallocGC:
1594 Out << "-dealloc (GC)";
1595 break;
1596
1597 case ErrorDeallocNotOwned:
1598 Out << "-dealloc (not-owned)";
1599 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001600
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001601 case ErrorLeak:
1602 Out << "Leaked";
1603 break;
1604
Ted Kremenek311f3d42008-10-22 23:56:21 +00001605 case ErrorLeakReturned:
1606 Out << "Leaked (Bad naming)";
1607 break;
1608
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001609 case ErrorGCLeakReturned:
1610 Out << "Leaked (GC-ed at return)";
1611 break;
1612
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001613 case ErrorUseAfterRelease:
1614 Out << "Use-After-Release [ERROR]";
1615 break;
1616
1617 case ErrorReleaseNotOwned:
1618 Out << "Release of Not-Owned [ERROR]";
1619 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001620
1621 case RefVal::ErrorOverAutorelease:
1622 Out << "Over autoreleased";
1623 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001624
1625 case RefVal::ErrorReturnedNotOwned:
1626 Out << "Non-owned object returned instead of owned";
1627 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001628 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001629
1630 if (ACnt) {
1631 Out << " [ARC +" << ACnt << ']';
1632 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001633}
Ted Kremenek0d721572008-03-11 17:48:22 +00001634
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001635} // end anonymous namespace
1636
1637//===----------------------------------------------------------------------===//
1638// RefBindings - State used to track object reference counts.
1639//===----------------------------------------------------------------------===//
1640
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001641typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001642static int RefBIndex = 0;
1643
1644namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001645 template<>
1646 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1647 static inline void* GDMIndex() { return &RefBIndex; }
1648 };
1649}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001650
1651//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001652// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001653//===----------------------------------------------------------------------===//
1654
Ted Kremenekb6578942009-02-24 19:15:11 +00001655typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1656typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1657typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001658
Ted Kremenekb6578942009-02-24 19:15:11 +00001659static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001660static int AutoRBIndex = 0;
1661
Ted Kremenekb6578942009-02-24 19:15:11 +00001662namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001663namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001664
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001665namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001666template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001667 : public GRStatePartialTrait<ARStack> {
1668 static inline void* GDMIndex() { return &AutoRBIndex; }
1669};
1670
1671template<> struct GRStateTrait<AutoreleasePoolContents>
1672 : public GRStatePartialTrait<ARPoolContents> {
1673 static inline void* GDMIndex() { return &AutoRCIndex; }
1674};
1675} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001676
Ted Kremenek681fb352009-03-20 17:34:15 +00001677static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1678 ARStack stack = state->get<AutoreleaseStack>();
1679 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1680}
1681
1682static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1683 SymbolRef sym) {
1684
1685 SymbolRef pool = GetCurrentAutoreleasePool(state);
1686 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1687 ARCounts newCnts(0);
1688
1689 if (cnts) {
1690 const unsigned *cnt = (*cnts).lookup(sym);
1691 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1692 }
1693 else
1694 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1695
1696 return state.set<AutoreleasePoolContents>(pool, newCnts);
1697}
1698
Ted Kremenek7aef4842008-04-16 20:40:59 +00001699//===----------------------------------------------------------------------===//
1700// Transfer functions.
1701//===----------------------------------------------------------------------===//
1702
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001703namespace {
1704
Ted Kremenek7d421f32008-04-09 23:49:11 +00001705class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001706public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001707 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001708 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001709 virtual void Print(std::ostream& Out, const GRState* state,
1710 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001711 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001712
1713private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001714 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1715 SummaryLogTy;
1716
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001717 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001718 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001719 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001720 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001721
Ted Kremenek708af042009-02-05 06:50:21 +00001722 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001723 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001724 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001725 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001726 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001727 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001728
Ted Kremenekb6578942009-02-24 19:15:11 +00001729 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1730 RefVal::Kind& hasErr);
1731
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001732 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1733 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001734 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001735 ExplodedNode<GRState>* Pred,
1736 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001737 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001738
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001739 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1740 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1741
1742 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1743 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1744 GenericNodeBuilder &Builder,
1745 GRExprEngine &Eng,
1746 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001747
Ted Kremenekb6578942009-02-24 19:15:11 +00001748public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001749 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001750 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001751 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1752 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001753 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1754 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001755
Ted Kremenek708af042009-02-05 06:50:21 +00001756 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001757
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001758 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001759
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001760 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1761 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001762 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001763
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001764 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001765 const LangOptions& getLangOptions() const { return LOpts; }
1766
Ted Kremenekc26c4692009-02-18 03:48:14 +00001767 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1768 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1769 return I == SummaryLog.end() ? 0 : I->second;
1770 }
1771
Ted Kremeneka7338b42008-03-11 06:39:11 +00001772 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001773
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001774 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001775 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001776 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001777 Expr* Ex,
1778 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001779 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001780 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001781 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001782
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001783 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001784 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001785 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001786 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001787 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001788
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001789
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001790 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001791 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001792 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001793 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001794 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001795
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001796 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001797 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001798 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001799 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001800 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001801
Ted Kremeneka42be302009-02-14 01:43:44 +00001802 // Stores.
1803 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1804
Ted Kremenekffefc352008-04-11 22:25:11 +00001805 // End-of-path.
1806
1807 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001808 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001809
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001810 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001811 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001812 GRStmtNodeBuilder<GRState>& Builder,
1813 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001814 Stmt* S, const GRState* state,
1815 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001816
1817 std::pair<ExplodedNode<GRState>*, GRStateRef>
1818 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001819 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1820 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001821 // Return statements.
1822
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001823 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001824 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001825 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001826 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001827 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001828
1829 // Assumptions.
1830
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001831 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001832 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001833 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001834};
1835
1836} // end anonymous namespace
1837
Ted Kremenek681fb352009-03-20 17:34:15 +00001838static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1839 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001840 if (Sym)
1841 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001842 else
1843 Out << "<pool>";
1844 Out << ":{";
1845
1846 // Get the contents of the pool.
1847 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1848 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1849 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1850
1851 Out << '}';
1852}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001853
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001854void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1855 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001856
1857
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001858
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001859 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001860
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001861 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001862 Out << sep << nl;
1863
1864 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1865 Out << (*I).first << " : ";
1866 (*I).second.print(Out);
1867 Out << nl;
1868 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001869
1870 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001871 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001872 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001873
Ted Kremenek681fb352009-03-20 17:34:15 +00001874 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1875 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1876 PrintPool(Out, *I, state);
1877
1878 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001879}
1880
Ted Kremenek47a72422009-04-29 18:50:19 +00001881//===----------------------------------------------------------------------===//
1882// Error reporting.
1883//===----------------------------------------------------------------------===//
1884
1885namespace {
1886
1887 //===-------------===//
1888 // Bug Descriptions. //
1889 //===-------------===//
1890
1891 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1892 protected:
1893 CFRefCount& TF;
1894
1895 CFRefBug(CFRefCount* tf, const char* name)
1896 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1897 public:
1898
1899 CFRefCount& getTF() { return TF; }
1900 const CFRefCount& getTF() const { return TF; }
1901
1902 // FIXME: Eventually remove.
1903 virtual const char* getDescription() const = 0;
1904
1905 virtual bool isLeak() const { return false; }
1906 };
1907
1908 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1909 public:
1910 UseAfterRelease(CFRefCount* tf)
1911 : CFRefBug(tf, "Use-after-release") {}
1912
1913 const char* getDescription() const {
1914 return "Reference-counted object is used after it is released";
1915 }
1916 };
1917
1918 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1919 public:
1920 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1921
1922 const char* getDescription() const {
1923 return "Incorrect decrement of the reference count of an "
1924 "object is not owned at this point by the caller";
1925 }
1926 };
1927
1928 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1929 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001930 DeallocGC(CFRefCount *tf)
1931 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001932
1933 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001934 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001935 }
1936 };
1937
1938 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1939 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001940 DeallocNotOwned(CFRefCount *tf)
1941 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001942
1943 const char *getDescription() const {
1944 return "-dealloc sent to object that may be referenced elsewhere";
1945 }
1946 };
1947
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001948 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1949 public:
1950 OverAutorelease(CFRefCount *tf) :
1951 CFRefBug(tf, "Object sent -autorelease too many times") {}
1952
1953 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001954 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001955 }
1956 };
1957
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001958 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1959 public:
1960 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1961 CFRefBug(tf, "Method should return an owned object") {}
1962
1963 const char *getDescription() const {
1964 return "Object with +0 retain counts returned to caller where a +1 "
1965 "(owning) retain count is expected";
1966 }
1967 };
1968
Ted Kremenek47a72422009-04-29 18:50:19 +00001969 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1970 const bool isReturn;
1971 protected:
1972 Leak(CFRefCount* tf, const char* name, bool isRet)
1973 : CFRefBug(tf, name), isReturn(isRet) {}
1974 public:
1975
1976 const char* getDescription() const { return ""; }
1977
1978 bool isLeak() const { return true; }
1979 };
1980
1981 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1982 public:
1983 LeakAtReturn(CFRefCount* tf, const char* name)
1984 : Leak(tf, name, true) {}
1985 };
1986
1987 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1988 public:
1989 LeakWithinFunction(CFRefCount* tf, const char* name)
1990 : Leak(tf, name, false) {}
1991 };
1992
1993 //===---------===//
1994 // Bug Reports. //
1995 //===---------===//
1996
1997 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1998 protected:
1999 SymbolRef Sym;
2000 const CFRefCount &TF;
2001 public:
2002 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2003 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002004 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2005
2006 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2007 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002008 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002009
2010 virtual ~CFRefReport() {}
2011
2012 CFRefBug& getBugType() {
2013 return (CFRefBug&) RangedBugReport::getBugType();
2014 }
2015 const CFRefBug& getBugType() const {
2016 return (const CFRefBug&) RangedBugReport::getBugType();
2017 }
2018
2019 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2020 const SourceRange*& end) {
2021
2022 if (!getBugType().isLeak())
2023 RangedBugReport::getRanges(BR, beg, end);
2024 else
2025 beg = end = 0;
2026 }
2027
2028 SymbolRef getSymbol() const { return Sym; }
2029
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002030 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002031 const ExplodedNode<GRState>* N);
2032
2033 std::pair<const char**,const char**> getExtraDescriptiveText();
2034
2035 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2036 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002037 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002038 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002039
Ted Kremenek47a72422009-04-29 18:50:19 +00002040 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2041 SourceLocation AllocSite;
2042 const MemRegion* AllocBinding;
2043 public:
2044 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2045 ExplodedNode<GRState> *n, SymbolRef sym,
2046 GRExprEngine& Eng);
2047
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002048 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002049 const ExplodedNode<GRState>* N);
2050
2051 SourceLocation getLocation() const { return AllocSite; }
2052 };
2053} // end anonymous namespace
2054
2055void CFRefCount::RegisterChecks(BugReporter& BR) {
2056 useAfterRelease = new UseAfterRelease(this);
2057 BR.Register(useAfterRelease);
2058
2059 releaseNotOwned = new BadRelease(this);
2060 BR.Register(releaseNotOwned);
2061
2062 deallocGC = new DeallocGC(this);
2063 BR.Register(deallocGC);
2064
2065 deallocNotOwned = new DeallocNotOwned(this);
2066 BR.Register(deallocNotOwned);
2067
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002068 overAutorelease = new OverAutorelease(this);
2069 BR.Register(overAutorelease);
2070
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002071 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2072 BR.Register(returnNotOwnedForOwned);
2073
Ted Kremenek47a72422009-04-29 18:50:19 +00002074 // First register "return" leaks.
2075 const char* name = 0;
2076
2077 if (isGCEnabled())
2078 name = "Leak of returned object when using garbage collection";
2079 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2080 name = "Leak of returned object when not using garbage collection (GC) in "
2081 "dual GC/non-GC code";
2082 else {
2083 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2084 name = "Leak of returned object";
2085 }
2086
2087 leakAtReturn = new LeakAtReturn(this, name);
2088 BR.Register(leakAtReturn);
2089
2090 // Second, register leaks within a function/method.
2091 if (isGCEnabled())
2092 name = "Leak of object when using garbage collection";
2093 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2094 name = "Leak of object when not using garbage collection (GC) in "
2095 "dual GC/non-GC code";
2096 else {
2097 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2098 name = "Leak";
2099 }
2100
2101 leakWithinFunction = new LeakWithinFunction(this, name);
2102 BR.Register(leakWithinFunction);
2103
2104 // Save the reference to the BugReporter.
2105 this->BR = &BR;
2106}
2107
2108static const char* Msgs[] = {
2109 // GC only
2110 "Code is compiled to only use garbage collection",
2111 // No GC.
2112 "Code is compiled to use reference counts",
2113 // Hybrid, with GC.
2114 "Code is compiled to use either garbage collection (GC) or reference counts"
2115 " (non-GC). The bug occurs with GC enabled",
2116 // Hybrid, without GC
2117 "Code is compiled to use either garbage collection (GC) or reference counts"
2118 " (non-GC). The bug occurs in non-GC mode"
2119};
2120
2121std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2122 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2123
2124 switch (TF.getLangOptions().getGCMode()) {
2125 default:
2126 assert(false);
2127
2128 case LangOptions::GCOnly:
2129 assert (TF.isGCEnabled());
2130 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2131
2132 case LangOptions::NonGC:
2133 assert (!TF.isGCEnabled());
2134 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2135
2136 case LangOptions::HybridGC:
2137 if (TF.isGCEnabled())
2138 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2139 else
2140 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2141 }
2142}
2143
2144static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2145 ArgEffect X) {
2146 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2147 I!=E; ++I)
2148 if (*I == X) return true;
2149
2150 return false;
2151}
2152
2153PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2154 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002155 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002156
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002157 // Check if the type state has changed.
2158 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002159 GRStateRef PrevSt(PrevN->getState(), StMgr);
2160 GRStateRef CurrSt(N->getState(), StMgr);
2161
2162 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2163 if (!CurrT) return NULL;
2164
2165 const RefVal& CurrV = *CurrT;
2166 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2167
2168 // Create a string buffer to constain all the useful things we want
2169 // to tell the user.
2170 std::string sbuf;
2171 llvm::raw_string_ostream os(sbuf);
2172
2173 // This is the allocation site since the previous node had no bindings
2174 // for this symbol.
2175 if (!PrevT) {
2176 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2177
2178 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2179 // Get the name of the callee (if it is available).
2180 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2181 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2182 os << "Call to function '" << FD->getNameAsString() <<'\'';
2183 else
2184 os << "function call";
2185 }
2186 else {
2187 assert (isa<ObjCMessageExpr>(S));
2188 os << "Method";
2189 }
2190
2191 if (CurrV.getObjKind() == RetEffect::CF) {
2192 os << " returns a Core Foundation object with a ";
2193 }
2194 else {
2195 assert (CurrV.getObjKind() == RetEffect::ObjC);
2196 os << " returns an Objective-C object with a ";
2197 }
2198
2199 if (CurrV.isOwned()) {
2200 os << "+1 retain count (owning reference).";
2201
2202 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2203 assert(CurrV.getObjKind() == RetEffect::CF);
2204 os << " "
2205 "Core Foundation objects are not automatically garbage collected.";
2206 }
2207 }
2208 else {
2209 assert (CurrV.isNotOwned());
2210 os << "+0 retain count (non-owning reference).";
2211 }
2212
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002213 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002214 return new PathDiagnosticEventPiece(Pos, os.str());
2215 }
2216
2217 // Gather up the effects that were performed on the object at this
2218 // program point
2219 llvm::SmallVector<ArgEffect, 2> AEffects;
2220
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002221 if (const RetainSummary *Summ =
2222 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002223 // We only have summaries attached to nodes after evaluating CallExpr and
2224 // ObjCMessageExprs.
2225 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2226
2227 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2228 // Iterate through the parameter expressions and see if the symbol
2229 // was ever passed as an argument.
2230 unsigned i = 0;
2231
2232 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2233 AI!=AE; ++AI, ++i) {
2234
2235 // Retrieve the value of the argument. Is it the symbol
2236 // we are interested in?
2237 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2238 continue;
2239
2240 // We have an argument. Get the effect!
2241 AEffects.push_back(Summ->getArg(i));
2242 }
2243 }
2244 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2245 if (Expr *receiver = ME->getReceiver())
2246 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2247 // The symbol we are tracking is the receiver.
2248 AEffects.push_back(Summ->getReceiverEffect());
2249 }
2250 }
2251 }
2252
2253 do {
2254 // Get the previous type state.
2255 RefVal PrevV = *PrevT;
2256
2257 // Specially handle -dealloc.
2258 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2259 // Determine if the object's reference count was pushed to zero.
2260 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2261 // We may not have transitioned to 'release' if we hit an error.
2262 // This case is handled elsewhere.
2263 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002264 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002265 os << "Object released by directly sending the '-dealloc' message";
2266 break;
2267 }
2268 }
2269
2270 // Specially handle CFMakeCollectable and friends.
2271 if (contains(AEffects, MakeCollectable)) {
2272 // Get the name of the function.
2273 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2274 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2275 const FunctionDecl* FD = X.getAsFunctionDecl();
2276 const std::string& FName = FD->getNameAsString();
2277
2278 if (TF.isGCEnabled()) {
2279 // Determine if the object's reference count was pushed to zero.
2280 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2281
2282 os << "In GC mode a call to '" << FName
2283 << "' decrements an object's retain count and registers the "
2284 "object with the garbage collector. ";
2285
2286 if (CurrV.getKind() == RefVal::Released) {
2287 assert(CurrV.getCount() == 0);
2288 os << "Since it now has a 0 retain count the object can be "
2289 "automatically collected by the garbage collector.";
2290 }
2291 else
2292 os << "An object must have a 0 retain count to be garbage collected. "
2293 "After this call its retain count is +" << CurrV.getCount()
2294 << '.';
2295 }
2296 else
2297 os << "When GC is not enabled a call to '" << FName
2298 << "' has no effect on its argument.";
2299
2300 // Nothing more to say.
2301 break;
2302 }
2303
2304 // Determine if the typestate has changed.
2305 if (!(PrevV == CurrV))
2306 switch (CurrV.getKind()) {
2307 case RefVal::Owned:
2308 case RefVal::NotOwned:
2309
Ted Kremenek4d99d342009-05-08 20:01:42 +00002310 if (PrevV.getCount() == CurrV.getCount()) {
2311 // Did an autorelease message get sent?
2312 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2313 return 0;
2314
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002315 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002316 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002317 break;
2318 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002319
2320 if (PrevV.getCount() > CurrV.getCount())
2321 os << "Reference count decremented.";
2322 else
2323 os << "Reference count incremented.";
2324
2325 if (unsigned Count = CurrV.getCount())
2326 os << " The object now has a +" << Count << " retain count.";
2327
2328 if (PrevV.getKind() == RefVal::Released) {
2329 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2330 os << " The object is not eligible for garbage collection until the "
2331 "retain count reaches 0 again.";
2332 }
2333
2334 break;
2335
2336 case RefVal::Released:
2337 os << "Object released.";
2338 break;
2339
2340 case RefVal::ReturnedOwned:
2341 os << "Object returned to caller as an owning reference (single retain "
2342 "count transferred to caller).";
2343 break;
2344
2345 case RefVal::ReturnedNotOwned:
2346 os << "Object returned to caller with a +0 (non-owning) retain count.";
2347 break;
2348
2349 default:
2350 return NULL;
2351 }
2352
2353 // Emit any remaining diagnostics for the argument effects (if any).
2354 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2355 E=AEffects.end(); I != E; ++I) {
2356
2357 // A bunch of things have alternate behavior under GC.
2358 if (TF.isGCEnabled())
2359 switch (*I) {
2360 default: break;
2361 case Autorelease:
2362 os << "In GC mode an 'autorelease' has no effect.";
2363 continue;
2364 case IncRefMsg:
2365 os << "In GC mode the 'retain' message has no effect.";
2366 continue;
2367 case DecRefMsg:
2368 os << "In GC mode the 'release' message has no effect.";
2369 continue;
2370 }
2371 }
2372 } while(0);
2373
2374 if (os.str().empty())
2375 return 0; // We have nothing to say!
2376
2377 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002378 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002379 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2380
2381 // Add the range by scanning the children of the statement for any bindings
2382 // to Sym.
2383 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2384 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2385 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2386 P->addRange(Exp->getSourceRange());
2387 break;
2388 }
2389
2390 return P;
2391}
2392
2393namespace {
2394 class VISIBILITY_HIDDEN FindUniqueBinding :
2395 public StoreManager::BindingsHandler {
2396 SymbolRef Sym;
2397 const MemRegion* Binding;
2398 bool First;
2399
2400 public:
2401 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2402
2403 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2404 SVal val) {
2405
2406 SymbolRef SymV = val.getAsSymbol();
2407 if (!SymV || SymV != Sym)
2408 return true;
2409
2410 if (Binding) {
2411 First = false;
2412 return false;
2413 }
2414 else
2415 Binding = R;
2416
2417 return true;
2418 }
2419
2420 operator bool() { return First && Binding; }
2421 const MemRegion* getRegion() { return Binding; }
2422 };
2423}
2424
2425static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2426GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2427 SymbolRef Sym) {
2428
2429 // Find both first node that referred to the tracked symbol and the
2430 // memory location that value was store to.
2431 const ExplodedNode<GRState>* Last = N;
2432 const MemRegion* FirstBinding = 0;
2433
2434 while (N) {
2435 const GRState* St = N->getState();
2436 RefBindings B = St->get<RefBindings>();
2437
2438 if (!B.lookup(Sym))
2439 break;
2440
2441 FindUniqueBinding FB(Sym);
2442 StateMgr.iterBindings(St, FB);
2443 if (FB) FirstBinding = FB.getRegion();
2444
2445 Last = N;
2446 N = N->pred_empty() ? NULL : *(N->pred_begin());
2447 }
2448
2449 return std::make_pair(Last, FirstBinding);
2450}
2451
2452PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002453CFRefReport::getEndPath(BugReporterContext& BRC,
2454 const ExplodedNode<GRState>* EndN) {
2455 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002456 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002457 BRC.addNotableSymbol(Sym);
2458 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002459}
2460
2461PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002462CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2463 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002464
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002465 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002466 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002467 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002468
2469 // We are reporting a leak. Walk up the graph to get to the first node where
2470 // the symbol appeared, and also get the first VarDecl that tracked object
2471 // is stored to.
2472 const ExplodedNode<GRState>* AllocNode = 0;
2473 const MemRegion* FirstBinding = 0;
2474
2475 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002476 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002477
2478 // Get the allocate site.
2479 assert(AllocNode);
2480 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2481
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002482 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002483 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2484
2485 // Compute an actual location for the leak. Sometimes a leak doesn't
2486 // occur at an actual statement (e.g., transition between blocks; end
2487 // of function) so we need to walk the graph and compute a real location.
2488 const ExplodedNode<GRState>* LeakN = EndN;
2489 PathDiagnosticLocation L;
2490
2491 while (LeakN) {
2492 ProgramPoint P = LeakN->getLocation();
2493
2494 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2495 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2496 break;
2497 }
2498 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2499 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2500 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2501 break;
2502 }
2503 }
2504
2505 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2506 }
2507
2508 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002509 const Decl &D = BRC.getCodeDecl();
2510 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002511 }
2512
2513 std::string sbuf;
2514 llvm::raw_string_ostream os(sbuf);
2515
2516 os << "Object allocated on line " << AllocLine;
2517
2518 if (FirstBinding)
2519 os << " and stored into '" << FirstBinding->getString() << '\'';
2520
2521 // Get the retain count.
2522 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2523
2524 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2525 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2526 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2527 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002528 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002529 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002530 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002531 << "') does not contain 'copy' or otherwise starts with"
2532 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002533 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002534 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002535 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2536 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2537 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002538 << "' is potentially leaked when using garbage collection. Callers "
2539 "of this method do not expect a returned object with a +1 retain "
2540 "count since they expect the object to be managed by the garbage "
2541 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002542 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002543 else
2544 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002545 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002546
2547 return new PathDiagnosticEventPiece(L, os.str());
2548}
2549
Ted Kremenek47a72422009-04-29 18:50:19 +00002550CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2551 ExplodedNode<GRState> *n,
2552 SymbolRef sym, GRExprEngine& Eng)
2553: CFRefReport(D, tf, n, sym)
2554{
2555
2556 // Most bug reports are cached at the location where they occured.
2557 // With leaks, we want to unique them by the location where they were
2558 // allocated, and only report a single path. To do this, we need to find
2559 // the allocation site of a piece of tracked memory, which we do via a
2560 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2561 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2562 // that all ancestor nodes that represent the allocation site have the
2563 // same SourceLocation.
2564 const ExplodedNode<GRState>* AllocNode = 0;
2565
2566 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002567 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002568
2569 // Get the SourceLocation for the allocation site.
2570 ProgramPoint P = AllocNode->getLocation();
2571 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2572
2573 // Fill in the description of the bug.
2574 Description.clear();
2575 llvm::raw_string_ostream os(Description);
2576 SourceManager& SMgr = Eng.getContext().getSourceManager();
2577 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002578 os << "Potential leak ";
2579 if (tf.isGCEnabled()) {
2580 os << "(when using garbage collection) ";
2581 }
2582 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002583
2584 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2585 if (AllocBinding)
2586 os << " and stored into '" << AllocBinding->getString() << '\'';
2587}
2588
2589//===----------------------------------------------------------------------===//
2590// Main checker logic.
2591//===----------------------------------------------------------------------===//
2592
Ted Kremenek272aa852008-06-25 21:21:56 +00002593/// GetReturnType - Used to get the return type of a message expression or
2594/// function call with the intention of affixing that type to a tracked symbol.
2595/// While the the return type can be queried directly from RetEx, when
2596/// invoking class methods we augment to the return type to be that of
2597/// a pointer to the class (as opposed it just being id).
2598static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2599
2600 QualType RetTy = RetE->getType();
2601
2602 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002603 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002604 if (!PT)
2605 return RetTy;
2606
2607 // If RetEx is not a message expression just return its type.
2608 // If RetEx is a message expression, return its types if it is something
2609 /// more specific than id.
2610
2611 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2612
Steve Naroff17c03822009-02-12 17:52:19 +00002613 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002614 return RetTy;
2615
2616 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2617
2618 // At this point we know the return type of the message expression is id.
2619 // If we have an ObjCInterceDecl, we know this is a call to a class method
2620 // whose type we can resolve. In such cases, promote the return type to
2621 // Class*.
2622 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2623}
2624
2625
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002626void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002627 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002628 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002629 Expr* Ex,
2630 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002631 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002632 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002633 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002634
Ted Kremeneka7338b42008-03-11 06:39:11 +00002635 // Get the state.
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002636 GRStateManager& StateMgr = Eng.getStateManager();
2637 GRStateRef state(Builder.GetState(Pred), StateMgr);
2638 ASTContext& Ctx = StateMgr.getContext();
2639 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek227c5372008-05-06 02:41:27 +00002640
2641 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002642 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002643 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002644 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002645 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002646
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002647 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002648 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002649 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002650
Ted Kremenek74556a12009-03-26 03:35:11 +00002651 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002652 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002653 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002654 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002655 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002656 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002657 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002658 }
2659 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002660 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002661
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002662 if (isa<Loc>(V)) {
2663 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002664 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002665 continue;
2666
2667 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002668
2669 // FIXME: Either this logic should also be replicated in GRSimpleVals
2670 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002671
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002672 // FIXME: We can have collisions on the conjured symbol if the
2673 // expression *I also creates conjured symbols. We probably want
2674 // to identify conjured symbols by an expression pair: the enclosing
2675 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002676 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002677
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002678 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002679
Ted Kremenek73ec7732009-05-06 18:19:24 +00002680 if (R) {
2681 // Are we dealing with an ElementRegion? If the element type is
2682 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xuea6851b2009-05-11 14:28:14 +00002683 // is a variable region then strip off the ElementRegion.
Ted Kremenek73ec7732009-05-06 18:19:24 +00002684 // FIXME: We really need to think about this for the general case
2685 // as sometimes we are reasoning about arrays and other times
2686 // about (char*), etc., is just a form of passing raw bytes.
2687 // e.g., void *p = alloca(); foo((char*)p);
2688 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2689 // Checking for 'integral type' is probably too promiscuous, but
2690 // we'll leave it in for now until we have a systematic way of
2691 // handling all of these cases. Eventually we need to come up
2692 // with an interface to StoreManager so that this logic can be
2693 // approriately delegated to the respective StoreManagers while
2694 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002695 // invalidating reference counts), probably via callbacks.
Ted Kremenek1cba5772009-05-11 22:55:17 +00002696 if (ER->getElementType()->isIntegralType()) {
2697 const MemRegion *superReg = ER->getSuperRegion();
2698 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2699 isa<ObjCIvarRegion>(superReg))
2700 R = cast<TypedRegion>(superReg);
2701 }
2702
Ted Kremenek73ec7732009-05-06 18:19:24 +00002703 // FIXME: What about layers of ElementRegions?
2704 }
2705
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002706 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002707 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002708
Ted Kremenek53b24182009-03-04 22:56:43 +00002709 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002710 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002711
Ted Kremenek53b24182009-03-04 22:56:43 +00002712 if (R->isBoundable(Ctx)) {
2713 // Set the value of the variable to be a conjured symbol.
2714 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002715 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002716
Zhongxing Xu079dc352009-04-09 06:03:54 +00002717 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002718 ValueManager &ValMgr = Eng.getValueManager();
2719 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002720 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002721 }
2722 else if (const RecordType *RT = T->getAsStructureType()) {
2723 // Handle structs in a not so awesome way. Here we just
2724 // eagerly bind new symbols to the fields. In reality we
2725 // should have the store manager handle this. The idea is just
2726 // to prototype some basic functionality here. All of this logic
2727 // should one day soon just go away.
2728 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2729
2730 // No record definition. There is nothing we can do.
2731 if (!RD)
2732 continue;
2733
2734 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2735
2736 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002737 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2738 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002739
2740 // For now just handle scalar fields.
2741 FieldDecl *FD = *FI;
2742 QualType FT = FD->getType();
2743
2744 if (Loc::IsLocType(FT) ||
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002745 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002746 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002747
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002748 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002749 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002750 }
2751 }
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002752 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2753 // Set the default value of the array to conjured symbol.
2754 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2755 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2756 Count);
2757 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2758 StateMgr);
2759 } else {
Ted Kremenek53b24182009-03-04 22:56:43 +00002760 // Just blast away other values.
2761 state = state.BindLoc(*MR, UnknownVal());
2762 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002763 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002764 }
2765 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002766 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002767 }
2768 else {
2769 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002770 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002771 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002772 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002773 else if (isa<nonloc::LocAsInteger>(V))
2774 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002775 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002776
Ted Kremenek272aa852008-06-25 21:21:56 +00002777 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002778 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002779 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002780 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002781 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002782 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002783 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002784 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002785 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002786 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002787 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002788 }
2789 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002790
Ted Kremenek272aa852008-06-25 21:21:56 +00002791 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002792 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002793 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002794 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002795 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002796 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002797
Ted Kremenekf2717b02008-07-18 17:24:20 +00002798 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002799 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002800
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002801 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2802 assert(Receiver);
2803 SVal V = state.GetSValAsScalarOrLoc(Receiver);
2804 bool found = false;
2805 if (SymbolRef Sym = V.getAsLocSymbol())
2806 if (state.get<RefBindings>(Sym)) {
2807 found = true;
2808 RE = Summaries.getObjAllocRetEffect();
2809 }
2810
2811 if (!found)
2812 RE = RetEffect::MakeNoRet();
2813 }
2814
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002815 switch (RE.getKind()) {
2816 default:
2817 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002818
Ted Kremenek8f90e712008-10-17 22:23:12 +00002819 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002820
Ted Kremenek455dd862008-04-11 20:23:24 +00002821 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002822 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2823 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002824
Ted Kremenek8f90e712008-10-17 22:23:12 +00002825 // FIXME: We eventually should handle structs and other compound types
2826 // that are returned by value.
2827
2828 QualType T = Ex->getType();
2829
Ted Kremenek79413a52008-11-13 06:10:40 +00002830 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002831 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002832 ValueManager &ValMgr = Eng.getValueManager();
2833 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002834 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002835 }
2836
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002837 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002838 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002839
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002840 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002841 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002842 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002843 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002844 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002845 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002846 break;
2847 }
2848
Ted Kremenek227c5372008-05-06 02:41:27 +00002849 case RetEffect::ReceiverAlias: {
2850 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002851 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002852 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002853 break;
2854 }
2855
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002856 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002857 case RetEffect::OwnedSymbol: {
2858 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002859 ValueManager &ValMgr = Eng.getValueManager();
2860 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2861 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2862 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2863 RetT));
2864 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002865
2866 // FIXME: Add a flag to the checker where allocations are assumed to
2867 // *not fail.
2868#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002869 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2870 bool isFeasible;
2871 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2872 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2873 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002874#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002875
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002876 break;
2877 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002878
2879 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002880 case RetEffect::NotOwnedSymbol: {
2881 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002882 ValueManager &ValMgr = Eng.getValueManager();
2883 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2884 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2885 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2886 RetT));
2887 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002888 break;
2889 }
2890 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002891
Ted Kremenek0dd65012009-02-18 02:00:25 +00002892 // Generate a sink node if we are at the end of a path.
2893 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002894 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2895 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002896
2897 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002898 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002899}
2900
2901
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002902void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002903 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002904 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002905 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002906 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002907 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002908 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002909 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002910
Ted Kremenek286e9852009-05-04 04:57:00 +00002911 assert(Summ);
2912 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002913 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002914}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002915
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002916void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002917 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002918 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002919 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002920 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002921 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002922
Ted Kremenek272aa852008-06-25 21:21:56 +00002923 if (Expr* Receiver = ME->getReceiver()) {
2924 // We need the type-information of the tracked receiver object
2925 // Retrieve it from the state.
2926 ObjCInterfaceDecl* ID = 0;
2927
2928 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2929 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002930 // FIXME: Is this really working as expected? There are cases where
2931 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002932 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002933 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002934
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002935 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002936 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002937 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002938 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002939
2940 if (const PointerType* PT = Ty->getAsPointerType()) {
2941 QualType PointeeTy = PT->getPointeeType();
2942
2943 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2944 ID = IT->getDecl();
2945 }
2946 }
2947 }
2948
Ted Kremenek04e00302009-04-29 17:09:14 +00002949 // FIXME: The receiver could be a reference to a class, meaning that
2950 // we should use the class method.
2951 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002952
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002953 // Special-case: are we sending a mesage to "self"?
2954 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002955 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2956 if (Expr* Receiver = ME->getReceiver()) {
2957 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2958 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2959 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2960 // Update the summary to make the default argument effect
2961 // 'StopTracking'.
2962 Summ = Summaries.copySummary(Summ);
2963 Summ->setDefaultArgEffect(StopTracking);
2964 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002965 }
2966 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002967 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002968 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002969 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002970
Ted Kremenek286e9852009-05-04 04:57:00 +00002971 if (!Summ)
2972 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002973
Ted Kremenek286e9852009-05-04 04:57:00 +00002974 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002975 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002976}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002977
2978namespace {
2979class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2980 GRStateRef state;
2981public:
2982 StopTrackingCallback(GRStateRef st) : state(st) {}
2983 GRStateRef getState() { return state; }
2984
2985 bool VisitSymbol(SymbolRef sym) {
2986 state = state.remove<RefBindings>(sym);
2987 return true;
2988 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002989
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002990 const GRState* getState() const { return state.getState(); }
2991};
2992} // end anonymous namespace
2993
2994
Ted Kremeneka42be302009-02-14 01:43:44 +00002995void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002996 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002997 bool escapes = false;
2998
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002999 // A value escapes in three possible cases (this may change):
3000 //
3001 // (1) we are binding to something that is not a memory region.
3002 // (2) we are binding to a memregion that does not have stack storage
3003 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003004 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00003005 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003006
Ted Kremeneka42be302009-02-14 01:43:44 +00003007 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003008 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003009 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003010 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3011 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003012
3013 if (!escapes) {
3014 // To test (3), generate a new state with the binding removed. If it is
3015 // the same state, then it escapes (since the store cannot represent
3016 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00003017 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003018 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003019 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003020
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003021 // If our store can represent the binding and we aren't storing to something
3022 // that doesn't have local storage then just return and have the simulation
3023 // state continue as is.
3024 if (!escapes)
3025 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003026
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003027 // Otherwise, find all symbols referenced by 'val' that we are tracking
3028 // and stop tracking them.
3029 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003030}
3031
Ted Kremenek541db372008-04-24 23:57:27 +00003032
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003033 // Return statements.
3034
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003035void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003036 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003037 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003038 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003039 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003040
3041 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003042 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003043 return;
3044
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003045 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00003046 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003047
Ted Kremenek74556a12009-03-26 03:35:11 +00003048 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003049 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003050
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003051 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003052 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003053
3054 if (!T)
3055 return;
3056
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003057 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003058 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003059
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003060 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003061 case RefVal::Owned: {
3062 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003063 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003064 X.setCount(cnt - 1);
3065 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003066 break;
3067 }
3068
3069 case RefVal::NotOwned: {
3070 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003071 if (cnt) {
3072 X.setCount(cnt - 1);
3073 X = X ^ RefVal::ReturnedOwned;
3074 }
3075 else {
3076 X = X ^ RefVal::ReturnedNotOwned;
3077 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003078 break;
3079 }
3080
3081 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003082 return;
3083 }
3084
3085 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003086 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003087 Pred = Builder.MakeNode(Dst, S, Pred, state);
3088
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003089 // Did we cache out?
3090 if (!Pred)
3091 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003092
3093 // Update the autorelease counts.
3094 static unsigned autoreleasetag = 0;
3095 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3096 bool stop = false;
3097 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3098 X, stop);
3099
3100 // Did we cache out?
3101 if (!Pred || stop)
3102 return;
3103
3104 // Get the updated binding.
3105 T = state.get<RefBindings>(Sym);
3106 assert(T);
3107 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003108
Ted Kremenek47a72422009-04-29 18:50:19 +00003109 // Any leaks or other errors?
3110 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003111 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003112 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003113 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003114 RetEffect RE = Summ.getRetEffect();
3115 bool hasError = false;
3116
3117 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3118 // Things are more complicated with garbage collection. If the
3119 // returned object is suppose to be an Objective-C object, we have
Ted Kremenekeaea6582009-05-10 16:52:15 +00003120 // a leak (as the caller expects a GC'ed object) because no
3121 // method should return ownership unless it returns a CF object.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003122 X = X ^ RefVal::ErrorGCLeakReturned;
3123
3124 // Keep this false until this is properly tested.
Ted Kremenekeaea6582009-05-10 16:52:15 +00003125 hasError = true;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003126 }
3127 else if (!RE.isOwned()) {
3128 // Either we are using GC and the returned object is a CF type
3129 // or we aren't using GC. In either case, we expect that the
3130 // enclosing method is expected to return ownership.
3131 hasError = true;
3132 X = X ^ RefVal::ErrorLeakReturned;
3133 }
3134
3135 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003136 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003137 static int ReturnOwnLeakTag = 0;
3138 state = state.set<RefBindings>(Sym, X);
3139 ExplodedNode<GRState> *N =
3140 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3141 if (N) {
3142 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003143 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3144 N, Sym, Eng);
3145 BR->EmitReport(report);
3146 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003147 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003148 }
3149 }
3150 else if (X.isReturnedNotOwned()) {
3151 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3152 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3153 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3154 if (Summ.getRetEffect().isOwned()) {
3155 // Trying to return a not owned object to a caller expecting an
3156 // owned object.
3157
3158 static int ReturnNotOwnedForOwnedTag = 0;
3159 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3160 if (ExplodedNode<GRState> *N =
3161 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3162 state, Pred)) {
3163 CFRefReport *report =
3164 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3165 *this, N, Sym);
3166 BR->EmitReport(report);
3167 }
3168 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003169 }
3170 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003171}
3172
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003173// Assumptions.
3174
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003175const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3176 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003177 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003178 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003179
3180 // FIXME: We may add to the interface of EvalAssume the list of symbols
3181 // whose assumptions have changed. For now we just iterate through the
3182 // bindings and check if any of the tracked symbols are NULL. This isn't
3183 // too bad since the number of symbols we will track in practice are
3184 // probably small and EvalAssume is only called at branches and a few
3185 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003186 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003187
3188 if (B.isEmpty())
3189 return St;
3190
3191 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003192
3193 GRStateRef state(St, VMgr);
3194 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003195
3196 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003197 // Check if the symbol is null (or equal to any constant).
3198 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003199 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003200 changed = true;
3201 B = RefBFactory.Remove(B, I.getKey());
3202 }
3203 }
3204
Ted Kremenek91781202008-08-17 03:20:02 +00003205 if (changed)
3206 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003207
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003208 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003209}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003210
Ted Kremenekb6578942009-02-24 19:15:11 +00003211GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3212 RefVal V, ArgEffect E,
3213 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003214
3215 // In GC mode [... release] and [... retain] do nothing.
3216 switch (E) {
3217 default: break;
3218 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3219 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003220 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003221 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3222 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003223 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003224
Ted Kremenek6537a642009-03-17 19:42:23 +00003225 // Handle all use-after-releases.
3226 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3227 V = V ^ RefVal::ErrorUseAfterRelease;
3228 hasErr = V.getKind();
3229 return state.set<RefBindings>(sym, V);
3230 }
3231
Ted Kremenek0d721572008-03-11 17:48:22 +00003232 switch (E) {
3233 default:
3234 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003235
3236 case Dealloc:
3237 // Any use of -dealloc in GC is *bad*.
3238 if (isGCEnabled()) {
3239 V = V ^ RefVal::ErrorDeallocGC;
3240 hasErr = V.getKind();
3241 break;
3242 }
3243
3244 switch (V.getKind()) {
3245 default:
3246 assert(false && "Invalid case.");
3247 case RefVal::Owned:
3248 // The object immediately transitions to the released state.
3249 V = V ^ RefVal::Released;
3250 V.clearCounts();
3251 return state.set<RefBindings>(sym, V);
3252 case RefVal::NotOwned:
3253 V = V ^ RefVal::ErrorDeallocNotOwned;
3254 hasErr = V.getKind();
3255 break;
3256 }
3257 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003258
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003259 case NewAutoreleasePool:
3260 assert(!isGCEnabled());
3261 return state.add<AutoreleaseStack>(sym);
3262
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003263 case MayEscape:
3264 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003265 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003266 break;
3267 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003268
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003269 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003270
Ted Kremenekede40b72008-07-09 18:11:16 +00003271 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003272 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003273 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003274
Ted Kremenek9b112d22009-01-28 21:44:40 +00003275 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003276 if (isGCEnabled())
3277 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003278
3279 // Update the autorelease counts.
3280 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003281 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003282 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003283
Ted Kremenek227c5372008-05-06 02:41:27 +00003284 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003285 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003286
Ted Kremenek0d721572008-03-11 17:48:22 +00003287 case IncRef:
3288 switch (V.getKind()) {
3289 default:
3290 assert(false);
3291
3292 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003293 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003294 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003295 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003296 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003297 // Non-GC cases are handled above.
3298 assert(isGCEnabled());
3299 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003300 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003301 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003302 break;
3303
Ted Kremenek272aa852008-06-25 21:21:56 +00003304 case SelfOwn:
3305 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003306 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003307 case DecRef:
3308 switch (V.getKind()) {
3309 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003310 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003311 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003312
Ted Kremenek272aa852008-06-25 21:21:56 +00003313 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003314 assert(V.getCount() > 0);
3315 if (V.getCount() == 1) V = V ^ RefVal::Released;
3316 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003317 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003318
Ted Kremenek272aa852008-06-25 21:21:56 +00003319 case RefVal::NotOwned:
3320 if (V.getCount() > 0)
3321 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003322 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003323 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003324 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003325 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003326 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003327
Ted Kremenek0d721572008-03-11 17:48:22 +00003328 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003329 // Non-GC cases are handled above.
3330 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003331 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003332 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003333 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003334 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003335 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003336 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003337 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003338}
3339
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003340//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003341// Handle dead symbols and end-of-path.
3342//===----------------------------------------------------------------------===//
3343
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003344std::pair<ExplodedNode<GRState>*, GRStateRef>
3345CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3346 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003347 GRExprEngine &Eng,
3348 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003349
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003350 unsigned ACnt = V.getAutoreleaseCount();
3351 stop = false;
3352
3353 // No autorelease counts? Nothing to be done.
3354 if (!ACnt)
3355 return std::make_pair(Pred, state);
3356
3357 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3358 unsigned Cnt = V.getCount();
3359
Ted Kremenek0603cf52009-05-11 15:26:06 +00003360 // FIXME: Handle sending 'autorelease' to already released object.
3361
3362 if (V.getKind() == RefVal::ReturnedOwned)
3363 ++Cnt;
3364
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003365 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003366 if (ACnt == Cnt) {
3367 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003368 if (V.getKind() == RefVal::ReturnedOwned)
3369 V = V ^ RefVal::ReturnedNotOwned;
3370 else
3371 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003372 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003373 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003374 V.setCount(Cnt - ACnt);
3375 V.setAutoreleaseCount(0);
3376 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003377 state = state.set<RefBindings>(Sym, V);
3378 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3379 stop = (N == 0);
3380 return std::make_pair(N, state);
3381 }
3382
3383 // Woah! More autorelease counts then retain counts left.
3384 // Emit hard error.
3385 stop = true;
3386 V = V ^ RefVal::ErrorOverAutorelease;
3387 state = state.set<RefBindings>(Sym, V);
3388
3389 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003390 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003391
3392 std::string sbuf;
3393 llvm::raw_string_ostream os(sbuf);
3394 os << "Object over-autoreleased: object was sent -autorelease " ;
3395 if (V.getAutoreleaseCount() > 1)
3396 os << V.getAutoreleaseCount() << " times";
3397 os << " but the object has ";
3398 if (V.getCount() == 0)
3399 os << "zero (locally visible)";
3400 else
3401 os << "+" << V.getCount();
3402 os << " retain counts";
3403
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003404 CFRefReport *report =
3405 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003406 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003407 BR->EmitReport(report);
3408 }
3409
3410 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003411}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003412
3413GRStateRef
3414CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3415 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3416
3417 bool hasLeak = V.isOwned() ||
3418 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3419
3420 if (!hasLeak)
3421 return state.remove<RefBindings>(sid);
3422
3423 Leaked.push_back(sid);
3424 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3425}
3426
3427ExplodedNode<GRState>*
3428CFRefCount::ProcessLeaks(GRStateRef state,
3429 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3430 GenericNodeBuilder &Builder,
3431 GRExprEngine& Eng,
3432 ExplodedNode<GRState> *Pred) {
3433
3434 if (Leaked.empty())
3435 return Pred;
3436
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003437 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003438 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003439
3440 if (N) {
3441 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3442 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3443
3444 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3445 : leakAtReturn);
3446 assert(BT && "BugType not initialized.");
3447 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3448 BR->EmitReport(report);
3449 }
3450 }
3451
3452 return N;
3453}
3454
Ted Kremenek708af042009-02-05 06:50:21 +00003455void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3456 GREndPathNodeBuilder<GRState>& Builder) {
3457
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003458 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003459 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003460 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003461 ExplodedNode<GRState> *Pred = 0;
3462
3463 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003464 bool stop = false;
3465 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3466 (*I).first,
3467 (*I).second, stop);
3468
3469 if (stop)
3470 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003471 }
3472
3473 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003474 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003475
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003476 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3477 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3478
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003479 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003480}
3481
3482void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3483 GRExprEngine& Eng,
3484 GRStmtNodeBuilder<GRState>& Builder,
3485 ExplodedNode<GRState>* Pred,
3486 Stmt* S,
3487 const GRState* St,
3488 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003489
3490 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003491 RefBindings B = state.get<RefBindings>();
3492
3493 // Update counts from autorelease pools
3494 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3495 E = SymReaper.dead_end(); I != E; ++I) {
3496 SymbolRef Sym = *I;
3497 if (const RefVal* T = B.lookup(Sym)){
3498 // Use the symbol as the tag.
3499 // FIXME: This might not be as unique as we would like.
3500 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003501 bool stop = false;
3502 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3503 Sym, *T, stop);
3504 if (stop)
3505 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003506 }
3507 }
3508
3509 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003510 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003511
3512 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003513 E = SymReaper.dead_end(); I != E; ++I) {
3514 if (const RefVal* T = B.lookup(*I))
3515 state = HandleSymbolDeath(state, *I, *T, Leaked);
3516 }
Ted Kremenek708af042009-02-05 06:50:21 +00003517
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003518 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003519 {
3520 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3521 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3522 }
Ted Kremenek708af042009-02-05 06:50:21 +00003523
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003524 // Did we cache out?
3525 if (!Pred)
3526 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003527
3528 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003529 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003530
Ted Kremenek876d8df2009-02-19 23:47:02 +00003531 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003532 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3533
Ted Kremenek876d8df2009-02-19 23:47:02 +00003534 state = state.set<RefBindings>(B);
3535 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003536}
3537
3538void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3539 GRStmtNodeBuilder<GRState>& Builder,
3540 Expr* NodeExpr, Expr* ErrorExpr,
3541 ExplodedNode<GRState>* Pred,
3542 const GRState* St,
3543 RefVal::Kind hasErr, SymbolRef Sym) {
3544 Builder.BuildSinks = true;
3545 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3546
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003547 if (!N)
3548 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003549
3550 CFRefBug *BT = 0;
3551
Ted Kremenek6537a642009-03-17 19:42:23 +00003552 switch (hasErr) {
3553 default:
3554 assert(false && "Unhandled error.");
3555 return;
3556 case RefVal::ErrorUseAfterRelease:
3557 BT = static_cast<CFRefBug*>(useAfterRelease);
3558 break;
3559 case RefVal::ErrorReleaseNotOwned:
3560 BT = static_cast<CFRefBug*>(releaseNotOwned);
3561 break;
3562 case RefVal::ErrorDeallocGC:
3563 BT = static_cast<CFRefBug*>(deallocGC);
3564 break;
3565 case RefVal::ErrorDeallocNotOwned:
3566 BT = static_cast<CFRefBug*>(deallocNotOwned);
3567 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003568 }
3569
Ted Kremenekc26c4692009-02-18 03:48:14 +00003570 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003571 report->addRange(ErrorExpr->getSourceRange());
3572 BR->EmitReport(report);
3573}
3574
3575//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003576// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003577//===----------------------------------------------------------------------===//
3578
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003579GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3580 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003581 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003582}