blob: 30ff67f4a56400f816280b41a3b049d72016f043 [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
Ted Kremenek5b44a402009-05-16 01:38:01 +0000897 // Does the interface subclass NSObject?
898 // FIXME: We can memoize here if this gets too expensive.
Ted Kremenek35920ed2009-01-07 00:39:56 +0000899 ObjCInterfaceDecl* ID = OT->getDecl();
900
Ted Kremenek5b44a402009-05-16 01:38:01 +0000901 // Assume that anything declared with a forward declaration and no
902 // @interface subclasses NSObject.
903 if (ID->isForwardDecl())
904 return true;
905
906 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
907
908
Ted Kremenek35920ed2009-01-07 00:39:56 +0000909 for ( ; ID ; ID = ID->getSuperClass())
910 if (ID->getIdentifier() == NSObjectII)
911 return true;
912
913 return false;
914}
915
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000916bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
917 return isRefType(T, "CF") || // Core Foundation.
918 isRefType(T, "CG") || // Core Graphics.
919 isRefType(T, "DADisk") || // Disk Arbitration API.
920 isRefType(T, "DADissenter") ||
921 isRefType(T, "DASessionRef");
922}
923
Ted Kremenek35920ed2009-01-07 00:39:56 +0000924//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000925// Summary creation for functions (largely uses of Core Foundation).
926//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000927
Ted Kremenek17144e82009-01-12 21:45:02 +0000928static bool isRetain(FunctionDecl* FD, const char* FName) {
929 const char* loc = strstr(FName, "Retain");
930 return loc && loc[sizeof("Retain")-1] == '\0';
931}
932
933static bool isRelease(FunctionDecl* FD, const char* FName) {
934 const char* loc = strstr(FName, "Release");
935 return loc && loc[sizeof("Release")-1] == '\0';
936}
937
Ted Kremenekd13c1872008-06-24 03:56:45 +0000938RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000939 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000940 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000941 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000942 return I->second;
943
Ted Kremenek64cddf12009-05-04 15:34:07 +0000944 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000945 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000946
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000947 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000948 // We generate "stop" summaries for implicitly defined functions.
949 if (FD->isImplicit()) {
950 S = getPersistentStopSummary();
951 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000952 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000953
Ted Kremenek064ef322009-02-23 16:51:39 +0000954 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000955 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000956 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000957 const char* FName = FD->getIdentifier()->getName();
958
Ted Kremenek38c6f022009-03-05 22:11:14 +0000959 // Strip away preceding '_'. Doing this here will effect all the checks
960 // down below.
961 while (*FName == '_') ++FName;
962
Ted Kremenek17144e82009-01-12 21:45:02 +0000963 // Inspect the result type.
964 QualType RetTy = FT->getResultType();
965
966 // FIXME: This should all be refactored into a chain of "summary lookup"
967 // filters.
968 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
969 // FIXES: <rdar://problem/6326900>
970 // This should be addressed using a API table. This strcmp is also
971 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000972 assert (ScratchArgs.isEmpty());
973 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000974 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
975 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000976 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000977
978 // Enable this code once the semantics of NSDeallocateObject are resolved
979 // for GC. <rdar://problem/6619988>
980#if 0
981 // Handle: NSDeallocateObject(id anObject);
982 // This method does allow 'nil' (although we don't check it now).
983 if (strcmp(FName, "NSDeallocateObject") == 0) {
984 return RetTy == Ctx.VoidTy
985 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
986 : getPersistentStopSummary();
987 }
988#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000989
990 // Handle: id NSMakeCollectable(CFTypeRef)
991 if (strcmp(FName, "NSMakeCollectable") == 0) {
992 S = (RetTy == Ctx.getObjCIdType())
993 ? getUnarySummary(FT, cfmakecollectable)
994 : getPersistentStopSummary();
995
996 break;
997 }
998
999 if (RetTy->isPointerType()) {
1000 // For CoreFoundation ('CF') types.
1001 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1002 if (isRetain(FD, FName))
1003 S = getUnarySummary(FT, cfretain);
1004 else if (strstr(FName, "MakeCollectable"))
1005 S = getUnarySummary(FT, cfmakecollectable);
1006 else
1007 S = getCFCreateGetRuleSummary(FD, FName);
1008
1009 break;
1010 }
1011
1012 // For CoreGraphics ('CG') types.
1013 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1014 if (isRetain(FD, FName))
1015 S = getUnarySummary(FT, cfretain);
1016 else
1017 S = getCFCreateGetRuleSummary(FD, FName);
1018
1019 break;
1020 }
1021
1022 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1023 if (isRefType(RetTy, "DADisk") ||
1024 isRefType(RetTy, "DADissenter") ||
1025 isRefType(RetTy, "DASessionRef")) {
1026 S = getCFCreateGetRuleSummary(FD, FName);
1027 break;
1028 }
1029
1030 break;
1031 }
1032
1033 // Check for release functions, the only kind of functions that we care
1034 // about that don't return a pointer type.
1035 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001036 // Test for 'CGCF'.
1037 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1038 FName += 4;
1039 else
1040 FName += 2;
1041
1042 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001043 S = getUnarySummary(FT, cfrelease);
1044 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001045 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001046 // Remaining CoreFoundation and CoreGraphics functions.
1047 // We use to assume that they all strictly followed the ownership idiom
1048 // and that ownership cannot be transferred. While this is technically
1049 // correct, many methods allow a tracked object to escape. For example:
1050 //
1051 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1052 // CFDictionaryAddValue(y, key, x);
1053 // CFRelease(x);
1054 // ... it is okay to use 'x' since 'y' has a reference to it
1055 //
1056 // We handle this and similar cases with the follow heuristic. If the
1057 // function name contains "InsertValue", "SetValue" or "AddValue" then
1058 // we assume that arguments may "escape."
1059 //
1060 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1061 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001062 CStrInCStrNoCase(FName, "SetValue") ||
1063 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001064 ? MayEscape : DoNothing;
1065
1066 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001067 }
1068 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001069 }
1070 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001071
1072 if (!S)
1073 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001074
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001075 // Annotations override defaults.
1076 assert(S);
1077 updateSummaryFromAnnotations(*S, FD);
1078
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001079 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001080 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001081}
1082
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001083RetainSummary*
1084RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1085 const char* FName) {
1086
Ted Kremenek562c1302008-05-05 16:51:50 +00001087 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1088 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001089
Ted Kremenek562c1302008-05-05 16:51:50 +00001090 if (strstr(FName, "Get"))
1091 return getCFSummaryGetRule(FD);
1092
Ted Kremenek286e9852009-05-04 04:57:00 +00001093 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001094}
1095
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001096RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001097RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1098 UnaryFuncKind func) {
1099
Ted Kremenek17144e82009-01-12 21:45:02 +00001100 // Sanity check that this is *really* a unary function. This can
1101 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001102 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001103 if (!FTP || FTP->getNumArgs() != 1)
1104 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001105
Ted Kremeneka56ae162009-05-03 05:20:50 +00001106 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001107
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001108 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001109 case cfretain: {
1110 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001111 return getPersistentSummary(RetEffect::MakeAlias(0),
1112 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001113 }
1114
1115 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001116 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001117 return getPersistentSummary(RetEffect::MakeNoRet(),
1118 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001119 }
1120
1121 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001122 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001123 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001124 }
1125
1126 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001127 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001128 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001129 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001130}
1131
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001132RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001133 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001134
1135 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001136 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1137 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001138 }
1139
Ted Kremenek68621b92009-01-28 05:56:51 +00001140 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001141}
1142
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001143RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001144 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001145 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1146 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001147}
1148
Ted Kremeneka7338b42008-03-11 06:39:11 +00001149//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001150// Summary creation for Selectors.
1151//===----------------------------------------------------------------------===//
1152
Ted Kremenekbcaff792008-05-06 15:44:25 +00001153RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001154RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001155 assert(ScratchArgs.isEmpty());
1156 // 'init' methods conceptually return a newly allocated object and claim
1157 // the receiver.
1158 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
1159 return getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1160 DecRefMsg);
1161
1162 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001163}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001164
1165void
1166RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1167 const FunctionDecl *FD) {
1168 if (!FD)
1169 return;
1170
1171 // Determine if there is a special return effect for this method.
1172 if (isTrackedObjCObjectType(FD->getResultType())) {
1173 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1174 Summ.setRetEffect(ObjCAllocRetE);
1175 }
1176 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1177 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1178 }
1179 }
1180}
1181
1182void
1183RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1184 const ObjCMethodDecl *MD) {
1185 if (!MD)
1186 return;
1187
1188 // Determine if there is a special return effect for this method.
1189 if (isTrackedObjCObjectType(MD->getResultType())) {
1190 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1191 Summ.setRetEffect(ObjCAllocRetE);
1192 }
1193 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1194 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1195 }
1196 }
1197}
1198
Ted Kremenekbcaff792008-05-06 15:44:25 +00001199RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001200RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1201 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001202
Ted Kremenek578498a2009-04-29 00:42:39 +00001203 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001204 // Scan the method decl for 'void*' arguments. These should be treated
1205 // as 'StopTracking' because they are often used with delegates.
1206 // Delegates are a frequent form of false positives with the retain
1207 // count checker.
1208 unsigned i = 0;
1209 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1210 E = MD->param_end(); I != E; ++I, ++i)
1211 if (ParmVarDecl *PD = *I) {
1212 QualType Ty = Ctx.getCanonicalType(PD->getType());
1213 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001214 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001215 }
1216 }
1217
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001218 // Any special effect for the receiver?
1219 ArgEffect ReceiverEff = DoNothing;
1220
1221 // If one of the arguments in the selector has the keyword 'delegate' we
1222 // should stop tracking the reference count for the receiver. This is
1223 // because the reference count is quite possibly handled by a delegate
1224 // method.
1225 if (S.isKeywordSelector()) {
1226 const std::string &str = S.getAsString();
1227 assert(!str.empty());
1228 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1229 }
1230
Ted Kremenek174a0772009-04-23 23:08:22 +00001231 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001232 if (isTrackedObjCObjectType(RetTy)) {
1233 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1234 // by instance methods.
Ted Kremenek613ef972009-05-15 15:49:00 +00001235 RetEffect E = followsFundamentalRule(S)
1236 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001237
1238 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001239 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001240
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001241 // Look for methods that return an owned core foundation object.
1242 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek613ef972009-05-15 15:49:00 +00001243 RetEffect E = followsFundamentalRule(S)
1244 ? RetEffect::MakeOwned(RetEffect::CF, true)
1245 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001246
1247 return getPersistentSummary(E, ReceiverEff, MayEscape);
1248 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001249
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001250 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001251 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001252
Ted Kremenek2f226732009-05-04 05:31:22 +00001253 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001254}
1255
1256RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001257RetainSummaryManager::getInstanceMethodSummary(Selector S,
1258 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001259 const ObjCInterfaceDecl* ID,
1260 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001261 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001262
Ted Kremeneka821b792009-04-29 05:04:30 +00001263 // Look up a summary in our summary cache.
1264 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001265
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001266 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001267 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001268
Ted Kremeneka56ae162009-05-03 05:20:50 +00001269 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001270 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001271
Ted Kremenek2f226732009-05-04 05:31:22 +00001272 // "initXXX": pass-through for receiver.
Ted Kremenek613ef972009-05-15 15:49:00 +00001273 if (deriveNamingConvention(S) == InitRule)
Ted Kremenek2f226732009-05-04 05:31:22 +00001274 Summ = getInitMethodSummary(RetTy);
1275 else
1276 Summ = getCommonMethodSummary(MD, S, RetTy);
1277
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001278 // Annotations override defaults.
1279 updateSummaryFromAnnotations(*Summ, MD);
1280
Ted Kremenek2f226732009-05-04 05:31:22 +00001281 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001282 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001283 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001284}
1285
Ted Kremeneka7722b72008-05-06 21:26:51 +00001286RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001287RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001288 const ObjCInterfaceDecl *ID,
1289 const ObjCMethodDecl *MD,
1290 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001291
Ted Kremenek578498a2009-04-29 00:42:39 +00001292 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001293 ObjCMethodSummariesTy::iterator I =
1294 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001295
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001296 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001297 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001298
1299 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001300
1301 // Annotations override defaults.
1302 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001303
Ted Kremenek2f226732009-05-04 05:31:22 +00001304 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001305 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001306 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001307}
1308
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001309void RetainSummaryManager::InitializeClassMethodSummaries() {
1310 assert(ScratchArgs.isEmpty());
1311 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001312
Ted Kremenek272aa852008-06-25 21:21:56 +00001313 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1314 // NSObject and its derivatives.
1315 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1316 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1317 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001318
1319 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001320 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001321 GetNullarySelector("currentHandler", Ctx),
1322 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001323
1324 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001325 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001326 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1327 GetUnarySelector("addObject", Ctx),
1328 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001329 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001330
1331 // Create the summaries for [NSObject performSelector...]. We treat
1332 // these as 'stop tracking' for the arguments because they are often
1333 // used for delegates that can release the object. When we have better
1334 // inter-procedural analysis we can potentially do something better. This
1335 // workaround is to remove false positives.
1336 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1337 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1338 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1339 "afterDelay", NULL);
1340 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1341 "afterDelay", "inModes", NULL);
1342 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1343 "withObject", "waitUntilDone", NULL);
1344 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1345 "withObject", "waitUntilDone", "modes", NULL);
1346 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1347 "withObject", "waitUntilDone", NULL);
1348 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1349 "withObject", "waitUntilDone", "modes", NULL);
1350 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1351 "withObject", NULL);
Ted Kremenekdf100482009-05-14 21:29:16 +00001352
1353 // Specially handle NSData.
1354 RetainSummary *dataWithBytesNoCopySumm =
1355 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1356 DoNothing);
1357 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1358 "dataWithBytesNoCopy", "length", NULL);
1359 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1360 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001361}
1362
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001363void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001364
Ted Kremeneka56ae162009-05-03 05:20:50 +00001365 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001366
Ted Kremeneka7722b72008-05-06 21:26:51 +00001367 // Create the "init" selector. It just acts as a pass-through for the
1368 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001369 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
1370 getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1371 DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001372
1373 // The next methods are allocators.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001374 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001375
1376 // Create the "copy" selector.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001377 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001378
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001379 // Create the "mutableCopy" selector.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001380 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001381
Ted Kremenek266d8b62008-05-06 02:26:56 +00001382 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001383 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001384 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001385 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001386
1387 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001388 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001389 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001390
1391 // Create the "drain" selector.
1392 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001393 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001394
1395 // Create the -dealloc summary.
1396 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1397 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001398
1399 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001400 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001401 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001402
Ted Kremenekaac82832009-02-23 17:45:03 +00001403 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001404 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001405 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001406 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001407
Ted Kremenek45642a42008-08-12 18:48:50 +00001408 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001409 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1410 // self-own themselves. However, they only do this once they are displayed.
1411 // Thus, we need to track an NSWindow's display status.
1412 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001413 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001414 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1415 StopTracking,
1416 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001417
1418 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1419
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001420#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001421 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001422 "styleMask", "backing", "defer", NULL);
1423
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001424 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001425 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001426#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001427
Ted Kremenek45642a42008-08-12 18:48:50 +00001428 // For NSPanel (which subclasses NSWindow), allocated objects are not
1429 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001430 // FIXME: For now we don't track NSPanels. object for the same reason
1431 // as for NSWindow objects.
1432 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1433
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001434#if 0
1435 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001436 "styleMask", "backing", "defer", NULL);
1437
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001438 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001439 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001440#endif
Ted Kremenek88294222009-05-18 23:14:34 +00001441
1442 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1443 // exit a method.
1444 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek272aa852008-06-25 21:21:56 +00001445
Ted Kremenekf2717b02008-07-18 17:24:20 +00001446 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001447 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1448 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001449
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001450 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1451 "file", "lineNumber", "description", NULL);
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001452
1453 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1454 addInstMethSummary("QCRenderer", AllocSumm,
1455 "createSnapshotImageOfType", NULL);
1456 addInstMethSummary("QCView", AllocSumm,
1457 "createSnapshotImageOfType", NULL);
1458
1459 // Create summaries for CIContext, 'createCGImage'.
1460 addInstMethSummary("CIContext", AllocSumm,
1461 "createCGImage", "fromRect", NULL);
1462 addInstMethSummary("CIContext", AllocSumm,
1463 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001464}
1465
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001466//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001467// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001468//===----------------------------------------------------------------------===//
1469
Ted Kremeneka7338b42008-03-11 06:39:11 +00001470namespace {
1471
Ted Kremenek7d421f32008-04-09 23:49:11 +00001472class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001473public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001474 enum Kind {
1475 Owned = 0, // Owning reference.
1476 NotOwned, // Reference is not owned by still valid (not freed).
1477 Released, // Object has been released.
1478 ReturnedOwned, // Returned object passes ownership to caller.
1479 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001480 ERROR_START,
1481 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1482 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001483 ErrorUseAfterRelease, // Object used after released.
1484 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001485 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001486 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001487 ErrorLeakReturned, // A memory leak due to the returning method not having
1488 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001489 ErrorGCLeakReturned,
1490 ErrorOverAutorelease,
1491 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001492 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001493
1494private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001495 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001496 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001497 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001498 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001499 QualType T;
1500
Ted Kremenek4d99d342009-05-08 20:01:42 +00001501 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1502 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001503
Ted Kremenek68621b92009-01-28 05:56:51 +00001504 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001505 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001506
1507public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001508 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001509
1510 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001511
Ted Kremenek4d99d342009-05-08 20:01:42 +00001512 unsigned getCount() const { return Cnt; }
1513 unsigned getAutoreleaseCount() const { return ACnt; }
1514 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1515 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001516 void setCount(unsigned i) { Cnt = i; }
1517 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001518
Ted Kremenek272aa852008-06-25 21:21:56 +00001519 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001520
1521 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001522
Ted Kremenek6537a642009-03-17 19:42:23 +00001523 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001524
Ted Kremenek6537a642009-03-17 19:42:23 +00001525 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001526
Ted Kremenekffefc352008-04-11 22:25:11 +00001527 bool isOwned() const {
1528 return getKind() == Owned;
1529 }
1530
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001531 bool isNotOwned() const {
1532 return getKind() == NotOwned;
1533 }
1534
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001535 bool isReturnedOwned() const {
1536 return getKind() == ReturnedOwned;
1537 }
1538
1539 bool isReturnedNotOwned() const {
1540 return getKind() == ReturnedNotOwned;
1541 }
1542
1543 bool isNonLeakError() const {
1544 Kind k = getKind();
1545 return isError(k) && !isLeak(k);
1546 }
1547
Ted Kremenek68621b92009-01-28 05:56:51 +00001548 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1549 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001550 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001551 }
1552
Ted Kremenek68621b92009-01-28 05:56:51 +00001553 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1554 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001555 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001556 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001557
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001558 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001559
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001560 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001561 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001562 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001563
Ted Kremenek272aa852008-06-25 21:21:56 +00001564 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001565 return RefVal(getKind(), getObjKind(), getCount() - i,
1566 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001567 }
1568
1569 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001570 return RefVal(getKind(), getObjKind(), getCount() + i,
1571 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001572 }
1573
1574 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001575 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1576 getType());
1577 }
1578
1579 RefVal autorelease() const {
1580 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1581 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001582 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001583
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001584 void Profile(llvm::FoldingSetNodeID& ID) const {
1585 ID.AddInteger((unsigned) kind);
1586 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001587 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001588 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001589 }
1590
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001591 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001592};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001593
1594void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001595 if (!T.isNull())
1596 Out << "Tracked Type:" << T.getAsString() << '\n';
1597
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001598 switch (getKind()) {
1599 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001600 case Owned: {
1601 Out << "Owned";
1602 unsigned cnt = getCount();
1603 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001604 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001605 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001606
Ted Kremenekc4f81022008-04-10 23:09:18 +00001607 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001608 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001609 unsigned cnt = getCount();
1610 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001611 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001612 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001613
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001614 case ReturnedOwned: {
1615 Out << "ReturnedOwned";
1616 unsigned cnt = getCount();
1617 if (cnt) Out << " (+ " << cnt << ")";
1618 break;
1619 }
1620
1621 case ReturnedNotOwned: {
1622 Out << "ReturnedNotOwned";
1623 unsigned cnt = getCount();
1624 if (cnt) Out << " (+ " << cnt << ")";
1625 break;
1626 }
1627
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001628 case Released:
1629 Out << "Released";
1630 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001631
1632 case ErrorDeallocGC:
1633 Out << "-dealloc (GC)";
1634 break;
1635
1636 case ErrorDeallocNotOwned:
1637 Out << "-dealloc (not-owned)";
1638 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001639
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001640 case ErrorLeak:
1641 Out << "Leaked";
1642 break;
1643
Ted Kremenek311f3d42008-10-22 23:56:21 +00001644 case ErrorLeakReturned:
1645 Out << "Leaked (Bad naming)";
1646 break;
1647
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001648 case ErrorGCLeakReturned:
1649 Out << "Leaked (GC-ed at return)";
1650 break;
1651
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001652 case ErrorUseAfterRelease:
1653 Out << "Use-After-Release [ERROR]";
1654 break;
1655
1656 case ErrorReleaseNotOwned:
1657 Out << "Release of Not-Owned [ERROR]";
1658 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001659
1660 case RefVal::ErrorOverAutorelease:
1661 Out << "Over autoreleased";
1662 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001663
1664 case RefVal::ErrorReturnedNotOwned:
1665 Out << "Non-owned object returned instead of owned";
1666 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001667 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001668
1669 if (ACnt) {
1670 Out << " [ARC +" << ACnt << ']';
1671 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001672}
Ted Kremenek0d721572008-03-11 17:48:22 +00001673
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001674} // end anonymous namespace
1675
1676//===----------------------------------------------------------------------===//
1677// RefBindings - State used to track object reference counts.
1678//===----------------------------------------------------------------------===//
1679
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001680typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001681static int RefBIndex = 0;
1682
1683namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001684 template<>
1685 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1686 static inline void* GDMIndex() { return &RefBIndex; }
1687 };
1688}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001689
1690//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001691// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001692//===----------------------------------------------------------------------===//
1693
Ted Kremenekb6578942009-02-24 19:15:11 +00001694typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1695typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1696typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001697
Ted Kremenekb6578942009-02-24 19:15:11 +00001698static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001699static int AutoRBIndex = 0;
1700
Ted Kremenekb6578942009-02-24 19:15:11 +00001701namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001702namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001703
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001704namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001705template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001706 : public GRStatePartialTrait<ARStack> {
1707 static inline void* GDMIndex() { return &AutoRBIndex; }
1708};
1709
1710template<> struct GRStateTrait<AutoreleasePoolContents>
1711 : public GRStatePartialTrait<ARPoolContents> {
1712 static inline void* GDMIndex() { return &AutoRCIndex; }
1713};
1714} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001715
Ted Kremenek681fb352009-03-20 17:34:15 +00001716static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1717 ARStack stack = state->get<AutoreleaseStack>();
1718 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1719}
1720
1721static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1722 SymbolRef sym) {
1723
1724 SymbolRef pool = GetCurrentAutoreleasePool(state);
1725 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1726 ARCounts newCnts(0);
1727
1728 if (cnts) {
1729 const unsigned *cnt = (*cnts).lookup(sym);
1730 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1731 }
1732 else
1733 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1734
1735 return state.set<AutoreleasePoolContents>(pool, newCnts);
1736}
1737
Ted Kremenek7aef4842008-04-16 20:40:59 +00001738//===----------------------------------------------------------------------===//
1739// Transfer functions.
1740//===----------------------------------------------------------------------===//
1741
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001742namespace {
1743
Ted Kremenek7d421f32008-04-09 23:49:11 +00001744class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001745public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001746 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001747 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001748 virtual void Print(std::ostream& Out, const GRState* state,
1749 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001750 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001751
1752private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001753 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1754 SummaryLogTy;
1755
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001756 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001757 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001758 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001759 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001760
Ted Kremenek708af042009-02-05 06:50:21 +00001761 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001762 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001763 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001764 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001765 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001766 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001767
Ted Kremenekb6578942009-02-24 19:15:11 +00001768 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1769 RefVal::Kind& hasErr);
1770
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001771 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1772 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001773 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001774 ExplodedNode<GRState>* Pred,
1775 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001776 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001777
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001778 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1779 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1780
1781 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1782 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1783 GenericNodeBuilder &Builder,
1784 GRExprEngine &Eng,
1785 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001786
Ted Kremenekb6578942009-02-24 19:15:11 +00001787public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001788 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001789 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001790 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1791 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001792 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1793 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001794
Ted Kremenek708af042009-02-05 06:50:21 +00001795 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001796
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001797 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001798
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001799 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1800 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001801 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001802
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001803 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001804 const LangOptions& getLangOptions() const { return LOpts; }
1805
Ted Kremenekc26c4692009-02-18 03:48:14 +00001806 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1807 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1808 return I == SummaryLog.end() ? 0 : I->second;
1809 }
1810
Ted Kremeneka7338b42008-03-11 06:39:11 +00001811 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001812
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001813 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001814 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001815 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001816 Expr* Ex,
1817 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001818 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001819 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001820 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001821
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001822 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001823 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001824 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001825 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001826 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001827
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001828
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001829 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001830 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001831 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001832 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001833 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001834
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001835 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001836 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001837 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001838 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001839 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001840
Ted Kremeneka42be302009-02-14 01:43:44 +00001841 // Stores.
1842 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1843
Ted Kremenekffefc352008-04-11 22:25:11 +00001844 // End-of-path.
1845
1846 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001847 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001848
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001849 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001850 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001851 GRStmtNodeBuilder<GRState>& Builder,
1852 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001853 Stmt* S, const GRState* state,
1854 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001855
1856 std::pair<ExplodedNode<GRState>*, GRStateRef>
1857 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001858 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1859 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001860 // Return statements.
1861
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001862 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001863 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001864 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001865 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001866 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001867
1868 // Assumptions.
1869
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001870 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001871 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001872 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001873};
1874
1875} // end anonymous namespace
1876
Ted Kremenek681fb352009-03-20 17:34:15 +00001877static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1878 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001879 if (Sym)
1880 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001881 else
1882 Out << "<pool>";
1883 Out << ":{";
1884
1885 // Get the contents of the pool.
1886 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1887 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1888 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1889
1890 Out << '}';
1891}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001892
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001893void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1894 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001895
1896
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001897
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001898 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001899
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001900 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001901 Out << sep << nl;
1902
1903 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1904 Out << (*I).first << " : ";
1905 (*I).second.print(Out);
1906 Out << nl;
1907 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001908
1909 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001910 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001911 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001912
Ted Kremenek681fb352009-03-20 17:34:15 +00001913 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1914 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1915 PrintPool(Out, *I, state);
1916
1917 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001918}
1919
Ted Kremenek47a72422009-04-29 18:50:19 +00001920//===----------------------------------------------------------------------===//
1921// Error reporting.
1922//===----------------------------------------------------------------------===//
1923
1924namespace {
1925
1926 //===-------------===//
1927 // Bug Descriptions. //
1928 //===-------------===//
1929
1930 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1931 protected:
1932 CFRefCount& TF;
1933
1934 CFRefBug(CFRefCount* tf, const char* name)
1935 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1936 public:
1937
1938 CFRefCount& getTF() { return TF; }
1939 const CFRefCount& getTF() const { return TF; }
1940
1941 // FIXME: Eventually remove.
1942 virtual const char* getDescription() const = 0;
1943
1944 virtual bool isLeak() const { return false; }
1945 };
1946
1947 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1948 public:
1949 UseAfterRelease(CFRefCount* tf)
1950 : CFRefBug(tf, "Use-after-release") {}
1951
1952 const char* getDescription() const {
1953 return "Reference-counted object is used after it is released";
1954 }
1955 };
1956
1957 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1958 public:
1959 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1960
1961 const char* getDescription() const {
1962 return "Incorrect decrement of the reference count of an "
1963 "object is not owned at this point by the caller";
1964 }
1965 };
1966
1967 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1968 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001969 DeallocGC(CFRefCount *tf)
1970 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001971
1972 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001973 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001974 }
1975 };
1976
1977 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1978 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001979 DeallocNotOwned(CFRefCount *tf)
1980 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001981
1982 const char *getDescription() const {
1983 return "-dealloc sent to object that may be referenced elsewhere";
1984 }
1985 };
1986
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001987 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1988 public:
1989 OverAutorelease(CFRefCount *tf) :
1990 CFRefBug(tf, "Object sent -autorelease too many times") {}
1991
1992 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001993 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001994 }
1995 };
1996
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001997 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1998 public:
1999 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2000 CFRefBug(tf, "Method should return an owned object") {}
2001
2002 const char *getDescription() const {
2003 return "Object with +0 retain counts returned to caller where a +1 "
2004 "(owning) retain count is expected";
2005 }
2006 };
2007
Ted Kremenek47a72422009-04-29 18:50:19 +00002008 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2009 const bool isReturn;
2010 protected:
2011 Leak(CFRefCount* tf, const char* name, bool isRet)
2012 : CFRefBug(tf, name), isReturn(isRet) {}
2013 public:
2014
2015 const char* getDescription() const { return ""; }
2016
2017 bool isLeak() const { return true; }
2018 };
2019
2020 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2021 public:
2022 LeakAtReturn(CFRefCount* tf, const char* name)
2023 : Leak(tf, name, true) {}
2024 };
2025
2026 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2027 public:
2028 LeakWithinFunction(CFRefCount* tf, const char* name)
2029 : Leak(tf, name, false) {}
2030 };
2031
2032 //===---------===//
2033 // Bug Reports. //
2034 //===---------===//
2035
2036 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2037 protected:
2038 SymbolRef Sym;
2039 const CFRefCount &TF;
2040 public:
2041 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2042 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002043 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2044
2045 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2046 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002047 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002048
2049 virtual ~CFRefReport() {}
2050
2051 CFRefBug& getBugType() {
2052 return (CFRefBug&) RangedBugReport::getBugType();
2053 }
2054 const CFRefBug& getBugType() const {
2055 return (const CFRefBug&) RangedBugReport::getBugType();
2056 }
2057
2058 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2059 const SourceRange*& end) {
2060
2061 if (!getBugType().isLeak())
2062 RangedBugReport::getRanges(BR, beg, end);
2063 else
2064 beg = end = 0;
2065 }
2066
2067 SymbolRef getSymbol() const { return Sym; }
2068
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002069 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002070 const ExplodedNode<GRState>* N);
2071
2072 std::pair<const char**,const char**> getExtraDescriptiveText();
2073
2074 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2075 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002076 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002077 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002078
Ted Kremenek47a72422009-04-29 18:50:19 +00002079 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2080 SourceLocation AllocSite;
2081 const MemRegion* AllocBinding;
2082 public:
2083 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2084 ExplodedNode<GRState> *n, SymbolRef sym,
2085 GRExprEngine& Eng);
2086
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002087 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002088 const ExplodedNode<GRState>* N);
2089
2090 SourceLocation getLocation() const { return AllocSite; }
2091 };
2092} // end anonymous namespace
2093
2094void CFRefCount::RegisterChecks(BugReporter& BR) {
2095 useAfterRelease = new UseAfterRelease(this);
2096 BR.Register(useAfterRelease);
2097
2098 releaseNotOwned = new BadRelease(this);
2099 BR.Register(releaseNotOwned);
2100
2101 deallocGC = new DeallocGC(this);
2102 BR.Register(deallocGC);
2103
2104 deallocNotOwned = new DeallocNotOwned(this);
2105 BR.Register(deallocNotOwned);
2106
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002107 overAutorelease = new OverAutorelease(this);
2108 BR.Register(overAutorelease);
2109
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002110 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2111 BR.Register(returnNotOwnedForOwned);
2112
Ted Kremenek47a72422009-04-29 18:50:19 +00002113 // First register "return" leaks.
2114 const char* name = 0;
2115
2116 if (isGCEnabled())
2117 name = "Leak of returned object when using garbage collection";
2118 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2119 name = "Leak of returned object when not using garbage collection (GC) in "
2120 "dual GC/non-GC code";
2121 else {
2122 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2123 name = "Leak of returned object";
2124 }
2125
2126 leakAtReturn = new LeakAtReturn(this, name);
2127 BR.Register(leakAtReturn);
2128
2129 // Second, register leaks within a function/method.
2130 if (isGCEnabled())
2131 name = "Leak of object when using garbage collection";
2132 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2133 name = "Leak of object when not using garbage collection (GC) in "
2134 "dual GC/non-GC code";
2135 else {
2136 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2137 name = "Leak";
2138 }
2139
2140 leakWithinFunction = new LeakWithinFunction(this, name);
2141 BR.Register(leakWithinFunction);
2142
2143 // Save the reference to the BugReporter.
2144 this->BR = &BR;
2145}
2146
2147static const char* Msgs[] = {
2148 // GC only
2149 "Code is compiled to only use garbage collection",
2150 // No GC.
2151 "Code is compiled to use reference counts",
2152 // Hybrid, with GC.
2153 "Code is compiled to use either garbage collection (GC) or reference counts"
2154 " (non-GC). The bug occurs with GC enabled",
2155 // Hybrid, without GC
2156 "Code is compiled to use either garbage collection (GC) or reference counts"
2157 " (non-GC). The bug occurs in non-GC mode"
2158};
2159
2160std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2161 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2162
2163 switch (TF.getLangOptions().getGCMode()) {
2164 default:
2165 assert(false);
2166
2167 case LangOptions::GCOnly:
2168 assert (TF.isGCEnabled());
2169 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2170
2171 case LangOptions::NonGC:
2172 assert (!TF.isGCEnabled());
2173 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2174
2175 case LangOptions::HybridGC:
2176 if (TF.isGCEnabled())
2177 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2178 else
2179 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2180 }
2181}
2182
2183static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2184 ArgEffect X) {
2185 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2186 I!=E; ++I)
2187 if (*I == X) return true;
2188
2189 return false;
2190}
2191
2192PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2193 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002194 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002195
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002196 if (!isa<PostStmt>(N->getLocation()))
2197 return NULL;
2198
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002199 // Check if the type state has changed.
2200 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002201 GRStateRef PrevSt(PrevN->getState(), StMgr);
2202 GRStateRef CurrSt(N->getState(), StMgr);
2203
2204 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2205 if (!CurrT) return NULL;
2206
2207 const RefVal& CurrV = *CurrT;
2208 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2209
2210 // Create a string buffer to constain all the useful things we want
2211 // to tell the user.
2212 std::string sbuf;
2213 llvm::raw_string_ostream os(sbuf);
2214
2215 // This is the allocation site since the previous node had no bindings
2216 // for this symbol.
2217 if (!PrevT) {
2218 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2219
2220 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2221 // Get the name of the callee (if it is available).
2222 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2223 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2224 os << "Call to function '" << FD->getNameAsString() <<'\'';
2225 else
2226 os << "function call";
2227 }
2228 else {
2229 assert (isa<ObjCMessageExpr>(S));
2230 os << "Method";
2231 }
2232
2233 if (CurrV.getObjKind() == RetEffect::CF) {
2234 os << " returns a Core Foundation object with a ";
2235 }
2236 else {
2237 assert (CurrV.getObjKind() == RetEffect::ObjC);
2238 os << " returns an Objective-C object with a ";
2239 }
2240
2241 if (CurrV.isOwned()) {
2242 os << "+1 retain count (owning reference).";
2243
2244 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2245 assert(CurrV.getObjKind() == RetEffect::CF);
2246 os << " "
2247 "Core Foundation objects are not automatically garbage collected.";
2248 }
2249 }
2250 else {
2251 assert (CurrV.isNotOwned());
2252 os << "+0 retain count (non-owning reference).";
2253 }
2254
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002255 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002256 return new PathDiagnosticEventPiece(Pos, os.str());
2257 }
2258
2259 // Gather up the effects that were performed on the object at this
2260 // program point
2261 llvm::SmallVector<ArgEffect, 2> AEffects;
2262
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002263 if (const RetainSummary *Summ =
2264 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002265 // We only have summaries attached to nodes after evaluating CallExpr and
2266 // ObjCMessageExprs.
2267 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2268
2269 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2270 // Iterate through the parameter expressions and see if the symbol
2271 // was ever passed as an argument.
2272 unsigned i = 0;
2273
2274 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2275 AI!=AE; ++AI, ++i) {
2276
2277 // Retrieve the value of the argument. Is it the symbol
2278 // we are interested in?
2279 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2280 continue;
2281
2282 // We have an argument. Get the effect!
2283 AEffects.push_back(Summ->getArg(i));
2284 }
2285 }
2286 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2287 if (Expr *receiver = ME->getReceiver())
2288 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2289 // The symbol we are tracking is the receiver.
2290 AEffects.push_back(Summ->getReceiverEffect());
2291 }
2292 }
2293 }
2294
2295 do {
2296 // Get the previous type state.
2297 RefVal PrevV = *PrevT;
2298
2299 // Specially handle -dealloc.
2300 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2301 // Determine if the object's reference count was pushed to zero.
2302 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2303 // We may not have transitioned to 'release' if we hit an error.
2304 // This case is handled elsewhere.
2305 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002306 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002307 os << "Object released by directly sending the '-dealloc' message";
2308 break;
2309 }
2310 }
2311
2312 // Specially handle CFMakeCollectable and friends.
2313 if (contains(AEffects, MakeCollectable)) {
2314 // Get the name of the function.
2315 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2316 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2317 const FunctionDecl* FD = X.getAsFunctionDecl();
2318 const std::string& FName = FD->getNameAsString();
2319
2320 if (TF.isGCEnabled()) {
2321 // Determine if the object's reference count was pushed to zero.
2322 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2323
2324 os << "In GC mode a call to '" << FName
2325 << "' decrements an object's retain count and registers the "
2326 "object with the garbage collector. ";
2327
2328 if (CurrV.getKind() == RefVal::Released) {
2329 assert(CurrV.getCount() == 0);
2330 os << "Since it now has a 0 retain count the object can be "
2331 "automatically collected by the garbage collector.";
2332 }
2333 else
2334 os << "An object must have a 0 retain count to be garbage collected. "
2335 "After this call its retain count is +" << CurrV.getCount()
2336 << '.';
2337 }
2338 else
2339 os << "When GC is not enabled a call to '" << FName
2340 << "' has no effect on its argument.";
2341
2342 // Nothing more to say.
2343 break;
2344 }
2345
2346 // Determine if the typestate has changed.
2347 if (!(PrevV == CurrV))
2348 switch (CurrV.getKind()) {
2349 case RefVal::Owned:
2350 case RefVal::NotOwned:
2351
Ted Kremenek4d99d342009-05-08 20:01:42 +00002352 if (PrevV.getCount() == CurrV.getCount()) {
2353 // Did an autorelease message get sent?
2354 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2355 return 0;
2356
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002357 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002358 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002359 break;
2360 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002361
2362 if (PrevV.getCount() > CurrV.getCount())
2363 os << "Reference count decremented.";
2364 else
2365 os << "Reference count incremented.";
2366
2367 if (unsigned Count = CurrV.getCount())
2368 os << " The object now has a +" << Count << " retain count.";
2369
2370 if (PrevV.getKind() == RefVal::Released) {
2371 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2372 os << " The object is not eligible for garbage collection until the "
2373 "retain count reaches 0 again.";
2374 }
2375
2376 break;
2377
2378 case RefVal::Released:
2379 os << "Object released.";
2380 break;
2381
2382 case RefVal::ReturnedOwned:
2383 os << "Object returned to caller as an owning reference (single retain "
2384 "count transferred to caller).";
2385 break;
2386
2387 case RefVal::ReturnedNotOwned:
2388 os << "Object returned to caller with a +0 (non-owning) retain count.";
2389 break;
2390
2391 default:
2392 return NULL;
2393 }
2394
2395 // Emit any remaining diagnostics for the argument effects (if any).
2396 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2397 E=AEffects.end(); I != E; ++I) {
2398
2399 // A bunch of things have alternate behavior under GC.
2400 if (TF.isGCEnabled())
2401 switch (*I) {
2402 default: break;
2403 case Autorelease:
2404 os << "In GC mode an 'autorelease' has no effect.";
2405 continue;
2406 case IncRefMsg:
2407 os << "In GC mode the 'retain' message has no effect.";
2408 continue;
2409 case DecRefMsg:
2410 os << "In GC mode the 'release' message has no effect.";
2411 continue;
2412 }
2413 }
2414 } while(0);
2415
2416 if (os.str().empty())
2417 return 0; // We have nothing to say!
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002418
2419 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002420 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002421 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2422
2423 // Add the range by scanning the children of the statement for any bindings
2424 // to Sym.
2425 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2426 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2427 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2428 P->addRange(Exp->getSourceRange());
2429 break;
2430 }
2431
2432 return P;
2433}
2434
2435namespace {
2436 class VISIBILITY_HIDDEN FindUniqueBinding :
2437 public StoreManager::BindingsHandler {
2438 SymbolRef Sym;
2439 const MemRegion* Binding;
2440 bool First;
2441
2442 public:
2443 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2444
2445 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2446 SVal val) {
2447
2448 SymbolRef SymV = val.getAsSymbol();
2449 if (!SymV || SymV != Sym)
2450 return true;
2451
2452 if (Binding) {
2453 First = false;
2454 return false;
2455 }
2456 else
2457 Binding = R;
2458
2459 return true;
2460 }
2461
2462 operator bool() { return First && Binding; }
2463 const MemRegion* getRegion() { return Binding; }
2464 };
2465}
2466
2467static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2468GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2469 SymbolRef Sym) {
2470
2471 // Find both first node that referred to the tracked symbol and the
2472 // memory location that value was store to.
2473 const ExplodedNode<GRState>* Last = N;
2474 const MemRegion* FirstBinding = 0;
2475
2476 while (N) {
2477 const GRState* St = N->getState();
2478 RefBindings B = St->get<RefBindings>();
2479
2480 if (!B.lookup(Sym))
2481 break;
2482
2483 FindUniqueBinding FB(Sym);
2484 StateMgr.iterBindings(St, FB);
2485 if (FB) FirstBinding = FB.getRegion();
2486
2487 Last = N;
2488 N = N->pred_empty() ? NULL : *(N->pred_begin());
2489 }
2490
2491 return std::make_pair(Last, FirstBinding);
2492}
2493
2494PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002495CFRefReport::getEndPath(BugReporterContext& BRC,
2496 const ExplodedNode<GRState>* EndN) {
2497 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002498 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002499 BRC.addNotableSymbol(Sym);
2500 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002501}
2502
2503PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002504CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2505 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002506
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002507 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002508 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002509 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002510
2511 // We are reporting a leak. Walk up the graph to get to the first node where
2512 // the symbol appeared, and also get the first VarDecl that tracked object
2513 // is stored to.
2514 const ExplodedNode<GRState>* AllocNode = 0;
2515 const MemRegion* FirstBinding = 0;
2516
2517 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002518 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002519
2520 // Get the allocate site.
2521 assert(AllocNode);
2522 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2523
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002524 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002525 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2526
2527 // Compute an actual location for the leak. Sometimes a leak doesn't
2528 // occur at an actual statement (e.g., transition between blocks; end
2529 // of function) so we need to walk the graph and compute a real location.
2530 const ExplodedNode<GRState>* LeakN = EndN;
2531 PathDiagnosticLocation L;
2532
2533 while (LeakN) {
2534 ProgramPoint P = LeakN->getLocation();
2535
2536 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2537 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2538 break;
2539 }
2540 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2541 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2542 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2543 break;
2544 }
2545 }
2546
2547 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2548 }
2549
2550 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002551 const Decl &D = BRC.getCodeDecl();
2552 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002553 }
2554
2555 std::string sbuf;
2556 llvm::raw_string_ostream os(sbuf);
2557
2558 os << "Object allocated on line " << AllocLine;
2559
2560 if (FirstBinding)
2561 os << " and stored into '" << FirstBinding->getString() << '\'';
2562
2563 // Get the retain count.
2564 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2565
2566 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2567 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2568 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2569 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002570 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002571 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002572 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002573 << "') does not contain 'copy' or otherwise starts with"
2574 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002575 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002576 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002577 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2578 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2579 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002580 << "' is potentially leaked when using garbage collection. Callers "
2581 "of this method do not expect a returned object with a +1 retain "
2582 "count since they expect the object to be managed by the garbage "
2583 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002584 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002585 else
2586 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002587 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002588
2589 return new PathDiagnosticEventPiece(L, os.str());
2590}
2591
Ted Kremenek47a72422009-04-29 18:50:19 +00002592CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2593 ExplodedNode<GRState> *n,
2594 SymbolRef sym, GRExprEngine& Eng)
2595: CFRefReport(D, tf, n, sym)
2596{
2597
2598 // Most bug reports are cached at the location where they occured.
2599 // With leaks, we want to unique them by the location where they were
2600 // allocated, and only report a single path. To do this, we need to find
2601 // the allocation site of a piece of tracked memory, which we do via a
2602 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2603 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2604 // that all ancestor nodes that represent the allocation site have the
2605 // same SourceLocation.
2606 const ExplodedNode<GRState>* AllocNode = 0;
2607
2608 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002609 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002610
2611 // Get the SourceLocation for the allocation site.
2612 ProgramPoint P = AllocNode->getLocation();
2613 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2614
2615 // Fill in the description of the bug.
2616 Description.clear();
2617 llvm::raw_string_ostream os(Description);
2618 SourceManager& SMgr = Eng.getContext().getSourceManager();
2619 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002620 os << "Potential leak ";
2621 if (tf.isGCEnabled()) {
2622 os << "(when using garbage collection) ";
2623 }
2624 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002625
2626 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2627 if (AllocBinding)
2628 os << " and stored into '" << AllocBinding->getString() << '\'';
2629}
2630
2631//===----------------------------------------------------------------------===//
2632// Main checker logic.
2633//===----------------------------------------------------------------------===//
2634
Ted Kremenek272aa852008-06-25 21:21:56 +00002635/// GetReturnType - Used to get the return type of a message expression or
2636/// function call with the intention of affixing that type to a tracked symbol.
2637/// While the the return type can be queried directly from RetEx, when
2638/// invoking class methods we augment to the return type to be that of
2639/// a pointer to the class (as opposed it just being id).
2640static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2641
2642 QualType RetTy = RetE->getType();
2643
2644 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002645 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002646 if (!PT)
2647 return RetTy;
2648
2649 // If RetEx is not a message expression just return its type.
2650 // If RetEx is a message expression, return its types if it is something
2651 /// more specific than id.
2652
2653 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2654
Steve Naroff17c03822009-02-12 17:52:19 +00002655 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002656 return RetTy;
2657
2658 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2659
2660 // At this point we know the return type of the message expression is id.
2661 // If we have an ObjCInterceDecl, we know this is a call to a class method
2662 // whose type we can resolve. In such cases, promote the return type to
2663 // Class*.
2664 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2665}
2666
2667
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002668void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002669 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002670 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002671 Expr* Ex,
2672 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002673 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002674 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002675 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002676
Ted Kremeneka7338b42008-03-11 06:39:11 +00002677 // Get the state.
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002678 GRStateManager& StateMgr = Eng.getStateManager();
2679 GRStateRef state(Builder.GetState(Pred), StateMgr);
2680 ASTContext& Ctx = StateMgr.getContext();
2681 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek227c5372008-05-06 02:41:27 +00002682
2683 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002684 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002685 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002686 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002687 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002688
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002689 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002690 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002691 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002692
Ted Kremenek74556a12009-03-26 03:35:11 +00002693 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002694 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002695 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002696 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002697 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002698 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002699 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002700 }
2701 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002702 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002703
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002704 if (isa<Loc>(V)) {
2705 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002706 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002707 continue;
2708
2709 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002710
2711 // FIXME: Either this logic should also be replicated in GRSimpleVals
2712 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002713
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002714 // FIXME: We can have collisions on the conjured symbol if the
2715 // expression *I also creates conjured symbols. We probably want
2716 // to identify conjured symbols by an expression pair: the enclosing
2717 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002718 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002719
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002720 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002721
Ted Kremenek73ec7732009-05-06 18:19:24 +00002722 if (R) {
2723 // Are we dealing with an ElementRegion? If the element type is
2724 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xuea6851b2009-05-11 14:28:14 +00002725 // is a variable region then strip off the ElementRegion.
Ted Kremenek73ec7732009-05-06 18:19:24 +00002726 // FIXME: We really need to think about this for the general case
2727 // as sometimes we are reasoning about arrays and other times
2728 // about (char*), etc., is just a form of passing raw bytes.
2729 // e.g., void *p = alloca(); foo((char*)p);
2730 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2731 // Checking for 'integral type' is probably too promiscuous, but
2732 // we'll leave it in for now until we have a systematic way of
2733 // handling all of these cases. Eventually we need to come up
2734 // with an interface to StoreManager so that this logic can be
2735 // approriately delegated to the respective StoreManagers while
2736 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002737 // invalidating reference counts), probably via callbacks.
Ted Kremenek1cba5772009-05-11 22:55:17 +00002738 if (ER->getElementType()->isIntegralType()) {
2739 const MemRegion *superReg = ER->getSuperRegion();
2740 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2741 isa<ObjCIvarRegion>(superReg))
2742 R = cast<TypedRegion>(superReg);
2743 }
2744
Ted Kremenek73ec7732009-05-06 18:19:24 +00002745 // FIXME: What about layers of ElementRegions?
2746 }
2747
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002748 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002749 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002750
Ted Kremenek53b24182009-03-04 22:56:43 +00002751 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002752 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002753
Ted Kremenek53b24182009-03-04 22:56:43 +00002754 if (R->isBoundable(Ctx)) {
2755 // Set the value of the variable to be a conjured symbol.
2756 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002757 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002758
Zhongxing Xu079dc352009-04-09 06:03:54 +00002759 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002760 ValueManager &ValMgr = Eng.getValueManager();
2761 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002762 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002763 }
2764 else if (const RecordType *RT = T->getAsStructureType()) {
2765 // Handle structs in a not so awesome way. Here we just
2766 // eagerly bind new symbols to the fields. In reality we
2767 // should have the store manager handle this. The idea is just
2768 // to prototype some basic functionality here. All of this logic
2769 // should one day soon just go away.
2770 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2771
2772 // No record definition. There is nothing we can do.
2773 if (!RD)
2774 continue;
2775
2776 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2777
2778 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002779 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2780 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002781
2782 // For now just handle scalar fields.
2783 FieldDecl *FD = *FI;
2784 QualType FT = FD->getType();
2785
2786 if (Loc::IsLocType(FT) ||
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002787 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002788 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002789
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002790 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002791 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002792 }
2793 }
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002794 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2795 // Set the default value of the array to conjured symbol.
2796 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2797 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2798 Count);
2799 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2800 StateMgr);
2801 } else {
Ted Kremenek53b24182009-03-04 22:56:43 +00002802 // Just blast away other values.
2803 state = state.BindLoc(*MR, UnknownVal());
2804 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002805 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002806 }
2807 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002808 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002809 }
2810 else {
2811 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002812 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002813 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002814 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002815 else if (isa<nonloc::LocAsInteger>(V))
2816 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002817 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002818
Ted Kremenek272aa852008-06-25 21:21:56 +00002819 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002820 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002821 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002822 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002823 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002824 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002825 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002826 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002827 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002828 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002829 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002830 }
2831 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002832
Ted Kremenek272aa852008-06-25 21:21:56 +00002833 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002834 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002835 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002836 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002837 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002838 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002839
Ted Kremenekf2717b02008-07-18 17:24:20 +00002840 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002841 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002842
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002843 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2844 assert(Receiver);
2845 SVal V = state.GetSValAsScalarOrLoc(Receiver);
2846 bool found = false;
2847 if (SymbolRef Sym = V.getAsLocSymbol())
2848 if (state.get<RefBindings>(Sym)) {
2849 found = true;
2850 RE = Summaries.getObjAllocRetEffect();
2851 }
2852
2853 if (!found)
2854 RE = RetEffect::MakeNoRet();
2855 }
2856
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002857 switch (RE.getKind()) {
2858 default:
2859 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002860
Ted Kremenek8f90e712008-10-17 22:23:12 +00002861 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002862
Ted Kremenek455dd862008-04-11 20:23:24 +00002863 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002864 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2865 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002866
Ted Kremenek8f90e712008-10-17 22:23:12 +00002867 // FIXME: We eventually should handle structs and other compound types
2868 // that are returned by value.
2869
2870 QualType T = Ex->getType();
2871
Ted Kremenek79413a52008-11-13 06:10:40 +00002872 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002873 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002874 ValueManager &ValMgr = Eng.getValueManager();
2875 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002876 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002877 }
2878
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002879 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002880 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002881
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002882 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002883 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002884 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002885 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002886 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002887 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002888 break;
2889 }
2890
Ted Kremenek227c5372008-05-06 02:41:27 +00002891 case RetEffect::ReceiverAlias: {
2892 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002893 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002894 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002895 break;
2896 }
2897
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002898 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002899 case RetEffect::OwnedSymbol: {
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::makeOwned(RE.getObjKind(),
2905 RetT));
2906 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002907
2908 // FIXME: Add a flag to the checker where allocations are assumed to
2909 // *not fail.
2910#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002911 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2912 bool isFeasible;
2913 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2914 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2915 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002916#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002917
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002918 break;
2919 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002920
2921 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002922 case RetEffect::NotOwnedSymbol: {
2923 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002924 ValueManager &ValMgr = Eng.getValueManager();
2925 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2926 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2927 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2928 RetT));
2929 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002930 break;
2931 }
2932 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002933
Ted Kremenek0dd65012009-02-18 02:00:25 +00002934 // Generate a sink node if we are at the end of a path.
2935 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002936 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2937 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002938
2939 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002940 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002941}
2942
2943
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002944void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002945 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002946 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002947 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002948 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002949 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002950 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002951 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002952
Ted Kremenek286e9852009-05-04 04:57:00 +00002953 assert(Summ);
2954 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002955 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002956}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002957
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002958void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002959 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002960 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002961 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002962 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002963 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002964
Ted Kremenek272aa852008-06-25 21:21:56 +00002965 if (Expr* Receiver = ME->getReceiver()) {
2966 // We need the type-information of the tracked receiver object
2967 // Retrieve it from the state.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002968 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek272aa852008-06-25 21:21:56 +00002969
2970 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2971 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002972 // FIXME: Is this really working as expected? There are cases where
2973 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002974 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002975 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002976
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002977 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002978 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002979 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002980 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002981
2982 if (const PointerType* PT = Ty->getAsPointerType()) {
2983 QualType PointeeTy = PT->getPointeeType();
2984
2985 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2986 ID = IT->getDecl();
2987 }
2988 }
2989 }
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002990
2991 // FIXME: this is a hack. This may or may not be the actual method
2992 // that is called.
2993 if (!ID) {
2994 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
2995 if (const ObjCInterfaceType *p =
2996 PT->getPointeeType()->getAsObjCInterfaceType())
2997 ID = p->getDecl();
2998 }
2999
Ted Kremenek04e00302009-04-29 17:09:14 +00003000 // FIXME: The receiver could be a reference to a class, meaning that
3001 // we should use the class method.
3002 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00003003
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003004 // Special-case: are we sending a mesage to "self"?
3005 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00003006 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
3007 if (Expr* Receiver = ME->getReceiver()) {
3008 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
3009 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
3010 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
3011 // Update the summary to make the default argument effect
3012 // 'StopTracking'.
3013 Summ = Summaries.copySummary(Summ);
3014 Summ->setDefaultArgEffect(StopTracking);
3015 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003016 }
3017 }
Ted Kremenek272aa852008-06-25 21:21:56 +00003018 }
Ted Kremenek1feab292008-04-16 04:28:53 +00003019 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00003020 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00003021
Ted Kremenek286e9852009-05-04 04:57:00 +00003022 if (!Summ)
3023 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00003024
Ted Kremenek286e9852009-05-04 04:57:00 +00003025 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00003026 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00003027}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003028
3029namespace {
3030class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
3031 GRStateRef state;
3032public:
3033 StopTrackingCallback(GRStateRef st) : state(st) {}
3034 GRStateRef getState() { return state; }
3035
3036 bool VisitSymbol(SymbolRef sym) {
3037 state = state.remove<RefBindings>(sym);
3038 return true;
3039 }
Ted Kremenek926abf22008-05-06 04:20:12 +00003040
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003041 const GRState* getState() const { return state.getState(); }
3042};
3043} // end anonymous namespace
3044
3045
Ted Kremeneka42be302009-02-14 01:43:44 +00003046void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00003047 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00003048 bool escapes = false;
3049
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003050 // A value escapes in three possible cases (this may change):
3051 //
3052 // (1) we are binding to something that is not a memory region.
3053 // (2) we are binding to a memregion that does not have stack storage
3054 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003055 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00003056 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003057
Ted Kremeneka42be302009-02-14 01:43:44 +00003058 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003059 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003060 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003061 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3062 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003063
3064 if (!escapes) {
3065 // To test (3), generate a new state with the binding removed. If it is
3066 // the same state, then it escapes (since the store cannot represent
3067 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00003068 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003069 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003070 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003071
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003072 // If our store can represent the binding and we aren't storing to something
3073 // that doesn't have local storage then just return and have the simulation
3074 // state continue as is.
3075 if (!escapes)
3076 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003077
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003078 // Otherwise, find all symbols referenced by 'val' that we are tracking
3079 // and stop tracking them.
3080 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003081}
3082
Ted Kremenek541db372008-04-24 23:57:27 +00003083
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003084 // Return statements.
3085
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003086void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003087 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003088 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003089 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003090 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003091
3092 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003093 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003094 return;
3095
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003096 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00003097 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003098
Ted Kremenek74556a12009-03-26 03:35:11 +00003099 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003100 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003101
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003102 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003103 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003104
3105 if (!T)
3106 return;
3107
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003108 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003109 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003110
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003111 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003112 case RefVal::Owned: {
3113 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003114 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003115 X.setCount(cnt - 1);
3116 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003117 break;
3118 }
3119
3120 case RefVal::NotOwned: {
3121 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003122 if (cnt) {
3123 X.setCount(cnt - 1);
3124 X = X ^ RefVal::ReturnedOwned;
3125 }
3126 else {
3127 X = X ^ RefVal::ReturnedNotOwned;
3128 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003129 break;
3130 }
3131
3132 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003133 return;
3134 }
3135
3136 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003137 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003138 Pred = Builder.MakeNode(Dst, S, Pred, state);
3139
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003140 // Did we cache out?
3141 if (!Pred)
3142 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003143
3144 // Update the autorelease counts.
3145 static unsigned autoreleasetag = 0;
3146 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3147 bool stop = false;
3148 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3149 X, stop);
3150
3151 // Did we cache out?
3152 if (!Pred || stop)
3153 return;
3154
3155 // Get the updated binding.
3156 T = state.get<RefBindings>(Sym);
3157 assert(T);
3158 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003159
Ted Kremenek47a72422009-04-29 18:50:19 +00003160 // Any leaks or other errors?
3161 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003162 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003163 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003164 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003165 RetEffect RE = Summ.getRetEffect();
3166 bool hasError = false;
3167
Ted Kremenek5b44a402009-05-16 01:38:01 +00003168 if (RE.getKind() != RetEffect::NoRet) {
3169 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3170 // Things are more complicated with garbage collection. If the
3171 // returned object is suppose to be an Objective-C object, we have
3172 // a leak (as the caller expects a GC'ed object) because no
3173 // method should return ownership unless it returns a CF object.
3174 X = X ^ RefVal::ErrorGCLeakReturned;
3175
3176 // Keep this false until this is properly tested.
3177 hasError = true;
3178 }
3179 else if (!RE.isOwned()) {
3180 // Either we are using GC and the returned object is a CF type
3181 // or we aren't using GC. In either case, we expect that the
3182 // enclosing method is expected to return ownership.
3183 hasError = true;
3184 X = X ^ RefVal::ErrorLeakReturned;
3185 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003186 }
3187
3188 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003189 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003190 static int ReturnOwnLeakTag = 0;
3191 state = state.set<RefBindings>(Sym, X);
3192 ExplodedNode<GRState> *N =
3193 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3194 if (N) {
3195 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003196 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3197 N, Sym, Eng);
3198 BR->EmitReport(report);
3199 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003200 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003201 }
3202 }
3203 else if (X.isReturnedNotOwned()) {
3204 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3205 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3206 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3207 if (Summ.getRetEffect().isOwned()) {
3208 // Trying to return a not owned object to a caller expecting an
3209 // owned object.
3210
3211 static int ReturnNotOwnedForOwnedTag = 0;
3212 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3213 if (ExplodedNode<GRState> *N =
3214 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3215 state, Pred)) {
3216 CFRefReport *report =
3217 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3218 *this, N, Sym);
3219 BR->EmitReport(report);
3220 }
3221 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003222 }
3223 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003224}
3225
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003226// Assumptions.
3227
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003228const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3229 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003230 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003231 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003232
3233 // FIXME: We may add to the interface of EvalAssume the list of symbols
3234 // whose assumptions have changed. For now we just iterate through the
3235 // bindings and check if any of the tracked symbols are NULL. This isn't
3236 // too bad since the number of symbols we will track in practice are
3237 // probably small and EvalAssume is only called at branches and a few
3238 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003239 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003240
3241 if (B.isEmpty())
3242 return St;
3243
3244 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003245
3246 GRStateRef state(St, VMgr);
3247 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003248
3249 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003250 // Check if the symbol is null (or equal to any constant).
3251 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003252 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003253 changed = true;
3254 B = RefBFactory.Remove(B, I.getKey());
3255 }
3256 }
3257
Ted Kremenek91781202008-08-17 03:20:02 +00003258 if (changed)
3259 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003260
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003261 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003262}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003263
Ted Kremenekb6578942009-02-24 19:15:11 +00003264GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3265 RefVal V, ArgEffect E,
3266 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003267
3268 // In GC mode [... release] and [... retain] do nothing.
3269 switch (E) {
3270 default: break;
3271 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3272 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003273 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003274 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3275 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003276 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003277
Ted Kremenek6537a642009-03-17 19:42:23 +00003278 // Handle all use-after-releases.
3279 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3280 V = V ^ RefVal::ErrorUseAfterRelease;
3281 hasErr = V.getKind();
3282 return state.set<RefBindings>(sym, V);
3283 }
3284
Ted Kremenek0d721572008-03-11 17:48:22 +00003285 switch (E) {
3286 default:
3287 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003288
3289 case Dealloc:
3290 // Any use of -dealloc in GC is *bad*.
3291 if (isGCEnabled()) {
3292 V = V ^ RefVal::ErrorDeallocGC;
3293 hasErr = V.getKind();
3294 break;
3295 }
3296
3297 switch (V.getKind()) {
3298 default:
3299 assert(false && "Invalid case.");
3300 case RefVal::Owned:
3301 // The object immediately transitions to the released state.
3302 V = V ^ RefVal::Released;
3303 V.clearCounts();
3304 return state.set<RefBindings>(sym, V);
3305 case RefVal::NotOwned:
3306 V = V ^ RefVal::ErrorDeallocNotOwned;
3307 hasErr = V.getKind();
3308 break;
3309 }
3310 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003311
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003312 case NewAutoreleasePool:
3313 assert(!isGCEnabled());
3314 return state.add<AutoreleaseStack>(sym);
3315
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003316 case MayEscape:
3317 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003318 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003319 break;
3320 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003321
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003322 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003323
Ted Kremenekede40b72008-07-09 18:11:16 +00003324 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003325 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003326 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003327
Ted Kremenek9b112d22009-01-28 21:44:40 +00003328 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003329 if (isGCEnabled())
3330 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003331
3332 // Update the autorelease counts.
3333 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003334 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003335 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003336
Ted Kremenek227c5372008-05-06 02:41:27 +00003337 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003338 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003339
Ted Kremenek0d721572008-03-11 17:48:22 +00003340 case IncRef:
3341 switch (V.getKind()) {
3342 default:
3343 assert(false);
3344
3345 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003346 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003347 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003348 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003349 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003350 // Non-GC cases are handled above.
3351 assert(isGCEnabled());
3352 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003353 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003354 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003355 break;
3356
Ted Kremenek272aa852008-06-25 21:21:56 +00003357 case SelfOwn:
3358 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003359 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003360 case DecRef:
3361 switch (V.getKind()) {
3362 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003363 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003364 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003365
Ted Kremenek272aa852008-06-25 21:21:56 +00003366 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003367 assert(V.getCount() > 0);
3368 if (V.getCount() == 1) V = V ^ RefVal::Released;
3369 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003370 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003371
Ted Kremenek272aa852008-06-25 21:21:56 +00003372 case RefVal::NotOwned:
3373 if (V.getCount() > 0)
3374 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003375 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003376 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003377 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003378 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003379 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003380
Ted Kremenek0d721572008-03-11 17:48:22 +00003381 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003382 // Non-GC cases are handled above.
3383 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003384 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003385 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003386 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003387 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003388 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003389 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003390 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003391}
3392
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003393//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003394// Handle dead symbols and end-of-path.
3395//===----------------------------------------------------------------------===//
3396
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003397std::pair<ExplodedNode<GRState>*, GRStateRef>
3398CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3399 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003400 GRExprEngine &Eng,
3401 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003402
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003403 unsigned ACnt = V.getAutoreleaseCount();
3404 stop = false;
3405
3406 // No autorelease counts? Nothing to be done.
3407 if (!ACnt)
3408 return std::make_pair(Pred, state);
3409
3410 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3411 unsigned Cnt = V.getCount();
3412
Ted Kremenek0603cf52009-05-11 15:26:06 +00003413 // FIXME: Handle sending 'autorelease' to already released object.
3414
3415 if (V.getKind() == RefVal::ReturnedOwned)
3416 ++Cnt;
3417
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003418 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003419 if (ACnt == Cnt) {
3420 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003421 if (V.getKind() == RefVal::ReturnedOwned)
3422 V = V ^ RefVal::ReturnedNotOwned;
3423 else
3424 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003425 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003426 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003427 V.setCount(Cnt - ACnt);
3428 V.setAutoreleaseCount(0);
3429 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003430 state = state.set<RefBindings>(Sym, V);
3431 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3432 stop = (N == 0);
3433 return std::make_pair(N, state);
3434 }
3435
3436 // Woah! More autorelease counts then retain counts left.
3437 // Emit hard error.
3438 stop = true;
3439 V = V ^ RefVal::ErrorOverAutorelease;
3440 state = state.set<RefBindings>(Sym, V);
3441
3442 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003443 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003444
3445 std::string sbuf;
3446 llvm::raw_string_ostream os(sbuf);
Ted Kremenek2e6ce412009-05-15 06:02:08 +00003447 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekbd271be2009-05-10 05:11:21 +00003448 if (V.getAutoreleaseCount() > 1)
3449 os << V.getAutoreleaseCount() << " times";
3450 os << " but the object has ";
3451 if (V.getCount() == 0)
3452 os << "zero (locally visible)";
3453 else
3454 os << "+" << V.getCount();
3455 os << " retain counts";
3456
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003457 CFRefReport *report =
3458 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003459 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003460 BR->EmitReport(report);
3461 }
3462
3463 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003464}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003465
3466GRStateRef
3467CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3468 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3469
3470 bool hasLeak = V.isOwned() ||
3471 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3472
3473 if (!hasLeak)
3474 return state.remove<RefBindings>(sid);
3475
3476 Leaked.push_back(sid);
3477 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3478}
3479
3480ExplodedNode<GRState>*
3481CFRefCount::ProcessLeaks(GRStateRef state,
3482 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3483 GenericNodeBuilder &Builder,
3484 GRExprEngine& Eng,
3485 ExplodedNode<GRState> *Pred) {
3486
3487 if (Leaked.empty())
3488 return Pred;
3489
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003490 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003491 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003492
3493 if (N) {
3494 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3495 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3496
3497 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3498 : leakAtReturn);
3499 assert(BT && "BugType not initialized.");
3500 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3501 BR->EmitReport(report);
3502 }
3503 }
3504
3505 return N;
3506}
3507
Ted Kremenek708af042009-02-05 06:50:21 +00003508void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3509 GREndPathNodeBuilder<GRState>& Builder) {
3510
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003511 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003512 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003513 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003514 ExplodedNode<GRState> *Pred = 0;
3515
3516 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003517 bool stop = false;
3518 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3519 (*I).first,
3520 (*I).second, stop);
3521
3522 if (stop)
3523 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003524 }
3525
3526 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003527 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003528
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003529 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3530 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3531
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003532 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003533}
3534
3535void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3536 GRExprEngine& Eng,
3537 GRStmtNodeBuilder<GRState>& Builder,
3538 ExplodedNode<GRState>* Pred,
3539 Stmt* S,
3540 const GRState* St,
3541 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003542
3543 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003544 RefBindings B = state.get<RefBindings>();
3545
3546 // Update counts from autorelease pools
3547 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3548 E = SymReaper.dead_end(); I != E; ++I) {
3549 SymbolRef Sym = *I;
3550 if (const RefVal* T = B.lookup(Sym)){
3551 // Use the symbol as the tag.
3552 // FIXME: This might not be as unique as we would like.
3553 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003554 bool stop = false;
3555 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3556 Sym, *T, stop);
3557 if (stop)
3558 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003559 }
3560 }
3561
3562 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003563 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003564
3565 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003566 E = SymReaper.dead_end(); I != E; ++I) {
3567 if (const RefVal* T = B.lookup(*I))
3568 state = HandleSymbolDeath(state, *I, *T, Leaked);
3569 }
Ted Kremenek708af042009-02-05 06:50:21 +00003570
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003571 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003572 {
3573 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3574 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3575 }
Ted Kremenek708af042009-02-05 06:50:21 +00003576
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003577 // Did we cache out?
3578 if (!Pred)
3579 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003580
3581 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003582 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003583
Ted Kremenek876d8df2009-02-19 23:47:02 +00003584 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003585 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3586
Ted Kremenek876d8df2009-02-19 23:47:02 +00003587 state = state.set<RefBindings>(B);
3588 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003589}
3590
3591void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3592 GRStmtNodeBuilder<GRState>& Builder,
3593 Expr* NodeExpr, Expr* ErrorExpr,
3594 ExplodedNode<GRState>* Pred,
3595 const GRState* St,
3596 RefVal::Kind hasErr, SymbolRef Sym) {
3597 Builder.BuildSinks = true;
3598 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3599
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003600 if (!N)
3601 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003602
3603 CFRefBug *BT = 0;
3604
Ted Kremenek6537a642009-03-17 19:42:23 +00003605 switch (hasErr) {
3606 default:
3607 assert(false && "Unhandled error.");
3608 return;
3609 case RefVal::ErrorUseAfterRelease:
3610 BT = static_cast<CFRefBug*>(useAfterRelease);
3611 break;
3612 case RefVal::ErrorReleaseNotOwned:
3613 BT = static_cast<CFRefBug*>(releaseNotOwned);
3614 break;
3615 case RefVal::ErrorDeallocGC:
3616 BT = static_cast<CFRefBug*>(deallocGC);
3617 break;
3618 case RefVal::ErrorDeallocNotOwned:
3619 BT = static_cast<CFRefBug*>(deallocNotOwned);
3620 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003621 }
3622
Ted Kremenekc26c4692009-02-18 03:48:14 +00003623 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003624 report->addRange(ErrorExpr->getSourceRange());
3625 BR->EmitReport(report);
3626}
3627
3628//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003629// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003630//===----------------------------------------------------------------------===//
3631
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003632GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3633 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003634 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003635}