blob: 215be47086761342f07ec1bfaaf8630da47e05c2 [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
Ted Kremenek613ef972009-05-15 15:49:00 +000079static NamingConvention deriveNamingConvention(Selector S) {
80 IdentifierInfo *II = S.getIdentifierInfoForSlot(0);
81
82 if (!II)
83 return NoConvention;
84
85 const char *s = II->getName();
86
Ted Kremenek4395b452009-02-21 05:13:43 +000087 // A method/function name may contain a prefix. We don't know it is there,
88 // however, until we encounter the first '_'.
89 bool InPossiblePrefix = true;
90 bool AtBeginning = true;
91 NamingConvention C = NoConvention;
92
93 while (*s != '\0') {
94 // Skip '_'.
95 if (*s == '_') {
96 if (InPossiblePrefix) {
97 InPossiblePrefix = false;
98 AtBeginning = true;
99 // Discard whatever 'convention' we
100 // had already derived since it occurs
101 // in the prefix.
102 C = NoConvention;
103 }
104 ++s;
105 continue;
106 }
107
108 // Skip numbers, ':', etc.
109 if (!isalpha(*s)) {
110 ++s;
111 continue;
112 }
113
114 const char *wordEnd = parseWord(s);
115 assert(wordEnd > s);
116 unsigned len = wordEnd - s;
117
118 switch (len) {
119 default:
120 break;
121 case 3:
122 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000123 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000124 C = CreateRule;
125 break;
126 case 4:
127 // Methods starting with 'alloc' or contain 'copy' follow the
128 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000129 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000130 C = CreateRule;
131 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000132 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000133 C = InitRule;
134 break;
135 case 5:
136 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
137 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000138 break;
139 }
140
141 // If we aren't in the prefix and have a derived convention then just
142 // return it now.
143 if (!InPossiblePrefix && C != NoConvention)
144 return C;
145
146 AtBeginning = false;
147 s = wordEnd;
148 }
149
150 // We will get here if there wasn't more than one word
151 // after the prefix.
152 return C;
153}
154
Ted Kremenek613ef972009-05-15 15:49:00 +0000155static bool followsFundamentalRule(Selector S) {
156 return deriveNamingConvention(S) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000157}
158
Ted Kremenek314b1952009-04-29 23:03:22 +0000159static const ObjCMethodDecl*
160ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
161 ObjCInterfaceDecl *ID =
162 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
163
164 return MD->isInstanceMethod()
165 ? ID->lookupInstanceMethod(Context, MD->getSelector())
166 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000167}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000168
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000169namespace {
170class VISIBILITY_HIDDEN GenericNodeBuilder {
171 GRStmtNodeBuilder<GRState> *SNB;
172 Stmt *S;
173 const void *tag;
174 GREndPathNodeBuilder<GRState> *ENB;
175public:
176 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
177 const void *t)
178 : SNB(&snb), S(s), tag(t), ENB(0) {}
179 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
180 : SNB(0), S(0), tag(0), ENB(&enb) {}
181
182 ExplodedNode<GRState> *MakeNode(const GRState *state,
183 ExplodedNode<GRState> *Pred) {
184 if (SNB)
Ted Kremenek3e3328d2009-05-09 01:50:57 +0000185 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000186
187 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000188 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000189 }
190};
191} // end anonymous namespace
192
Ted Kremenek7d421f32008-04-09 23:49:11 +0000193//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000194// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000195//===----------------------------------------------------------------------===//
196
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000197static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000198 IdentifierInfo* II = &Ctx.Idents.get(name);
199 return Ctx.Selectors.getSelector(0, &II);
200}
201
Ted Kremenek0e344d42008-05-06 00:30:21 +0000202static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
203 IdentifierInfo* II = &Ctx.Idents.get(name);
204 return Ctx.Selectors.getSelector(1, &II);
205}
206
Ted Kremenek272aa852008-06-25 21:21:56 +0000207//===----------------------------------------------------------------------===//
208// Type querying functions.
209//===----------------------------------------------------------------------===//
210
Ted Kremenek17144e82009-01-12 21:45:02 +0000211static bool hasPrefix(const char* s, const char* prefix) {
212 if (!prefix)
213 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000214
Ted Kremenek17144e82009-01-12 21:45:02 +0000215 char c = *s;
216 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000217
Ted Kremenek17144e82009-01-12 21:45:02 +0000218 while (c != '\0' && cP != '\0') {
219 if (c != cP) break;
220 c = *(++s);
221 cP = *(++prefix);
222 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000223
Ted Kremenek17144e82009-01-12 21:45:02 +0000224 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000225}
226
Ted Kremenek17144e82009-01-12 21:45:02 +0000227static bool hasSuffix(const char* s, const char* suffix) {
228 const char* loc = strstr(s, suffix);
229 return loc && strcmp(suffix, loc) == 0;
230}
231
232static bool isRefType(QualType RetTy, const char* prefix,
233 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000234
Ted Kremenek2f289b62009-05-12 04:53:03 +0000235 // Recursively walk the typedef stack, allowing typedefs of reference types.
236 while (1) {
237 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
238 const char* TDName = TD->getDecl()->getIdentifier()->getName();
239 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
240 return true;
241
242 RetTy = TD->getDecl()->getUnderlyingType();
243 continue;
244 }
245 break;
Ted Kremenek17144e82009-01-12 21:45:02 +0000246 }
247
248 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000249 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000250
251 // Is the type void*?
252 const PointerType* PT = RetTy->getAsPointerType();
253 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000254 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000255
256 // Does the name start with the prefix?
257 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000258}
259
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000260//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000261// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000262//===----------------------------------------------------------------------===//
263
Ted Kremenek272aa852008-06-25 21:21:56 +0000264/// ArgEffect is used to summarize a function/method call's effect on a
265/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000266enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
267 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
268 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000269
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000271template <> struct FoldingSetTrait<ArgEffect> {
272static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
273 ID.AddInteger((unsigned) X);
274}
Ted Kremenek272aa852008-06-25 21:21:56 +0000275};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000276} // end llvm namespace
277
Ted Kremeneka56ae162009-05-03 05:20:50 +0000278/// ArgEffects summarizes the effects of a function/method call on all of
279/// its arguments.
280typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
281
Ted Kremeneka7338b42008-03-11 06:39:11 +0000282namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000283
284/// RetEffect is used to summarize a function/method call's behavior with
285/// respect to its return value.
286class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000287public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000288 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000289 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
290 OwnedWhenTrackedReceiver };
Ted Kremenek68621b92009-01-28 05:56:51 +0000291
292 enum ObjKind { CF, ObjC, AnyObj };
293
Ted Kremeneka7338b42008-03-11 06:39:11 +0000294private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000295 Kind K;
296 ObjKind O;
297 unsigned index;
298
299 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
300 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000301
Ted Kremeneka7338b42008-03-11 06:39:11 +0000302public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000303 Kind getKind() const { return K; }
304
305 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000306
307 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000308 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000309 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000310 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000311
Ted Kremenek314b1952009-04-29 23:03:22 +0000312 bool isOwned() const {
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000313 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
314 K == OwnedWhenTrackedReceiver;
Ted Kremenek314b1952009-04-29 23:03:22 +0000315 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +0000316
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000317 static RetEffect MakeOwnedWhenTrackedReceiver() {
318 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
319 }
320
Ted Kremenek272aa852008-06-25 21:21:56 +0000321 static RetEffect MakeAlias(unsigned Idx) {
322 return RetEffect(Alias, Idx);
323 }
324 static RetEffect MakeReceiverAlias() {
325 return RetEffect(ReceiverAlias);
326 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000327 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
328 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000329 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000330 static RetEffect MakeNotOwned(ObjKind o) {
331 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000332 }
333 static RetEffect MakeGCNotOwned() {
334 return RetEffect(GCNotOwnedSymbol, ObjC);
335 }
336
Ted Kremenek272aa852008-06-25 21:21:56 +0000337 static RetEffect MakeNoRet() {
338 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000339 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000340
Ted Kremenek272aa852008-06-25 21:21:56 +0000341 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000342 ID.AddInteger((unsigned)K);
343 ID.AddInteger((unsigned)O);
344 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000345 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000346};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000347
Ted Kremenek272aa852008-06-25 21:21:56 +0000348
Ted Kremenek2f226732009-05-04 05:31:22 +0000349class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000350 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
351 /// specifies the argument (starting from 0). This can be sparsely
352 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000354
355 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
356 /// do not have an entry in Args.
357 ArgEffect DefaultArgEffect;
358
Ted Kremenek272aa852008-06-25 21:21:56 +0000359 /// Receiver - If this summary applies to an Objective-C message expression,
360 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000361 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000362
363 /// Ret - The effect on the return value. Used to indicate if the
364 /// function/method call returns a new tracked symbol, returns an
365 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000366 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000367
Ted Kremenekf2717b02008-07-18 17:24:20 +0000368 /// EndPath - Indicates that execution of this method/function should
369 /// terminate the simulation of a path.
370 bool EndPath;
371
Ted Kremeneka7338b42008-03-11 06:39:11 +0000372public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000373 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000374 ArgEffect ReceiverEff, bool endpath = false)
375 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
376 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000377
Ted Kremenek272aa852008-06-25 21:21:56 +0000378 /// getArg - Return the argument effect on the argument specified by
379 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000380 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000381 if (const ArgEffect *AE = Args.lookup(idx))
382 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000383
Ted Kremenekbcaff792008-05-06 15:44:25 +0000384 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000385 }
386
Ted Kremenek2f226732009-05-04 05:31:22 +0000387 /// setDefaultArgEffect - Set the default argument effect.
388 void setDefaultArgEffect(ArgEffect E) {
389 DefaultArgEffect = E;
390 }
391
392 /// setArg - Set the argument effect on the argument specified by idx.
393 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
394 Args = AF.Add(Args, idx, E);
395 }
396
Ted Kremenek272aa852008-06-25 21:21:56 +0000397 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000398 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000399
Ted Kremenek2f226732009-05-04 05:31:22 +0000400 /// setRetEffect - Set the effect of the return value of the call.
401 void setRetEffect(RetEffect E) { Ret = E; }
402
Ted Kremenekf2717b02008-07-18 17:24:20 +0000403 /// isEndPath - Returns true if executing the given method/function should
404 /// terminate the path.
405 bool isEndPath() const { return EndPath; }
406
Ted Kremenek272aa852008-06-25 21:21:56 +0000407 /// getReceiverEffect - Returns the effect on the receiver of the call.
408 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000409 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000410
Ted Kremenek2f226732009-05-04 05:31:22 +0000411 /// setReceiverEffect - Set the effect on the receiver of the call.
412 void setReceiverEffect(ArgEffect E) { Receiver = E; }
413
Ted Kremeneka56ae162009-05-03 05:20:50 +0000414 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000415
Ted Kremeneka56ae162009-05-03 05:20:50 +0000416 ExprIterator begin_args() const { return Args.begin(); }
417 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000418
Ted Kremeneka56ae162009-05-03 05:20:50 +0000419 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000420 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000421 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000422 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000423 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000424 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000425 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000426 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000427 }
428
429 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000430 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000431 }
432};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000433} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000434
Ted Kremenek272aa852008-06-25 21:21:56 +0000435//===----------------------------------------------------------------------===//
436// Data structures for constructing summaries.
437//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000438
Ted Kremenek272aa852008-06-25 21:21:56 +0000439namespace {
440class VISIBILITY_HIDDEN ObjCSummaryKey {
441 IdentifierInfo* II;
442 Selector S;
443public:
444 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
445 : II(ii), S(s) {}
446
Ted Kremenek314b1952009-04-29 23:03:22 +0000447 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000448 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +0000449
450 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
451 : II(d ? d->getIdentifier() : ii), S(s) {}
Ted Kremenek272aa852008-06-25 21:21:56 +0000452
453 ObjCSummaryKey(Selector s)
454 : II(0), S(s) {}
455
456 IdentifierInfo* getIdentifier() const { return II; }
457 Selector getSelector() const { return S; }
458};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000459}
460
461namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000462template <> struct DenseMapInfo<ObjCSummaryKey> {
463 static inline ObjCSummaryKey getEmptyKey() {
464 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
465 DenseMapInfo<Selector>::getEmptyKey());
466 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000467
Ted Kremenek272aa852008-06-25 21:21:56 +0000468 static inline ObjCSummaryKey getTombstoneKey() {
469 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
470 DenseMapInfo<Selector>::getTombstoneKey());
471 }
472
473 static unsigned getHashValue(const ObjCSummaryKey &V) {
474 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
475 & 0x88888888)
476 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
477 & 0x55555555);
478 }
479
480 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
481 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
482 RHS.getIdentifier()) &&
483 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
484 RHS.getSelector());
485 }
486
487 static bool isPod() {
488 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
489 DenseMapInfo<Selector>::isPod();
490 }
491};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000492} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000493
Ted Kremenek84f010c2008-06-23 23:30:29 +0000494namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000495class VISIBILITY_HIDDEN ObjCSummaryCache {
496 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
497 MapTy M;
498public:
499 ObjCSummaryCache() {}
500
501 typedef MapTy::iterator iterator;
502
Ted Kremenek314b1952009-04-29 23:03:22 +0000503 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
504 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000505 // Lookup the method using the decl for the class @interface. If we
506 // have no decl, lookup using the class name.
507 return D ? find(D, S) : find(ClsName, S);
508 }
509
Ted Kremenek314b1952009-04-29 23:03:22 +0000510 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000511 // Do a lookup with the (D,S) pair. If we find a match return
512 // the iterator.
513 ObjCSummaryKey K(D, S);
514 MapTy::iterator I = M.find(K);
515
516 if (I != M.end() || !D)
517 return I;
518
519 // Walk the super chain. If we find a hit with a parent, we'll end
520 // up returning that summary. We actually allow that key (null,S), as
521 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
522 // generate initial summaries without having to worry about NSObject
523 // being declared.
524 // FIXME: We may change this at some point.
525 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
526 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
527 break;
528
529 if (!C)
530 return I;
531 }
532
533 // Cache the summary with original key to make the next lookup faster
534 // and return the iterator.
535 M[K] = I->second;
536 return I;
537 }
538
Ted Kremenek9449ca92008-08-12 20:41:56 +0000539
Ted Kremenek272aa852008-06-25 21:21:56 +0000540 iterator find(Expr* Receiver, Selector S) {
541 return find(getReceiverDecl(Receiver), S);
542 }
543
544 iterator find(IdentifierInfo* II, Selector S) {
545 // FIXME: Class method lookup. Right now we dont' have a good way
546 // of going between IdentifierInfo* and the class hierarchy.
547 iterator I = M.find(ObjCSummaryKey(II, S));
548 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
549 }
550
551 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
552
553 const PointerType* PT = E->getType()->getAsPointerType();
554 if (!PT) return 0;
555
556 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
557 if (!OI) return 0;
558
559 return OI ? OI->getDecl() : 0;
560 }
561
562 iterator end() { return M.end(); }
563
564 RetainSummary*& operator[](ObjCMessageExpr* ME) {
565
566 Selector S = ME->getSelector();
567
568 if (Expr* Receiver = ME->getReceiver()) {
569 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
570 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
571 }
572
573 return M[ObjCSummaryKey(ME->getClassName(), S)];
574 }
575
576 RetainSummary*& operator[](ObjCSummaryKey K) {
577 return M[K];
578 }
579
580 RetainSummary*& operator[](Selector S) {
581 return M[ ObjCSummaryKey(S) ];
582 }
583};
584} // end anonymous namespace
585
586//===----------------------------------------------------------------------===//
587// Data structures for managing collections of summaries.
588//===----------------------------------------------------------------------===//
589
590namespace {
591class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000592
593 //==-----------------------------------------------------------------==//
594 // Typedefs.
595 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000596
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000597 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
598 FuncSummariesTy;
599
Ted Kremenek84f010c2008-06-23 23:30:29 +0000600 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000601
602 //==-----------------------------------------------------------------==//
603 // Data.
604 //==-----------------------------------------------------------------==//
605
Ted Kremenek272aa852008-06-25 21:21:56 +0000606 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000607 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000608
Ted Kremenekede40b72008-07-09 18:11:16 +0000609 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
610 /// "CFDictionaryCreate".
611 IdentifierInfo* CFDictionaryCreateII;
612
Ted Kremenek272aa852008-06-25 21:21:56 +0000613 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000614 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000615
Ted Kremenek272aa852008-06-25 21:21:56 +0000616 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000617 FuncSummariesTy FuncSummaries;
618
Ted Kremenek272aa852008-06-25 21:21:56 +0000619 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
620 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000621 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000622
Ted Kremenek272aa852008-06-25 21:21:56 +0000623 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000624 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000625
Ted Kremenek272aa852008-06-25 21:21:56 +0000626 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
627 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000628 llvm::BumpPtrAllocator BPAlloc;
629
Ted Kremeneka56ae162009-05-03 05:20:50 +0000630 /// AF - A factory for ArgEffects objects.
631 ArgEffects::Factory AF;
632
Ted Kremenek272aa852008-06-25 21:21:56 +0000633 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000634 ArgEffects ScratchArgs;
635
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000636 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
637 /// objects.
638 RetEffect ObjCAllocRetE;
639
Ted Kremenek286e9852009-05-04 04:57:00 +0000640 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000641 RetainSummary* StopSummary;
642
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000643 //==-----------------------------------------------------------------==//
644 // Methods.
645 //==-----------------------------------------------------------------==//
646
Ted Kremenek272aa852008-06-25 21:21:56 +0000647 /// getArgEffects - Returns a persistent ArgEffects object based on the
648 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000649 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000650
Ted Kremenek562c1302008-05-05 16:51:50 +0000651 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000652
653public:
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000654 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
655
Ted Kremenek2f226732009-05-04 05:31:22 +0000656 RetainSummary *getDefaultSummary() {
657 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
658 return new (Summ) RetainSummary(DefaultSummary);
659 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000660
Ted Kremenek064ef322009-02-23 16:51:39 +0000661 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000662
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000663 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
664 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000665 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000666
Ted Kremeneka56ae162009-05-03 05:20:50 +0000667 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000668 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000669 ArgEffect DefaultEff = MayEscape,
670 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000671
Ted Kremenek266d8b62008-05-06 02:26:56 +0000672 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000673 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000674 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000675 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000676 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000677
Ted Kremeneka821b792009-04-29 05:04:30 +0000678 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000679 if (StopSummary)
680 return StopSummary;
681
682 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
683 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000684
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000685 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000686 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000687
Ted Kremeneka821b792009-04-29 05:04:30 +0000688 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000689
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000690 void InitializeClassMethodSummaries();
691 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000692
Ted Kremenek9b42e062009-05-03 04:42:10 +0000693 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000694 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000695
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000696private:
697
Ted Kremenekf2717b02008-07-18 17:24:20 +0000698 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
699 RetainSummary* Summ) {
700 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
701 }
702
Ted Kremenek272aa852008-06-25 21:21:56 +0000703 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
704 ObjCClassMethodSummaries[S] = Summ;
705 }
706
707 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
708 ObjCMethodSummaries[S] = Summ;
709 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000710
711 void addClassMethSummary(const char* Cls, const char* nullaryName,
712 RetainSummary *Summ) {
713 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
714 Selector S = GetNullarySelector(nullaryName, Ctx);
715 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
716 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000717
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000718 void addInstMethSummary(const char* Cls, const char* nullaryName,
719 RetainSummary *Summ) {
720 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
721 Selector S = GetNullarySelector(nullaryName, Ctx);
722 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
723 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000724
725 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000726 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000727
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000728 while (const char* s = va_arg(argp, const char*))
729 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000730
731 return Ctx.Selectors.getSelector(II.size(), &II[0]);
732 }
733
734 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
735 RetainSummary* Summ, va_list argp) {
736 Selector S = generateSelector(argp);
737 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000738 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000739
740 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
741 va_list argp;
742 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000743 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000744 va_end(argp);
745 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000746
747 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
748 va_list argp;
749 va_start(argp, Summ);
750 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
751 va_end(argp);
752 }
753
754 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
755 va_list argp;
756 va_start(argp, Summ);
757 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
758 va_end(argp);
759 }
760
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000761 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000762 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
763 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000764 DoNothing, DoNothing, true);
765 va_list argp;
766 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000767 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000768 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000769 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000770
Ted Kremeneka7338b42008-03-11 06:39:11 +0000771public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000772
773 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000774 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000775 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000776 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000777 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
778 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000779 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
780 RetEffect::MakeNoRet() /* return effect */,
Ted Kremeneka13b0862009-05-11 18:30:24 +0000781 MayEscape, /* default argument effect */
782 DoNothing /* receiver effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000783 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000784
785 InitializeClassMethodSummaries();
786 InitializeMethodSummaries();
787 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000788
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000789 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000790
Ted Kremenekd13c1872008-06-24 03:56:45 +0000791 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000792
Ted Kremenek314b1952009-04-29 23:03:22 +0000793 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
794 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000795 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000796 ID, ME->getMethodDecl(), ME->getType());
797 }
798
Ted Kremenek04e00302009-04-29 17:09:14 +0000799 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000800 const ObjCInterfaceDecl* ID,
801 const ObjCMethodDecl *MD,
802 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000803
804 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000805 const ObjCInterfaceDecl *ID,
806 const ObjCMethodDecl *MD,
807 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000808
809 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
810 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
811 ME->getClassInfo().first,
812 ME->getMethodDecl(), ME->getType());
813 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000814
815 /// getMethodSummary - This version of getMethodSummary is used to query
816 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000817 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
818 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000819 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000820 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000821 IdentifierInfo *ClsName = ID->getIdentifier();
822 QualType ResultTy = MD->getResultType();
823
Ted Kremenek81eb4642009-04-30 05:47:23 +0000824 // Resolve the method decl last.
825 if (const ObjCMethodDecl *InterfaceMD =
826 ResolveToInterfaceMethodDecl(MD, Ctx))
827 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000828
Ted Kremenek91b89a42009-04-29 17:17:48 +0000829 if (MD->isInstanceMethod())
830 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
831 else
832 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
833 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000834
Ted Kremenek314b1952009-04-29 23:03:22 +0000835 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
836 Selector S, QualType RetTy);
837
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000838 void updateSummaryFromAnnotations(RetainSummary &Summ,
839 const ObjCMethodDecl *MD);
840
841 void updateSummaryFromAnnotations(RetainSummary &Summ,
842 const FunctionDecl *FD);
843
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000844 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000845
846 RetainSummary *copySummary(RetainSummary *OldSumm) {
847 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
848 new (Summ) RetainSummary(*OldSumm);
849 return Summ;
850 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000851};
852
853} // end anonymous namespace
854
855//===----------------------------------------------------------------------===//
856// Implementation of checker data structures.
857//===----------------------------------------------------------------------===//
858
Ted Kremeneka56ae162009-05-03 05:20:50 +0000859RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000860
Ted Kremeneka56ae162009-05-03 05:20:50 +0000861ArgEffects RetainSummaryManager::getArgEffects() {
862 ArgEffects AE = ScratchArgs;
863 ScratchArgs = AF.GetEmptyMap();
864 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000865}
866
Ted Kremenek266d8b62008-05-06 02:26:56 +0000867RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000868RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000869 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000870 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000871 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000872 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000873 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000874 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000875 return Summ;
876}
877
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000878//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000879// Predicates.
880//===----------------------------------------------------------------------===//
881
Ted Kremenek9b42e062009-05-03 04:42:10 +0000882bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000883 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000884 return false;
885
Ted Kremenek0d813552009-04-23 22:11:07 +0000886 // We assume that id<..>, id, and "Class" all represent tracked objects.
887 const PointerType *PT = Ty->getAsPointerType();
888 if (PT == 0)
889 return true;
890
891 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000892
893 // We assume that id<..>, id, and "Class" all represent tracked objects.
894 if (!OT)
895 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000896
897 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000898 // FIXME: We can memoize here if this gets too expensive.
899 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
900 ObjCInterfaceDecl* ID = OT->getDecl();
901
902 for ( ; ID ; ID = ID->getSuperClass())
903 if (ID->getIdentifier() == NSObjectII)
904 return true;
905
906 return false;
907}
908
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000909bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
910 return isRefType(T, "CF") || // Core Foundation.
911 isRefType(T, "CG") || // Core Graphics.
912 isRefType(T, "DADisk") || // Disk Arbitration API.
913 isRefType(T, "DADissenter") ||
914 isRefType(T, "DASessionRef");
915}
916
Ted Kremenek35920ed2009-01-07 00:39:56 +0000917//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000918// Summary creation for functions (largely uses of Core Foundation).
919//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000920
Ted Kremenek17144e82009-01-12 21:45:02 +0000921static bool isRetain(FunctionDecl* FD, const char* FName) {
922 const char* loc = strstr(FName, "Retain");
923 return loc && loc[sizeof("Retain")-1] == '\0';
924}
925
926static bool isRelease(FunctionDecl* FD, const char* FName) {
927 const char* loc = strstr(FName, "Release");
928 return loc && loc[sizeof("Release")-1] == '\0';
929}
930
Ted Kremenekd13c1872008-06-24 03:56:45 +0000931RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000932 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000933 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000934 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000935 return I->second;
936
Ted Kremenek64cddf12009-05-04 15:34:07 +0000937 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000938 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000939
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000940 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000941 // We generate "stop" summaries for implicitly defined functions.
942 if (FD->isImplicit()) {
943 S = getPersistentStopSummary();
944 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000945 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000946
Ted Kremenek064ef322009-02-23 16:51:39 +0000947 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000948 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000949 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000950 const char* FName = FD->getIdentifier()->getName();
951
Ted Kremenek38c6f022009-03-05 22:11:14 +0000952 // Strip away preceding '_'. Doing this here will effect all the checks
953 // down below.
954 while (*FName == '_') ++FName;
955
Ted Kremenek17144e82009-01-12 21:45:02 +0000956 // Inspect the result type.
957 QualType RetTy = FT->getResultType();
958
959 // FIXME: This should all be refactored into a chain of "summary lookup"
960 // filters.
961 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
962 // FIXES: <rdar://problem/6326900>
963 // This should be addressed using a API table. This strcmp is also
964 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000965 assert (ScratchArgs.isEmpty());
966 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000967 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
968 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000969 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000970
971 // Enable this code once the semantics of NSDeallocateObject are resolved
972 // for GC. <rdar://problem/6619988>
973#if 0
974 // Handle: NSDeallocateObject(id anObject);
975 // This method does allow 'nil' (although we don't check it now).
976 if (strcmp(FName, "NSDeallocateObject") == 0) {
977 return RetTy == Ctx.VoidTy
978 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
979 : getPersistentStopSummary();
980 }
981#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000982
983 // Handle: id NSMakeCollectable(CFTypeRef)
984 if (strcmp(FName, "NSMakeCollectable") == 0) {
985 S = (RetTy == Ctx.getObjCIdType())
986 ? getUnarySummary(FT, cfmakecollectable)
987 : getPersistentStopSummary();
988
989 break;
990 }
991
992 if (RetTy->isPointerType()) {
993 // For CoreFoundation ('CF') types.
994 if (isRefType(RetTy, "CF", &Ctx, FName)) {
995 if (isRetain(FD, FName))
996 S = getUnarySummary(FT, cfretain);
997 else if (strstr(FName, "MakeCollectable"))
998 S = getUnarySummary(FT, cfmakecollectable);
999 else
1000 S = getCFCreateGetRuleSummary(FD, FName);
1001
1002 break;
1003 }
1004
1005 // For CoreGraphics ('CG') types.
1006 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1007 if (isRetain(FD, FName))
1008 S = getUnarySummary(FT, cfretain);
1009 else
1010 S = getCFCreateGetRuleSummary(FD, FName);
1011
1012 break;
1013 }
1014
1015 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1016 if (isRefType(RetTy, "DADisk") ||
1017 isRefType(RetTy, "DADissenter") ||
1018 isRefType(RetTy, "DASessionRef")) {
1019 S = getCFCreateGetRuleSummary(FD, FName);
1020 break;
1021 }
1022
1023 break;
1024 }
1025
1026 // Check for release functions, the only kind of functions that we care
1027 // about that don't return a pointer type.
1028 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001029 // Test for 'CGCF'.
1030 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1031 FName += 4;
1032 else
1033 FName += 2;
1034
1035 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001036 S = getUnarySummary(FT, cfrelease);
1037 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001038 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001039 // Remaining CoreFoundation and CoreGraphics functions.
1040 // We use to assume that they all strictly followed the ownership idiom
1041 // and that ownership cannot be transferred. While this is technically
1042 // correct, many methods allow a tracked object to escape. For example:
1043 //
1044 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1045 // CFDictionaryAddValue(y, key, x);
1046 // CFRelease(x);
1047 // ... it is okay to use 'x' since 'y' has a reference to it
1048 //
1049 // We handle this and similar cases with the follow heuristic. If the
1050 // function name contains "InsertValue", "SetValue" or "AddValue" then
1051 // we assume that arguments may "escape."
1052 //
1053 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1054 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001055 CStrInCStrNoCase(FName, "SetValue") ||
1056 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001057 ? MayEscape : DoNothing;
1058
1059 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001060 }
1061 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001062 }
1063 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001064
1065 if (!S)
1066 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001067
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001068 // Annotations override defaults.
1069 assert(S);
1070 updateSummaryFromAnnotations(*S, FD);
1071
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001072 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001073 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001074}
1075
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001076RetainSummary*
1077RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1078 const char* FName) {
1079
Ted Kremenek562c1302008-05-05 16:51:50 +00001080 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1081 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001082
Ted Kremenek562c1302008-05-05 16:51:50 +00001083 if (strstr(FName, "Get"))
1084 return getCFSummaryGetRule(FD);
1085
Ted Kremenek286e9852009-05-04 04:57:00 +00001086 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001087}
1088
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001089RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001090RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1091 UnaryFuncKind func) {
1092
Ted Kremenek17144e82009-01-12 21:45:02 +00001093 // Sanity check that this is *really* a unary function. This can
1094 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001095 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001096 if (!FTP || FTP->getNumArgs() != 1)
1097 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001098
Ted Kremeneka56ae162009-05-03 05:20:50 +00001099 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001100
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001101 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001102 case cfretain: {
1103 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001104 return getPersistentSummary(RetEffect::MakeAlias(0),
1105 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001106 }
1107
1108 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001109 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001110 return getPersistentSummary(RetEffect::MakeNoRet(),
1111 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001112 }
1113
1114 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001115 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001116 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001117 }
1118
1119 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001120 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001121 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001122 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001123}
1124
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001125RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001126 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001127
1128 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001129 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1130 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001131 }
1132
Ted Kremenek68621b92009-01-28 05:56:51 +00001133 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001134}
1135
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001136RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001137 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001138 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1139 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001140}
1141
Ted Kremeneka7338b42008-03-11 06:39:11 +00001142//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001143// Summary creation for Selectors.
1144//===----------------------------------------------------------------------===//
1145
Ted Kremenekbcaff792008-05-06 15:44:25 +00001146RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001147RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001148 assert(ScratchArgs.isEmpty());
1149 // 'init' methods conceptually return a newly allocated object and claim
1150 // the receiver.
1151 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
1152 return getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1153 DecRefMsg);
1154
1155 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001156}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001157
1158void
1159RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1160 const FunctionDecl *FD) {
1161 if (!FD)
1162 return;
1163
1164 // Determine if there is a special return effect for this method.
1165 if (isTrackedObjCObjectType(FD->getResultType())) {
1166 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1167 Summ.setRetEffect(ObjCAllocRetE);
1168 }
1169 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1170 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1171 }
1172 }
1173}
1174
1175void
1176RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1177 const ObjCMethodDecl *MD) {
1178 if (!MD)
1179 return;
1180
1181 // Determine if there is a special return effect for this method.
1182 if (isTrackedObjCObjectType(MD->getResultType())) {
1183 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1184 Summ.setRetEffect(ObjCAllocRetE);
1185 }
1186 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1187 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1188 }
1189 }
1190}
1191
Ted Kremenekbcaff792008-05-06 15:44:25 +00001192RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001193RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1194 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001195
Ted Kremenek578498a2009-04-29 00:42:39 +00001196 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001197 // Scan the method decl for 'void*' arguments. These should be treated
1198 // as 'StopTracking' because they are often used with delegates.
1199 // Delegates are a frequent form of false positives with the retain
1200 // count checker.
1201 unsigned i = 0;
1202 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1203 E = MD->param_end(); I != E; ++I, ++i)
1204 if (ParmVarDecl *PD = *I) {
1205 QualType Ty = Ctx.getCanonicalType(PD->getType());
1206 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001207 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001208 }
1209 }
1210
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001211 // Any special effect for the receiver?
1212 ArgEffect ReceiverEff = DoNothing;
1213
1214 // If one of the arguments in the selector has the keyword 'delegate' we
1215 // should stop tracking the reference count for the receiver. This is
1216 // because the reference count is quite possibly handled by a delegate
1217 // method.
1218 if (S.isKeywordSelector()) {
1219 const std::string &str = S.getAsString();
1220 assert(!str.empty());
1221 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1222 }
1223
Ted Kremenek174a0772009-04-23 23:08:22 +00001224 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001225 if (isTrackedObjCObjectType(RetTy)) {
1226 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1227 // by instance methods.
Ted Kremenek613ef972009-05-15 15:49:00 +00001228 RetEffect E = followsFundamentalRule(S)
1229 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001230
1231 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001232 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001233
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001234 // Look for methods that return an owned core foundation object.
1235 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek613ef972009-05-15 15:49:00 +00001236 RetEffect E = followsFundamentalRule(S)
1237 ? RetEffect::MakeOwned(RetEffect::CF, true)
1238 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001239
1240 return getPersistentSummary(E, ReceiverEff, MayEscape);
1241 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001242
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001243 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001244 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001245
Ted Kremenek2f226732009-05-04 05:31:22 +00001246 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001247}
1248
1249RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001250RetainSummaryManager::getInstanceMethodSummary(Selector S,
1251 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001252 const ObjCInterfaceDecl* ID,
1253 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001254 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001255
Ted Kremeneka821b792009-04-29 05:04:30 +00001256 // Look up a summary in our summary cache.
1257 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001258
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001259 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001260 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001261
Ted Kremeneka56ae162009-05-03 05:20:50 +00001262 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001263 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001264
Ted Kremenek2f226732009-05-04 05:31:22 +00001265 // "initXXX": pass-through for receiver.
Ted Kremenek613ef972009-05-15 15:49:00 +00001266 if (deriveNamingConvention(S) == InitRule)
Ted Kremenek2f226732009-05-04 05:31:22 +00001267 Summ = getInitMethodSummary(RetTy);
1268 else
1269 Summ = getCommonMethodSummary(MD, S, RetTy);
1270
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001271 // Annotations override defaults.
1272 updateSummaryFromAnnotations(*Summ, MD);
1273
Ted Kremenek2f226732009-05-04 05:31:22 +00001274 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001275 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001276 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001277}
1278
Ted Kremeneka7722b72008-05-06 21:26:51 +00001279RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001280RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001281 const ObjCInterfaceDecl *ID,
1282 const ObjCMethodDecl *MD,
1283 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001284
Ted Kremenek578498a2009-04-29 00:42:39 +00001285 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001286 ObjCMethodSummariesTy::iterator I =
1287 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001288
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001289 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001290 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001291
1292 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001293
1294 // Annotations override defaults.
1295 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001296
Ted Kremenek2f226732009-05-04 05:31:22 +00001297 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001298 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001299 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001300}
1301
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001302void RetainSummaryManager::InitializeClassMethodSummaries() {
1303 assert(ScratchArgs.isEmpty());
1304 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001305
Ted Kremenek272aa852008-06-25 21:21:56 +00001306 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1307 // NSObject and its derivatives.
1308 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1309 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1310 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001311
1312 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001313 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001314 GetNullarySelector("currentHandler", Ctx),
1315 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001316
1317 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001318 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001319 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1320 GetUnarySelector("addObject", Ctx),
1321 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001322 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001323
1324 // Create the summaries for [NSObject performSelector...]. We treat
1325 // these as 'stop tracking' for the arguments because they are often
1326 // used for delegates that can release the object. When we have better
1327 // inter-procedural analysis we can potentially do something better. This
1328 // workaround is to remove false positives.
1329 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1330 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1331 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1332 "afterDelay", NULL);
1333 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1334 "afterDelay", "inModes", NULL);
1335 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1336 "withObject", "waitUntilDone", NULL);
1337 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1338 "withObject", "waitUntilDone", "modes", NULL);
1339 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1340 "withObject", "waitUntilDone", NULL);
1341 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1342 "withObject", "waitUntilDone", "modes", NULL);
1343 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1344 "withObject", NULL);
Ted Kremenekdf100482009-05-14 21:29:16 +00001345
1346 // Specially handle NSData.
1347 RetainSummary *dataWithBytesNoCopySumm =
1348 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1349 DoNothing);
1350 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1351 "dataWithBytesNoCopy", "length", NULL);
1352 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1353 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001354}
1355
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001356void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001357
Ted Kremeneka56ae162009-05-03 05:20:50 +00001358 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001359
Ted Kremeneka7722b72008-05-06 21:26:51 +00001360 // Create the "init" selector. It just acts as a pass-through for the
1361 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001362 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
1363 getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1364 DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001365
1366 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001367 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001368
1369 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001370 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1371
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001372 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001373 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001374
Ted Kremenek266d8b62008-05-06 02:26:56 +00001375 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001376 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001377 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001378 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001379
1380 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001381 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001382 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001383
1384 // Create the "drain" selector.
1385 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001386 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001387
1388 // Create the -dealloc summary.
1389 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1390 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001391
1392 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001393 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001394 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001395
Ted Kremenekaac82832009-02-23 17:45:03 +00001396 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001397 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001398 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001399 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001400
Ted Kremenek45642a42008-08-12 18:48:50 +00001401 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001402 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1403 // self-own themselves. However, they only do this once they are displayed.
1404 // Thus, we need to track an NSWindow's display status.
1405 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001406 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001407 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1408 StopTracking,
1409 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001410
1411 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1412
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001413#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001414 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001415 "styleMask", "backing", "defer", NULL);
1416
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001417 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001418 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001419#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001420
Ted Kremenek45642a42008-08-12 18:48:50 +00001421 // For NSPanel (which subclasses NSWindow), allocated objects are not
1422 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001423 // FIXME: For now we don't track NSPanels. object for the same reason
1424 // as for NSWindow objects.
1425 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1426
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001427#if 0
1428 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001429 "styleMask", "backing", "defer", NULL);
1430
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001431 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001432 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001433#endif
Ted Kremenek272aa852008-06-25 21:21:56 +00001434
Ted Kremenekf2717b02008-07-18 17:24:20 +00001435 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001436 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1437 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001438
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001439 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1440 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001441}
1442
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001443//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001444// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001445//===----------------------------------------------------------------------===//
1446
Ted Kremeneka7338b42008-03-11 06:39:11 +00001447namespace {
1448
Ted Kremenek7d421f32008-04-09 23:49:11 +00001449class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001450public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001451 enum Kind {
1452 Owned = 0, // Owning reference.
1453 NotOwned, // Reference is not owned by still valid (not freed).
1454 Released, // Object has been released.
1455 ReturnedOwned, // Returned object passes ownership to caller.
1456 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001457 ERROR_START,
1458 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1459 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001460 ErrorUseAfterRelease, // Object used after released.
1461 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001462 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001463 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001464 ErrorLeakReturned, // A memory leak due to the returning method not having
1465 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001466 ErrorGCLeakReturned,
1467 ErrorOverAutorelease,
1468 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001469 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001470
1471private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001472 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001473 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001474 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001475 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001476 QualType T;
1477
Ted Kremenek4d99d342009-05-08 20:01:42 +00001478 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1479 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001480
Ted Kremenek68621b92009-01-28 05:56:51 +00001481 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001482 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001483
1484public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001485 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001486
1487 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001488
Ted Kremenek4d99d342009-05-08 20:01:42 +00001489 unsigned getCount() const { return Cnt; }
1490 unsigned getAutoreleaseCount() const { return ACnt; }
1491 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1492 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001493 void setCount(unsigned i) { Cnt = i; }
1494 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001495
Ted Kremenek272aa852008-06-25 21:21:56 +00001496 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001497
1498 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001499
Ted Kremenek6537a642009-03-17 19:42:23 +00001500 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001501
Ted Kremenek6537a642009-03-17 19:42:23 +00001502 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001503
Ted Kremenekffefc352008-04-11 22:25:11 +00001504 bool isOwned() const {
1505 return getKind() == Owned;
1506 }
1507
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001508 bool isNotOwned() const {
1509 return getKind() == NotOwned;
1510 }
1511
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001512 bool isReturnedOwned() const {
1513 return getKind() == ReturnedOwned;
1514 }
1515
1516 bool isReturnedNotOwned() const {
1517 return getKind() == ReturnedNotOwned;
1518 }
1519
1520 bool isNonLeakError() const {
1521 Kind k = getKind();
1522 return isError(k) && !isLeak(k);
1523 }
1524
Ted Kremenek68621b92009-01-28 05:56:51 +00001525 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1526 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001527 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001528 }
1529
Ted Kremenek68621b92009-01-28 05:56:51 +00001530 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1531 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001532 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001533 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001534
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001535 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001536
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001537 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001538 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001539 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001540
Ted Kremenek272aa852008-06-25 21:21:56 +00001541 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001542 return RefVal(getKind(), getObjKind(), getCount() - i,
1543 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001544 }
1545
1546 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001547 return RefVal(getKind(), getObjKind(), getCount() + i,
1548 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001549 }
1550
1551 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001552 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1553 getType());
1554 }
1555
1556 RefVal autorelease() const {
1557 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1558 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001559 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001560
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001561 void Profile(llvm::FoldingSetNodeID& ID) const {
1562 ID.AddInteger((unsigned) kind);
1563 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001564 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001565 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001566 }
1567
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001568 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001569};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001570
1571void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001572 if (!T.isNull())
1573 Out << "Tracked Type:" << T.getAsString() << '\n';
1574
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001575 switch (getKind()) {
1576 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001577 case Owned: {
1578 Out << "Owned";
1579 unsigned cnt = getCount();
1580 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001581 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001582 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001583
Ted Kremenekc4f81022008-04-10 23:09:18 +00001584 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001585 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001586 unsigned cnt = getCount();
1587 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001588 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001589 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001590
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001591 case ReturnedOwned: {
1592 Out << "ReturnedOwned";
1593 unsigned cnt = getCount();
1594 if (cnt) Out << " (+ " << cnt << ")";
1595 break;
1596 }
1597
1598 case ReturnedNotOwned: {
1599 Out << "ReturnedNotOwned";
1600 unsigned cnt = getCount();
1601 if (cnt) Out << " (+ " << cnt << ")";
1602 break;
1603 }
1604
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001605 case Released:
1606 Out << "Released";
1607 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001608
1609 case ErrorDeallocGC:
1610 Out << "-dealloc (GC)";
1611 break;
1612
1613 case ErrorDeallocNotOwned:
1614 Out << "-dealloc (not-owned)";
1615 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001616
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001617 case ErrorLeak:
1618 Out << "Leaked";
1619 break;
1620
Ted Kremenek311f3d42008-10-22 23:56:21 +00001621 case ErrorLeakReturned:
1622 Out << "Leaked (Bad naming)";
1623 break;
1624
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001625 case ErrorGCLeakReturned:
1626 Out << "Leaked (GC-ed at return)";
1627 break;
1628
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001629 case ErrorUseAfterRelease:
1630 Out << "Use-After-Release [ERROR]";
1631 break;
1632
1633 case ErrorReleaseNotOwned:
1634 Out << "Release of Not-Owned [ERROR]";
1635 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001636
1637 case RefVal::ErrorOverAutorelease:
1638 Out << "Over autoreleased";
1639 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001640
1641 case RefVal::ErrorReturnedNotOwned:
1642 Out << "Non-owned object returned instead of owned";
1643 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001644 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001645
1646 if (ACnt) {
1647 Out << " [ARC +" << ACnt << ']';
1648 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001649}
Ted Kremenek0d721572008-03-11 17:48:22 +00001650
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001651} // end anonymous namespace
1652
1653//===----------------------------------------------------------------------===//
1654// RefBindings - State used to track object reference counts.
1655//===----------------------------------------------------------------------===//
1656
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001657typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001658static int RefBIndex = 0;
1659
1660namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001661 template<>
1662 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1663 static inline void* GDMIndex() { return &RefBIndex; }
1664 };
1665}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001666
1667//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001668// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001669//===----------------------------------------------------------------------===//
1670
Ted Kremenekb6578942009-02-24 19:15:11 +00001671typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1672typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1673typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001674
Ted Kremenekb6578942009-02-24 19:15:11 +00001675static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001676static int AutoRBIndex = 0;
1677
Ted Kremenekb6578942009-02-24 19:15:11 +00001678namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001679namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001680
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001681namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001682template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001683 : public GRStatePartialTrait<ARStack> {
1684 static inline void* GDMIndex() { return &AutoRBIndex; }
1685};
1686
1687template<> struct GRStateTrait<AutoreleasePoolContents>
1688 : public GRStatePartialTrait<ARPoolContents> {
1689 static inline void* GDMIndex() { return &AutoRCIndex; }
1690};
1691} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001692
Ted Kremenek681fb352009-03-20 17:34:15 +00001693static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1694 ARStack stack = state->get<AutoreleaseStack>();
1695 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1696}
1697
1698static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1699 SymbolRef sym) {
1700
1701 SymbolRef pool = GetCurrentAutoreleasePool(state);
1702 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1703 ARCounts newCnts(0);
1704
1705 if (cnts) {
1706 const unsigned *cnt = (*cnts).lookup(sym);
1707 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1708 }
1709 else
1710 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1711
1712 return state.set<AutoreleasePoolContents>(pool, newCnts);
1713}
1714
Ted Kremenek7aef4842008-04-16 20:40:59 +00001715//===----------------------------------------------------------------------===//
1716// Transfer functions.
1717//===----------------------------------------------------------------------===//
1718
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001719namespace {
1720
Ted Kremenek7d421f32008-04-09 23:49:11 +00001721class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001722public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001723 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001724 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001725 virtual void Print(std::ostream& Out, const GRState* state,
1726 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001727 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001728
1729private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001730 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1731 SummaryLogTy;
1732
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001733 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001734 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001735 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001736 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001737
Ted Kremenek708af042009-02-05 06:50:21 +00001738 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001739 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001740 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001741 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001742 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001743 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001744
Ted Kremenekb6578942009-02-24 19:15:11 +00001745 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1746 RefVal::Kind& hasErr);
1747
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001748 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1749 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001750 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001751 ExplodedNode<GRState>* Pred,
1752 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001753 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001754
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001755 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1756 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1757
1758 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1759 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1760 GenericNodeBuilder &Builder,
1761 GRExprEngine &Eng,
1762 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001763
Ted Kremenekb6578942009-02-24 19:15:11 +00001764public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001765 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001766 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001767 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1768 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001769 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1770 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001771
Ted Kremenek708af042009-02-05 06:50:21 +00001772 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001773
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001774 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001775
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001776 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1777 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001778 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001779
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001780 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001781 const LangOptions& getLangOptions() const { return LOpts; }
1782
Ted Kremenekc26c4692009-02-18 03:48:14 +00001783 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1784 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1785 return I == SummaryLog.end() ? 0 : I->second;
1786 }
1787
Ted Kremeneka7338b42008-03-11 06:39:11 +00001788 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001789
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001790 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001791 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001792 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001793 Expr* Ex,
1794 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001795 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001796 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001797 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001798
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001799 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001800 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001801 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001802 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001803 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001804
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001805
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001806 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001807 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001808 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001809 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001810 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001811
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001812 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001813 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001814 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001815 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001816 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001817
Ted Kremeneka42be302009-02-14 01:43:44 +00001818 // Stores.
1819 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1820
Ted Kremenekffefc352008-04-11 22:25:11 +00001821 // End-of-path.
1822
1823 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001824 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001825
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001826 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001827 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001828 GRStmtNodeBuilder<GRState>& Builder,
1829 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001830 Stmt* S, const GRState* state,
1831 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001832
1833 std::pair<ExplodedNode<GRState>*, GRStateRef>
1834 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001835 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1836 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001837 // Return statements.
1838
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001839 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001840 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001841 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001842 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001843 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001844
1845 // Assumptions.
1846
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001847 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001848 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001849 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001850};
1851
1852} // end anonymous namespace
1853
Ted Kremenek681fb352009-03-20 17:34:15 +00001854static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1855 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001856 if (Sym)
1857 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001858 else
1859 Out << "<pool>";
1860 Out << ":{";
1861
1862 // Get the contents of the pool.
1863 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1864 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1865 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1866
1867 Out << '}';
1868}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001869
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001870void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1871 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001872
1873
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001874
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001875 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001876
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001877 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001878 Out << sep << nl;
1879
1880 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1881 Out << (*I).first << " : ";
1882 (*I).second.print(Out);
1883 Out << nl;
1884 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001885
1886 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001887 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001888 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001889
Ted Kremenek681fb352009-03-20 17:34:15 +00001890 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1891 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1892 PrintPool(Out, *I, state);
1893
1894 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001895}
1896
Ted Kremenek47a72422009-04-29 18:50:19 +00001897//===----------------------------------------------------------------------===//
1898// Error reporting.
1899//===----------------------------------------------------------------------===//
1900
1901namespace {
1902
1903 //===-------------===//
1904 // Bug Descriptions. //
1905 //===-------------===//
1906
1907 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1908 protected:
1909 CFRefCount& TF;
1910
1911 CFRefBug(CFRefCount* tf, const char* name)
1912 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1913 public:
1914
1915 CFRefCount& getTF() { return TF; }
1916 const CFRefCount& getTF() const { return TF; }
1917
1918 // FIXME: Eventually remove.
1919 virtual const char* getDescription() const = 0;
1920
1921 virtual bool isLeak() const { return false; }
1922 };
1923
1924 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1925 public:
1926 UseAfterRelease(CFRefCount* tf)
1927 : CFRefBug(tf, "Use-after-release") {}
1928
1929 const char* getDescription() const {
1930 return "Reference-counted object is used after it is released";
1931 }
1932 };
1933
1934 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1935 public:
1936 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1937
1938 const char* getDescription() const {
1939 return "Incorrect decrement of the reference count of an "
1940 "object is not owned at this point by the caller";
1941 }
1942 };
1943
1944 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1945 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001946 DeallocGC(CFRefCount *tf)
1947 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001948
1949 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001950 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001951 }
1952 };
1953
1954 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1955 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001956 DeallocNotOwned(CFRefCount *tf)
1957 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001958
1959 const char *getDescription() const {
1960 return "-dealloc sent to object that may be referenced elsewhere";
1961 }
1962 };
1963
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001964 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1965 public:
1966 OverAutorelease(CFRefCount *tf) :
1967 CFRefBug(tf, "Object sent -autorelease too many times") {}
1968
1969 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001970 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001971 }
1972 };
1973
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001974 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1975 public:
1976 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1977 CFRefBug(tf, "Method should return an owned object") {}
1978
1979 const char *getDescription() const {
1980 return "Object with +0 retain counts returned to caller where a +1 "
1981 "(owning) retain count is expected";
1982 }
1983 };
1984
Ted Kremenek47a72422009-04-29 18:50:19 +00001985 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1986 const bool isReturn;
1987 protected:
1988 Leak(CFRefCount* tf, const char* name, bool isRet)
1989 : CFRefBug(tf, name), isReturn(isRet) {}
1990 public:
1991
1992 const char* getDescription() const { return ""; }
1993
1994 bool isLeak() const { return true; }
1995 };
1996
1997 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1998 public:
1999 LeakAtReturn(CFRefCount* tf, const char* name)
2000 : Leak(tf, name, true) {}
2001 };
2002
2003 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2004 public:
2005 LeakWithinFunction(CFRefCount* tf, const char* name)
2006 : Leak(tf, name, false) {}
2007 };
2008
2009 //===---------===//
2010 // Bug Reports. //
2011 //===---------===//
2012
2013 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2014 protected:
2015 SymbolRef Sym;
2016 const CFRefCount &TF;
2017 public:
2018 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2019 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002020 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2021
2022 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2023 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002024 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002025
2026 virtual ~CFRefReport() {}
2027
2028 CFRefBug& getBugType() {
2029 return (CFRefBug&) RangedBugReport::getBugType();
2030 }
2031 const CFRefBug& getBugType() const {
2032 return (const CFRefBug&) RangedBugReport::getBugType();
2033 }
2034
2035 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2036 const SourceRange*& end) {
2037
2038 if (!getBugType().isLeak())
2039 RangedBugReport::getRanges(BR, beg, end);
2040 else
2041 beg = end = 0;
2042 }
2043
2044 SymbolRef getSymbol() const { return Sym; }
2045
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002046 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002047 const ExplodedNode<GRState>* N);
2048
2049 std::pair<const char**,const char**> getExtraDescriptiveText();
2050
2051 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2052 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002053 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002054 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002055
Ted Kremenek47a72422009-04-29 18:50:19 +00002056 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2057 SourceLocation AllocSite;
2058 const MemRegion* AllocBinding;
2059 public:
2060 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2061 ExplodedNode<GRState> *n, SymbolRef sym,
2062 GRExprEngine& Eng);
2063
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002064 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002065 const ExplodedNode<GRState>* N);
2066
2067 SourceLocation getLocation() const { return AllocSite; }
2068 };
2069} // end anonymous namespace
2070
2071void CFRefCount::RegisterChecks(BugReporter& BR) {
2072 useAfterRelease = new UseAfterRelease(this);
2073 BR.Register(useAfterRelease);
2074
2075 releaseNotOwned = new BadRelease(this);
2076 BR.Register(releaseNotOwned);
2077
2078 deallocGC = new DeallocGC(this);
2079 BR.Register(deallocGC);
2080
2081 deallocNotOwned = new DeallocNotOwned(this);
2082 BR.Register(deallocNotOwned);
2083
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002084 overAutorelease = new OverAutorelease(this);
2085 BR.Register(overAutorelease);
2086
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002087 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2088 BR.Register(returnNotOwnedForOwned);
2089
Ted Kremenek47a72422009-04-29 18:50:19 +00002090 // First register "return" leaks.
2091 const char* name = 0;
2092
2093 if (isGCEnabled())
2094 name = "Leak of returned object when using garbage collection";
2095 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2096 name = "Leak of returned object when not using garbage collection (GC) in "
2097 "dual GC/non-GC code";
2098 else {
2099 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2100 name = "Leak of returned object";
2101 }
2102
2103 leakAtReturn = new LeakAtReturn(this, name);
2104 BR.Register(leakAtReturn);
2105
2106 // Second, register leaks within a function/method.
2107 if (isGCEnabled())
2108 name = "Leak of object when using garbage collection";
2109 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2110 name = "Leak of object when not using garbage collection (GC) in "
2111 "dual GC/non-GC code";
2112 else {
2113 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2114 name = "Leak";
2115 }
2116
2117 leakWithinFunction = new LeakWithinFunction(this, name);
2118 BR.Register(leakWithinFunction);
2119
2120 // Save the reference to the BugReporter.
2121 this->BR = &BR;
2122}
2123
2124static const char* Msgs[] = {
2125 // GC only
2126 "Code is compiled to only use garbage collection",
2127 // No GC.
2128 "Code is compiled to use reference counts",
2129 // Hybrid, with GC.
2130 "Code is compiled to use either garbage collection (GC) or reference counts"
2131 " (non-GC). The bug occurs with GC enabled",
2132 // Hybrid, without GC
2133 "Code is compiled to use either garbage collection (GC) or reference counts"
2134 " (non-GC). The bug occurs in non-GC mode"
2135};
2136
2137std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2138 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2139
2140 switch (TF.getLangOptions().getGCMode()) {
2141 default:
2142 assert(false);
2143
2144 case LangOptions::GCOnly:
2145 assert (TF.isGCEnabled());
2146 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2147
2148 case LangOptions::NonGC:
2149 assert (!TF.isGCEnabled());
2150 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2151
2152 case LangOptions::HybridGC:
2153 if (TF.isGCEnabled())
2154 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2155 else
2156 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2157 }
2158}
2159
2160static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2161 ArgEffect X) {
2162 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2163 I!=E; ++I)
2164 if (*I == X) return true;
2165
2166 return false;
2167}
2168
2169PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2170 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002171 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002172
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002173 if (!isa<PostStmt>(N->getLocation()))
2174 return NULL;
2175
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002176 // Check if the type state has changed.
2177 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002178 GRStateRef PrevSt(PrevN->getState(), StMgr);
2179 GRStateRef CurrSt(N->getState(), StMgr);
2180
2181 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2182 if (!CurrT) return NULL;
2183
2184 const RefVal& CurrV = *CurrT;
2185 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2186
2187 // Create a string buffer to constain all the useful things we want
2188 // to tell the user.
2189 std::string sbuf;
2190 llvm::raw_string_ostream os(sbuf);
2191
2192 // This is the allocation site since the previous node had no bindings
2193 // for this symbol.
2194 if (!PrevT) {
2195 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2196
2197 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2198 // Get the name of the callee (if it is available).
2199 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2200 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2201 os << "Call to function '" << FD->getNameAsString() <<'\'';
2202 else
2203 os << "function call";
2204 }
2205 else {
2206 assert (isa<ObjCMessageExpr>(S));
2207 os << "Method";
2208 }
2209
2210 if (CurrV.getObjKind() == RetEffect::CF) {
2211 os << " returns a Core Foundation object with a ";
2212 }
2213 else {
2214 assert (CurrV.getObjKind() == RetEffect::ObjC);
2215 os << " returns an Objective-C object with a ";
2216 }
2217
2218 if (CurrV.isOwned()) {
2219 os << "+1 retain count (owning reference).";
2220
2221 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2222 assert(CurrV.getObjKind() == RetEffect::CF);
2223 os << " "
2224 "Core Foundation objects are not automatically garbage collected.";
2225 }
2226 }
2227 else {
2228 assert (CurrV.isNotOwned());
2229 os << "+0 retain count (non-owning reference).";
2230 }
2231
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002232 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002233 return new PathDiagnosticEventPiece(Pos, os.str());
2234 }
2235
2236 // Gather up the effects that were performed on the object at this
2237 // program point
2238 llvm::SmallVector<ArgEffect, 2> AEffects;
2239
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002240 if (const RetainSummary *Summ =
2241 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002242 // We only have summaries attached to nodes after evaluating CallExpr and
2243 // ObjCMessageExprs.
2244 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2245
2246 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2247 // Iterate through the parameter expressions and see if the symbol
2248 // was ever passed as an argument.
2249 unsigned i = 0;
2250
2251 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2252 AI!=AE; ++AI, ++i) {
2253
2254 // Retrieve the value of the argument. Is it the symbol
2255 // we are interested in?
2256 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2257 continue;
2258
2259 // We have an argument. Get the effect!
2260 AEffects.push_back(Summ->getArg(i));
2261 }
2262 }
2263 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2264 if (Expr *receiver = ME->getReceiver())
2265 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2266 // The symbol we are tracking is the receiver.
2267 AEffects.push_back(Summ->getReceiverEffect());
2268 }
2269 }
2270 }
2271
2272 do {
2273 // Get the previous type state.
2274 RefVal PrevV = *PrevT;
2275
2276 // Specially handle -dealloc.
2277 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2278 // Determine if the object's reference count was pushed to zero.
2279 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2280 // We may not have transitioned to 'release' if we hit an error.
2281 // This case is handled elsewhere.
2282 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002283 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002284 os << "Object released by directly sending the '-dealloc' message";
2285 break;
2286 }
2287 }
2288
2289 // Specially handle CFMakeCollectable and friends.
2290 if (contains(AEffects, MakeCollectable)) {
2291 // Get the name of the function.
2292 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2293 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2294 const FunctionDecl* FD = X.getAsFunctionDecl();
2295 const std::string& FName = FD->getNameAsString();
2296
2297 if (TF.isGCEnabled()) {
2298 // Determine if the object's reference count was pushed to zero.
2299 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2300
2301 os << "In GC mode a call to '" << FName
2302 << "' decrements an object's retain count and registers the "
2303 "object with the garbage collector. ";
2304
2305 if (CurrV.getKind() == RefVal::Released) {
2306 assert(CurrV.getCount() == 0);
2307 os << "Since it now has a 0 retain count the object can be "
2308 "automatically collected by the garbage collector.";
2309 }
2310 else
2311 os << "An object must have a 0 retain count to be garbage collected. "
2312 "After this call its retain count is +" << CurrV.getCount()
2313 << '.';
2314 }
2315 else
2316 os << "When GC is not enabled a call to '" << FName
2317 << "' has no effect on its argument.";
2318
2319 // Nothing more to say.
2320 break;
2321 }
2322
2323 // Determine if the typestate has changed.
2324 if (!(PrevV == CurrV))
2325 switch (CurrV.getKind()) {
2326 case RefVal::Owned:
2327 case RefVal::NotOwned:
2328
Ted Kremenek4d99d342009-05-08 20:01:42 +00002329 if (PrevV.getCount() == CurrV.getCount()) {
2330 // Did an autorelease message get sent?
2331 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2332 return 0;
2333
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002334 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002335 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002336 break;
2337 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002338
2339 if (PrevV.getCount() > CurrV.getCount())
2340 os << "Reference count decremented.";
2341 else
2342 os << "Reference count incremented.";
2343
2344 if (unsigned Count = CurrV.getCount())
2345 os << " The object now has a +" << Count << " retain count.";
2346
2347 if (PrevV.getKind() == RefVal::Released) {
2348 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2349 os << " The object is not eligible for garbage collection until the "
2350 "retain count reaches 0 again.";
2351 }
2352
2353 break;
2354
2355 case RefVal::Released:
2356 os << "Object released.";
2357 break;
2358
2359 case RefVal::ReturnedOwned:
2360 os << "Object returned to caller as an owning reference (single retain "
2361 "count transferred to caller).";
2362 break;
2363
2364 case RefVal::ReturnedNotOwned:
2365 os << "Object returned to caller with a +0 (non-owning) retain count.";
2366 break;
2367
2368 default:
2369 return NULL;
2370 }
2371
2372 // Emit any remaining diagnostics for the argument effects (if any).
2373 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2374 E=AEffects.end(); I != E; ++I) {
2375
2376 // A bunch of things have alternate behavior under GC.
2377 if (TF.isGCEnabled())
2378 switch (*I) {
2379 default: break;
2380 case Autorelease:
2381 os << "In GC mode an 'autorelease' has no effect.";
2382 continue;
2383 case IncRefMsg:
2384 os << "In GC mode the 'retain' message has no effect.";
2385 continue;
2386 case DecRefMsg:
2387 os << "In GC mode the 'release' message has no effect.";
2388 continue;
2389 }
2390 }
2391 } while(0);
2392
2393 if (os.str().empty())
2394 return 0; // We have nothing to say!
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002395
2396 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002397 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002398 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2399
2400 // Add the range by scanning the children of the statement for any bindings
2401 // to Sym.
2402 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2403 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2404 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2405 P->addRange(Exp->getSourceRange());
2406 break;
2407 }
2408
2409 return P;
2410}
2411
2412namespace {
2413 class VISIBILITY_HIDDEN FindUniqueBinding :
2414 public StoreManager::BindingsHandler {
2415 SymbolRef Sym;
2416 const MemRegion* Binding;
2417 bool First;
2418
2419 public:
2420 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2421
2422 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2423 SVal val) {
2424
2425 SymbolRef SymV = val.getAsSymbol();
2426 if (!SymV || SymV != Sym)
2427 return true;
2428
2429 if (Binding) {
2430 First = false;
2431 return false;
2432 }
2433 else
2434 Binding = R;
2435
2436 return true;
2437 }
2438
2439 operator bool() { return First && Binding; }
2440 const MemRegion* getRegion() { return Binding; }
2441 };
2442}
2443
2444static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2445GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2446 SymbolRef Sym) {
2447
2448 // Find both first node that referred to the tracked symbol and the
2449 // memory location that value was store to.
2450 const ExplodedNode<GRState>* Last = N;
2451 const MemRegion* FirstBinding = 0;
2452
2453 while (N) {
2454 const GRState* St = N->getState();
2455 RefBindings B = St->get<RefBindings>();
2456
2457 if (!B.lookup(Sym))
2458 break;
2459
2460 FindUniqueBinding FB(Sym);
2461 StateMgr.iterBindings(St, FB);
2462 if (FB) FirstBinding = FB.getRegion();
2463
2464 Last = N;
2465 N = N->pred_empty() ? NULL : *(N->pred_begin());
2466 }
2467
2468 return std::make_pair(Last, FirstBinding);
2469}
2470
2471PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002472CFRefReport::getEndPath(BugReporterContext& BRC,
2473 const ExplodedNode<GRState>* EndN) {
2474 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002475 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002476 BRC.addNotableSymbol(Sym);
2477 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002478}
2479
2480PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002481CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2482 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002483
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002484 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002485 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002486 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002487
2488 // We are reporting a leak. Walk up the graph to get to the first node where
2489 // the symbol appeared, and also get the first VarDecl that tracked object
2490 // is stored to.
2491 const ExplodedNode<GRState>* AllocNode = 0;
2492 const MemRegion* FirstBinding = 0;
2493
2494 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002495 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002496
2497 // Get the allocate site.
2498 assert(AllocNode);
2499 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2500
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002501 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002502 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2503
2504 // Compute an actual location for the leak. Sometimes a leak doesn't
2505 // occur at an actual statement (e.g., transition between blocks; end
2506 // of function) so we need to walk the graph and compute a real location.
2507 const ExplodedNode<GRState>* LeakN = EndN;
2508 PathDiagnosticLocation L;
2509
2510 while (LeakN) {
2511 ProgramPoint P = LeakN->getLocation();
2512
2513 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2514 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2515 break;
2516 }
2517 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2518 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2519 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2520 break;
2521 }
2522 }
2523
2524 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2525 }
2526
2527 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002528 const Decl &D = BRC.getCodeDecl();
2529 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002530 }
2531
2532 std::string sbuf;
2533 llvm::raw_string_ostream os(sbuf);
2534
2535 os << "Object allocated on line " << AllocLine;
2536
2537 if (FirstBinding)
2538 os << " and stored into '" << FirstBinding->getString() << '\'';
2539
2540 // Get the retain count.
2541 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2542
2543 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2544 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2545 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2546 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002547 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002548 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002549 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002550 << "') does not contain 'copy' or otherwise starts with"
2551 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002552 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002553 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002554 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2555 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2556 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002557 << "' is potentially leaked when using garbage collection. Callers "
2558 "of this method do not expect a returned object with a +1 retain "
2559 "count since they expect the object to be managed by the garbage "
2560 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002561 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002562 else
2563 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002564 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002565
2566 return new PathDiagnosticEventPiece(L, os.str());
2567}
2568
Ted Kremenek47a72422009-04-29 18:50:19 +00002569CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2570 ExplodedNode<GRState> *n,
2571 SymbolRef sym, GRExprEngine& Eng)
2572: CFRefReport(D, tf, n, sym)
2573{
2574
2575 // Most bug reports are cached at the location where they occured.
2576 // With leaks, we want to unique them by the location where they were
2577 // allocated, and only report a single path. To do this, we need to find
2578 // the allocation site of a piece of tracked memory, which we do via a
2579 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2580 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2581 // that all ancestor nodes that represent the allocation site have the
2582 // same SourceLocation.
2583 const ExplodedNode<GRState>* AllocNode = 0;
2584
2585 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002586 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002587
2588 // Get the SourceLocation for the allocation site.
2589 ProgramPoint P = AllocNode->getLocation();
2590 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2591
2592 // Fill in the description of the bug.
2593 Description.clear();
2594 llvm::raw_string_ostream os(Description);
2595 SourceManager& SMgr = Eng.getContext().getSourceManager();
2596 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002597 os << "Potential leak ";
2598 if (tf.isGCEnabled()) {
2599 os << "(when using garbage collection) ";
2600 }
2601 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002602
2603 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2604 if (AllocBinding)
2605 os << " and stored into '" << AllocBinding->getString() << '\'';
2606}
2607
2608//===----------------------------------------------------------------------===//
2609// Main checker logic.
2610//===----------------------------------------------------------------------===//
2611
Ted Kremenek272aa852008-06-25 21:21:56 +00002612/// GetReturnType - Used to get the return type of a message expression or
2613/// function call with the intention of affixing that type to a tracked symbol.
2614/// While the the return type can be queried directly from RetEx, when
2615/// invoking class methods we augment to the return type to be that of
2616/// a pointer to the class (as opposed it just being id).
2617static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2618
2619 QualType RetTy = RetE->getType();
2620
2621 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002622 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002623 if (!PT)
2624 return RetTy;
2625
2626 // If RetEx is not a message expression just return its type.
2627 // If RetEx is a message expression, return its types if it is something
2628 /// more specific than id.
2629
2630 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2631
Steve Naroff17c03822009-02-12 17:52:19 +00002632 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002633 return RetTy;
2634
2635 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2636
2637 // At this point we know the return type of the message expression is id.
2638 // If we have an ObjCInterceDecl, we know this is a call to a class method
2639 // whose type we can resolve. In such cases, promote the return type to
2640 // Class*.
2641 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2642}
2643
2644
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002645void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002646 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002647 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002648 Expr* Ex,
2649 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002650 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002651 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002652 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002653
Ted Kremeneka7338b42008-03-11 06:39:11 +00002654 // Get the state.
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002655 GRStateManager& StateMgr = Eng.getStateManager();
2656 GRStateRef state(Builder.GetState(Pred), StateMgr);
2657 ASTContext& Ctx = StateMgr.getContext();
2658 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek227c5372008-05-06 02:41:27 +00002659
2660 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002661 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002662 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002663 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002664 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002665
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002666 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002667 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002668 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002669
Ted Kremenek74556a12009-03-26 03:35:11 +00002670 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002671 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002672 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002673 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002674 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002675 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002676 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002677 }
2678 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002679 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002680
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002681 if (isa<Loc>(V)) {
2682 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002683 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002684 continue;
2685
2686 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002687
2688 // FIXME: Either this logic should also be replicated in GRSimpleVals
2689 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002690
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002691 // FIXME: We can have collisions on the conjured symbol if the
2692 // expression *I also creates conjured symbols. We probably want
2693 // to identify conjured symbols by an expression pair: the enclosing
2694 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002695 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002696
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002697 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002698
Ted Kremenek73ec7732009-05-06 18:19:24 +00002699 if (R) {
2700 // Are we dealing with an ElementRegion? If the element type is
2701 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xuea6851b2009-05-11 14:28:14 +00002702 // is a variable region then strip off the ElementRegion.
Ted Kremenek73ec7732009-05-06 18:19:24 +00002703 // FIXME: We really need to think about this for the general case
2704 // as sometimes we are reasoning about arrays and other times
2705 // about (char*), etc., is just a form of passing raw bytes.
2706 // e.g., void *p = alloca(); foo((char*)p);
2707 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2708 // Checking for 'integral type' is probably too promiscuous, but
2709 // we'll leave it in for now until we have a systematic way of
2710 // handling all of these cases. Eventually we need to come up
2711 // with an interface to StoreManager so that this logic can be
2712 // approriately delegated to the respective StoreManagers while
2713 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002714 // invalidating reference counts), probably via callbacks.
Ted Kremenek1cba5772009-05-11 22:55:17 +00002715 if (ER->getElementType()->isIntegralType()) {
2716 const MemRegion *superReg = ER->getSuperRegion();
2717 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2718 isa<ObjCIvarRegion>(superReg))
2719 R = cast<TypedRegion>(superReg);
2720 }
2721
Ted Kremenek73ec7732009-05-06 18:19:24 +00002722 // FIXME: What about layers of ElementRegions?
2723 }
2724
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002725 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002726 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002727
Ted Kremenek53b24182009-03-04 22:56:43 +00002728 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002729 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002730
Ted Kremenek53b24182009-03-04 22:56:43 +00002731 if (R->isBoundable(Ctx)) {
2732 // Set the value of the variable to be a conjured symbol.
2733 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002734 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002735
Zhongxing Xu079dc352009-04-09 06:03:54 +00002736 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002737 ValueManager &ValMgr = Eng.getValueManager();
2738 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002739 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002740 }
2741 else if (const RecordType *RT = T->getAsStructureType()) {
2742 // Handle structs in a not so awesome way. Here we just
2743 // eagerly bind new symbols to the fields. In reality we
2744 // should have the store manager handle this. The idea is just
2745 // to prototype some basic functionality here. All of this logic
2746 // should one day soon just go away.
2747 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2748
2749 // No record definition. There is nothing we can do.
2750 if (!RD)
2751 continue;
2752
2753 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2754
2755 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002756 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2757 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002758
2759 // For now just handle scalar fields.
2760 FieldDecl *FD = *FI;
2761 QualType FT = FD->getType();
2762
2763 if (Loc::IsLocType(FT) ||
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002764 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002765 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002766
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002767 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002768 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002769 }
2770 }
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002771 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2772 // Set the default value of the array to conjured symbol.
2773 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2774 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2775 Count);
2776 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2777 StateMgr);
2778 } else {
Ted Kremenek53b24182009-03-04 22:56:43 +00002779 // Just blast away other values.
2780 state = state.BindLoc(*MR, UnknownVal());
2781 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002782 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002783 }
2784 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002785 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002786 }
2787 else {
2788 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002789 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002790 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002791 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002792 else if (isa<nonloc::LocAsInteger>(V))
2793 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002794 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002795
Ted Kremenek272aa852008-06-25 21:21:56 +00002796 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002797 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002798 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002799 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002800 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002801 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002802 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002803 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002804 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002805 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002806 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002807 }
2808 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002809
Ted Kremenek272aa852008-06-25 21:21:56 +00002810 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002811 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002812 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002813 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002814 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002815 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002816
Ted Kremenekf2717b02008-07-18 17:24:20 +00002817 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002818 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002819
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002820 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2821 assert(Receiver);
2822 SVal V = state.GetSValAsScalarOrLoc(Receiver);
2823 bool found = false;
2824 if (SymbolRef Sym = V.getAsLocSymbol())
2825 if (state.get<RefBindings>(Sym)) {
2826 found = true;
2827 RE = Summaries.getObjAllocRetEffect();
2828 }
2829
2830 if (!found)
2831 RE = RetEffect::MakeNoRet();
2832 }
2833
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002834 switch (RE.getKind()) {
2835 default:
2836 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002837
Ted Kremenek8f90e712008-10-17 22:23:12 +00002838 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002839
Ted Kremenek455dd862008-04-11 20:23:24 +00002840 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002841 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2842 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002843
Ted Kremenek8f90e712008-10-17 22:23:12 +00002844 // FIXME: We eventually should handle structs and other compound types
2845 // that are returned by value.
2846
2847 QualType T = Ex->getType();
2848
Ted Kremenek79413a52008-11-13 06:10:40 +00002849 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002850 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002851 ValueManager &ValMgr = Eng.getValueManager();
2852 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002853 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002854 }
2855
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002856 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002857 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002858
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002859 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002860 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002861 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002862 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002863 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002864 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002865 break;
2866 }
2867
Ted Kremenek227c5372008-05-06 02:41:27 +00002868 case RetEffect::ReceiverAlias: {
2869 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002870 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002871 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002872 break;
2873 }
2874
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002875 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002876 case RetEffect::OwnedSymbol: {
2877 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002878 ValueManager &ValMgr = Eng.getValueManager();
2879 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2880 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2881 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2882 RetT));
2883 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002884
2885 // FIXME: Add a flag to the checker where allocations are assumed to
2886 // *not fail.
2887#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002888 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2889 bool isFeasible;
2890 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2891 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2892 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002893#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002894
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002895 break;
2896 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002897
2898 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002899 case RetEffect::NotOwnedSymbol: {
2900 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002901 ValueManager &ValMgr = Eng.getValueManager();
2902 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2903 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2904 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2905 RetT));
2906 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002907 break;
2908 }
2909 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002910
Ted Kremenek0dd65012009-02-18 02:00:25 +00002911 // Generate a sink node if we are at the end of a path.
2912 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002913 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2914 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002915
2916 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002917 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002918}
2919
2920
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002921void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002922 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002923 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002924 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002925 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002926 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002927 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002928 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002929
Ted Kremenek286e9852009-05-04 04:57:00 +00002930 assert(Summ);
2931 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002932 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002933}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002934
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002935void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002936 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002937 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002938 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002939 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002940 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002941
Ted Kremenek272aa852008-06-25 21:21:56 +00002942 if (Expr* Receiver = ME->getReceiver()) {
2943 // We need the type-information of the tracked receiver object
2944 // Retrieve it from the state.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002945 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek272aa852008-06-25 21:21:56 +00002946
2947 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2948 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002949 // FIXME: Is this really working as expected? There are cases where
2950 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002951 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002952 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002953
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002954 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002955 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002956 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002957 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002958
2959 if (const PointerType* PT = Ty->getAsPointerType()) {
2960 QualType PointeeTy = PT->getPointeeType();
2961
2962 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2963 ID = IT->getDecl();
2964 }
2965 }
2966 }
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002967
2968 // FIXME: this is a hack. This may or may not be the actual method
2969 // that is called.
2970 if (!ID) {
2971 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
2972 if (const ObjCInterfaceType *p =
2973 PT->getPointeeType()->getAsObjCInterfaceType())
2974 ID = p->getDecl();
2975 }
2976
Ted Kremenek04e00302009-04-29 17:09:14 +00002977 // FIXME: The receiver could be a reference to a class, meaning that
2978 // we should use the class method.
2979 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002980
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002981 // Special-case: are we sending a mesage to "self"?
2982 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002983 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2984 if (Expr* Receiver = ME->getReceiver()) {
2985 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2986 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2987 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2988 // Update the summary to make the default argument effect
2989 // 'StopTracking'.
2990 Summ = Summaries.copySummary(Summ);
2991 Summ->setDefaultArgEffect(StopTracking);
2992 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002993 }
2994 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002995 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002996 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002997 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002998
Ted Kremenek286e9852009-05-04 04:57:00 +00002999 if (!Summ)
3000 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00003001
Ted Kremenek286e9852009-05-04 04:57:00 +00003002 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00003003 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00003004}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003005
3006namespace {
3007class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
3008 GRStateRef state;
3009public:
3010 StopTrackingCallback(GRStateRef st) : state(st) {}
3011 GRStateRef getState() { return state; }
3012
3013 bool VisitSymbol(SymbolRef sym) {
3014 state = state.remove<RefBindings>(sym);
3015 return true;
3016 }
Ted Kremenek926abf22008-05-06 04:20:12 +00003017
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003018 const GRState* getState() const { return state.getState(); }
3019};
3020} // end anonymous namespace
3021
3022
Ted Kremeneka42be302009-02-14 01:43:44 +00003023void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00003024 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00003025 bool escapes = false;
3026
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003027 // A value escapes in three possible cases (this may change):
3028 //
3029 // (1) we are binding to something that is not a memory region.
3030 // (2) we are binding to a memregion that does not have stack storage
3031 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003032 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00003033 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003034
Ted Kremeneka42be302009-02-14 01:43:44 +00003035 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003036 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003037 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003038 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3039 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003040
3041 if (!escapes) {
3042 // To test (3), generate a new state with the binding removed. If it is
3043 // the same state, then it escapes (since the store cannot represent
3044 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00003045 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003046 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003047 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003048
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003049 // If our store can represent the binding and we aren't storing to something
3050 // that doesn't have local storage then just return and have the simulation
3051 // state continue as is.
3052 if (!escapes)
3053 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003054
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003055 // Otherwise, find all symbols referenced by 'val' that we are tracking
3056 // and stop tracking them.
3057 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003058}
3059
Ted Kremenek541db372008-04-24 23:57:27 +00003060
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003061 // Return statements.
3062
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003063void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003064 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003065 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003066 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003067 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003068
3069 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003070 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003071 return;
3072
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003073 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00003074 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003075
Ted Kremenek74556a12009-03-26 03:35:11 +00003076 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003077 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003078
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003079 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003080 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003081
3082 if (!T)
3083 return;
3084
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003085 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003086 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003087
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003088 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003089 case RefVal::Owned: {
3090 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003091 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003092 X.setCount(cnt - 1);
3093 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003094 break;
3095 }
3096
3097 case RefVal::NotOwned: {
3098 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003099 if (cnt) {
3100 X.setCount(cnt - 1);
3101 X = X ^ RefVal::ReturnedOwned;
3102 }
3103 else {
3104 X = X ^ RefVal::ReturnedNotOwned;
3105 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003106 break;
3107 }
3108
3109 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003110 return;
3111 }
3112
3113 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003114 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003115 Pred = Builder.MakeNode(Dst, S, Pred, state);
3116
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003117 // Did we cache out?
3118 if (!Pred)
3119 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003120
3121 // Update the autorelease counts.
3122 static unsigned autoreleasetag = 0;
3123 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3124 bool stop = false;
3125 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3126 X, stop);
3127
3128 // Did we cache out?
3129 if (!Pred || stop)
3130 return;
3131
3132 // Get the updated binding.
3133 T = state.get<RefBindings>(Sym);
3134 assert(T);
3135 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003136
Ted Kremenek47a72422009-04-29 18:50:19 +00003137 // Any leaks or other errors?
3138 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003139 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003140 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003141 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003142 RetEffect RE = Summ.getRetEffect();
3143 bool hasError = false;
3144
3145 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3146 // Things are more complicated with garbage collection. If the
3147 // returned object is suppose to be an Objective-C object, we have
Ted Kremenekeaea6582009-05-10 16:52:15 +00003148 // a leak (as the caller expects a GC'ed object) because no
3149 // method should return ownership unless it returns a CF object.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003150 X = X ^ RefVal::ErrorGCLeakReturned;
3151
3152 // Keep this false until this is properly tested.
Ted Kremenekeaea6582009-05-10 16:52:15 +00003153 hasError = true;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003154 }
3155 else if (!RE.isOwned()) {
3156 // Either we are using GC and the returned object is a CF type
3157 // or we aren't using GC. In either case, we expect that the
3158 // enclosing method is expected to return ownership.
3159 hasError = true;
3160 X = X ^ RefVal::ErrorLeakReturned;
3161 }
3162
3163 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003164 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003165 static int ReturnOwnLeakTag = 0;
3166 state = state.set<RefBindings>(Sym, X);
3167 ExplodedNode<GRState> *N =
3168 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3169 if (N) {
3170 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003171 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3172 N, Sym, Eng);
3173 BR->EmitReport(report);
3174 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003175 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003176 }
3177 }
3178 else if (X.isReturnedNotOwned()) {
3179 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3180 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3181 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3182 if (Summ.getRetEffect().isOwned()) {
3183 // Trying to return a not owned object to a caller expecting an
3184 // owned object.
3185
3186 static int ReturnNotOwnedForOwnedTag = 0;
3187 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3188 if (ExplodedNode<GRState> *N =
3189 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3190 state, Pred)) {
3191 CFRefReport *report =
3192 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3193 *this, N, Sym);
3194 BR->EmitReport(report);
3195 }
3196 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003197 }
3198 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003199}
3200
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003201// Assumptions.
3202
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003203const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3204 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003205 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003206 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003207
3208 // FIXME: We may add to the interface of EvalAssume the list of symbols
3209 // whose assumptions have changed. For now we just iterate through the
3210 // bindings and check if any of the tracked symbols are NULL. This isn't
3211 // too bad since the number of symbols we will track in practice are
3212 // probably small and EvalAssume is only called at branches and a few
3213 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003214 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003215
3216 if (B.isEmpty())
3217 return St;
3218
3219 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003220
3221 GRStateRef state(St, VMgr);
3222 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003223
3224 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003225 // Check if the symbol is null (or equal to any constant).
3226 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003227 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003228 changed = true;
3229 B = RefBFactory.Remove(B, I.getKey());
3230 }
3231 }
3232
Ted Kremenek91781202008-08-17 03:20:02 +00003233 if (changed)
3234 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003235
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003236 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003237}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003238
Ted Kremenekb6578942009-02-24 19:15:11 +00003239GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3240 RefVal V, ArgEffect E,
3241 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003242
3243 // In GC mode [... release] and [... retain] do nothing.
3244 switch (E) {
3245 default: break;
3246 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3247 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003248 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003249 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3250 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003251 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003252
Ted Kremenek6537a642009-03-17 19:42:23 +00003253 // Handle all use-after-releases.
3254 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3255 V = V ^ RefVal::ErrorUseAfterRelease;
3256 hasErr = V.getKind();
3257 return state.set<RefBindings>(sym, V);
3258 }
3259
Ted Kremenek0d721572008-03-11 17:48:22 +00003260 switch (E) {
3261 default:
3262 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003263
3264 case Dealloc:
3265 // Any use of -dealloc in GC is *bad*.
3266 if (isGCEnabled()) {
3267 V = V ^ RefVal::ErrorDeallocGC;
3268 hasErr = V.getKind();
3269 break;
3270 }
3271
3272 switch (V.getKind()) {
3273 default:
3274 assert(false && "Invalid case.");
3275 case RefVal::Owned:
3276 // The object immediately transitions to the released state.
3277 V = V ^ RefVal::Released;
3278 V.clearCounts();
3279 return state.set<RefBindings>(sym, V);
3280 case RefVal::NotOwned:
3281 V = V ^ RefVal::ErrorDeallocNotOwned;
3282 hasErr = V.getKind();
3283 break;
3284 }
3285 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003286
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003287 case NewAutoreleasePool:
3288 assert(!isGCEnabled());
3289 return state.add<AutoreleaseStack>(sym);
3290
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003291 case MayEscape:
3292 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003293 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003294 break;
3295 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003296
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003297 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003298
Ted Kremenekede40b72008-07-09 18:11:16 +00003299 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003300 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003301 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003302
Ted Kremenek9b112d22009-01-28 21:44:40 +00003303 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003304 if (isGCEnabled())
3305 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003306
3307 // Update the autorelease counts.
3308 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003309 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003310 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003311
Ted Kremenek227c5372008-05-06 02:41:27 +00003312 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003313 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003314
Ted Kremenek0d721572008-03-11 17:48:22 +00003315 case IncRef:
3316 switch (V.getKind()) {
3317 default:
3318 assert(false);
3319
3320 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003321 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003322 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003323 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003324 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003325 // Non-GC cases are handled above.
3326 assert(isGCEnabled());
3327 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003328 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003329 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003330 break;
3331
Ted Kremenek272aa852008-06-25 21:21:56 +00003332 case SelfOwn:
3333 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003334 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003335 case DecRef:
3336 switch (V.getKind()) {
3337 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003338 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003339 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003340
Ted Kremenek272aa852008-06-25 21:21:56 +00003341 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003342 assert(V.getCount() > 0);
3343 if (V.getCount() == 1) V = V ^ RefVal::Released;
3344 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003345 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003346
Ted Kremenek272aa852008-06-25 21:21:56 +00003347 case RefVal::NotOwned:
3348 if (V.getCount() > 0)
3349 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003350 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003351 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003352 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003353 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003354 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003355
Ted Kremenek0d721572008-03-11 17:48:22 +00003356 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003357 // Non-GC cases are handled above.
3358 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003359 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003360 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003361 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003362 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003363 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003364 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003365 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003366}
3367
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003368//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003369// Handle dead symbols and end-of-path.
3370//===----------------------------------------------------------------------===//
3371
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003372std::pair<ExplodedNode<GRState>*, GRStateRef>
3373CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3374 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003375 GRExprEngine &Eng,
3376 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003377
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003378 unsigned ACnt = V.getAutoreleaseCount();
3379 stop = false;
3380
3381 // No autorelease counts? Nothing to be done.
3382 if (!ACnt)
3383 return std::make_pair(Pred, state);
3384
3385 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3386 unsigned Cnt = V.getCount();
3387
Ted Kremenek0603cf52009-05-11 15:26:06 +00003388 // FIXME: Handle sending 'autorelease' to already released object.
3389
3390 if (V.getKind() == RefVal::ReturnedOwned)
3391 ++Cnt;
3392
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003393 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003394 if (ACnt == Cnt) {
3395 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003396 if (V.getKind() == RefVal::ReturnedOwned)
3397 V = V ^ RefVal::ReturnedNotOwned;
3398 else
3399 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003400 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003401 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003402 V.setCount(Cnt - ACnt);
3403 V.setAutoreleaseCount(0);
3404 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003405 state = state.set<RefBindings>(Sym, V);
3406 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3407 stop = (N == 0);
3408 return std::make_pair(N, state);
3409 }
3410
3411 // Woah! More autorelease counts then retain counts left.
3412 // Emit hard error.
3413 stop = true;
3414 V = V ^ RefVal::ErrorOverAutorelease;
3415 state = state.set<RefBindings>(Sym, V);
3416
3417 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003418 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003419
3420 std::string sbuf;
3421 llvm::raw_string_ostream os(sbuf);
Ted Kremenek2e6ce412009-05-15 06:02:08 +00003422 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekbd271be2009-05-10 05:11:21 +00003423 if (V.getAutoreleaseCount() > 1)
3424 os << V.getAutoreleaseCount() << " times";
3425 os << " but the object has ";
3426 if (V.getCount() == 0)
3427 os << "zero (locally visible)";
3428 else
3429 os << "+" << V.getCount();
3430 os << " retain counts";
3431
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003432 CFRefReport *report =
3433 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003434 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003435 BR->EmitReport(report);
3436 }
3437
3438 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003439}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003440
3441GRStateRef
3442CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3443 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3444
3445 bool hasLeak = V.isOwned() ||
3446 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3447
3448 if (!hasLeak)
3449 return state.remove<RefBindings>(sid);
3450
3451 Leaked.push_back(sid);
3452 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3453}
3454
3455ExplodedNode<GRState>*
3456CFRefCount::ProcessLeaks(GRStateRef state,
3457 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3458 GenericNodeBuilder &Builder,
3459 GRExprEngine& Eng,
3460 ExplodedNode<GRState> *Pred) {
3461
3462 if (Leaked.empty())
3463 return Pred;
3464
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003465 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003466 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003467
3468 if (N) {
3469 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3470 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3471
3472 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3473 : leakAtReturn);
3474 assert(BT && "BugType not initialized.");
3475 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3476 BR->EmitReport(report);
3477 }
3478 }
3479
3480 return N;
3481}
3482
Ted Kremenek708af042009-02-05 06:50:21 +00003483void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3484 GREndPathNodeBuilder<GRState>& Builder) {
3485
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003486 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003487 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003488 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003489 ExplodedNode<GRState> *Pred = 0;
3490
3491 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003492 bool stop = false;
3493 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3494 (*I).first,
3495 (*I).second, stop);
3496
3497 if (stop)
3498 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003499 }
3500
3501 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003502 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003503
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003504 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3505 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3506
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003507 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003508}
3509
3510void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3511 GRExprEngine& Eng,
3512 GRStmtNodeBuilder<GRState>& Builder,
3513 ExplodedNode<GRState>* Pred,
3514 Stmt* S,
3515 const GRState* St,
3516 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003517
3518 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003519 RefBindings B = state.get<RefBindings>();
3520
3521 // Update counts from autorelease pools
3522 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3523 E = SymReaper.dead_end(); I != E; ++I) {
3524 SymbolRef Sym = *I;
3525 if (const RefVal* T = B.lookup(Sym)){
3526 // Use the symbol as the tag.
3527 // FIXME: This might not be as unique as we would like.
3528 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003529 bool stop = false;
3530 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3531 Sym, *T, stop);
3532 if (stop)
3533 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003534 }
3535 }
3536
3537 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003538 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003539
3540 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003541 E = SymReaper.dead_end(); I != E; ++I) {
3542 if (const RefVal* T = B.lookup(*I))
3543 state = HandleSymbolDeath(state, *I, *T, Leaked);
3544 }
Ted Kremenek708af042009-02-05 06:50:21 +00003545
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003546 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003547 {
3548 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3549 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3550 }
Ted Kremenek708af042009-02-05 06:50:21 +00003551
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003552 // Did we cache out?
3553 if (!Pred)
3554 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003555
3556 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003557 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003558
Ted Kremenek876d8df2009-02-19 23:47:02 +00003559 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003560 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3561
Ted Kremenek876d8df2009-02-19 23:47:02 +00003562 state = state.set<RefBindings>(B);
3563 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003564}
3565
3566void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3567 GRStmtNodeBuilder<GRState>& Builder,
3568 Expr* NodeExpr, Expr* ErrorExpr,
3569 ExplodedNode<GRState>* Pred,
3570 const GRState* St,
3571 RefVal::Kind hasErr, SymbolRef Sym) {
3572 Builder.BuildSinks = true;
3573 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3574
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003575 if (!N)
3576 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003577
3578 CFRefBug *BT = 0;
3579
Ted Kremenek6537a642009-03-17 19:42:23 +00003580 switch (hasErr) {
3581 default:
3582 assert(false && "Unhandled error.");
3583 return;
3584 case RefVal::ErrorUseAfterRelease:
3585 BT = static_cast<CFRefBug*>(useAfterRelease);
3586 break;
3587 case RefVal::ErrorReleaseNotOwned:
3588 BT = static_cast<CFRefBug*>(releaseNotOwned);
3589 break;
3590 case RefVal::ErrorDeallocGC:
3591 BT = static_cast<CFRefBug*>(deallocGC);
3592 break;
3593 case RefVal::ErrorDeallocNotOwned:
3594 BT = static_cast<CFRefBug*>(deallocNotOwned);
3595 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003596 }
3597
Ted Kremenekc26c4692009-02-18 03:48:14 +00003598 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003599 report->addRange(ErrorExpr->getSourceRange());
3600 BR->EmitReport(report);
3601}
3602
3603//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003604// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003605//===----------------------------------------------------------------------===//
3606
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003607GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3608 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003609 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003610}