blob: 532d16da0f0e8149afbc91b6439af653af83b023 [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;
Ted Kremenekd27ed0d2009-06-05 23:18:01 +0000639
640 /// ObjCInitRetE - Default return effect for init methods returning Objective-C
641 /// objects.
642 RetEffect ObjCInitRetE;
643
Ted Kremenek286e9852009-05-04 04:57:00 +0000644 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000645 RetainSummary* StopSummary;
646
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000647 //==-----------------------------------------------------------------==//
648 // Methods.
649 //==-----------------------------------------------------------------==//
650
Ted Kremenek272aa852008-06-25 21:21:56 +0000651 /// getArgEffects - Returns a persistent ArgEffects object based on the
652 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000653 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000654
Ted Kremenek562c1302008-05-05 16:51:50 +0000655 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000656
657public:
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000658 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
659
Ted Kremenek2f226732009-05-04 05:31:22 +0000660 RetainSummary *getDefaultSummary() {
661 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
662 return new (Summ) RetainSummary(DefaultSummary);
663 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000664
Ted Kremenek064ef322009-02-23 16:51:39 +0000665 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000666
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000667 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
668 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000669 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000670
Ted Kremeneka56ae162009-05-03 05:20:50 +0000671 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000672 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000673 ArgEffect DefaultEff = MayEscape,
674 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000675
Ted Kremenek266d8b62008-05-06 02:26:56 +0000676 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000677 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000678 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000679 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000680 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000681
Ted Kremeneka821b792009-04-29 05:04:30 +0000682 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000683 if (StopSummary)
684 return StopSummary;
685
686 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
687 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000688
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000689 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000690 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000691
Ted Kremeneka821b792009-04-29 05:04:30 +0000692 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000693
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000694 void InitializeClassMethodSummaries();
695 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000696
Ted Kremenek9b42e062009-05-03 04:42:10 +0000697 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000698 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000699
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000700private:
701
Ted Kremenekf2717b02008-07-18 17:24:20 +0000702 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
703 RetainSummary* Summ) {
704 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
705 }
706
Ted Kremenek272aa852008-06-25 21:21:56 +0000707 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
708 ObjCClassMethodSummaries[S] = Summ;
709 }
710
711 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
712 ObjCMethodSummaries[S] = Summ;
713 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000714
715 void addClassMethSummary(const char* Cls, const char* nullaryName,
716 RetainSummary *Summ) {
717 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
718 Selector S = GetNullarySelector(nullaryName, Ctx);
719 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
720 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000721
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000722 void addInstMethSummary(const char* Cls, const char* nullaryName,
723 RetainSummary *Summ) {
724 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
725 Selector S = GetNullarySelector(nullaryName, Ctx);
726 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
727 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000728
729 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000730 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000731
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000732 while (const char* s = va_arg(argp, const char*))
733 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000734
735 return Ctx.Selectors.getSelector(II.size(), &II[0]);
736 }
737
738 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
739 RetainSummary* Summ, va_list argp) {
740 Selector S = generateSelector(argp);
741 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000742 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000743
744 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
745 va_list argp;
746 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000747 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000748 va_end(argp);
749 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000750
751 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
752 va_list argp;
753 va_start(argp, Summ);
754 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
755 va_end(argp);
756 }
757
758 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
759 va_list argp;
760 va_start(argp, Summ);
761 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
762 va_end(argp);
763 }
764
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000765 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000766 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
767 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000768 DoNothing, DoNothing, true);
769 va_list argp;
770 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000771 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000772 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000773 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000774
Ted Kremeneka7338b42008-03-11 06:39:11 +0000775public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000776
777 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000778 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000779 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000780 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000781 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
782 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenekd27ed0d2009-06-05 23:18:01 +0000783 ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned()
784 : RetEffect::MakeOwnedWhenTrackedReceiver()),
Ted Kremenek286e9852009-05-04 04:57:00 +0000785 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
786 RetEffect::MakeNoRet() /* return effect */,
Ted Kremeneka13b0862009-05-11 18:30:24 +0000787 MayEscape, /* default argument effect */
788 DoNothing /* receiver effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000789 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000790
791 InitializeClassMethodSummaries();
792 InitializeMethodSummaries();
793 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000794
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000795 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000796
Ted Kremenekd13c1872008-06-24 03:56:45 +0000797 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000798
Ted Kremenek314b1952009-04-29 23:03:22 +0000799 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
800 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000801 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000802 ID, ME->getMethodDecl(), ME->getType());
803 }
804
Ted Kremenek04e00302009-04-29 17:09:14 +0000805 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000806 const ObjCInterfaceDecl* ID,
807 const ObjCMethodDecl *MD,
808 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000809
810 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000811 const ObjCInterfaceDecl *ID,
812 const ObjCMethodDecl *MD,
813 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000814
815 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
816 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
817 ME->getClassInfo().first,
818 ME->getMethodDecl(), ME->getType());
819 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000820
821 /// getMethodSummary - This version of getMethodSummary is used to query
822 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000823 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
824 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000825 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000826 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000827 IdentifierInfo *ClsName = ID->getIdentifier();
828 QualType ResultTy = MD->getResultType();
829
Ted Kremenek81eb4642009-04-30 05:47:23 +0000830 // Resolve the method decl last.
831 if (const ObjCMethodDecl *InterfaceMD =
832 ResolveToInterfaceMethodDecl(MD, Ctx))
833 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000834
Ted Kremenek91b89a42009-04-29 17:17:48 +0000835 if (MD->isInstanceMethod())
836 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
837 else
838 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
839 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000840
Ted Kremenek314b1952009-04-29 23:03:22 +0000841 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
842 Selector S, QualType RetTy);
843
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000844 void updateSummaryFromAnnotations(RetainSummary &Summ,
845 const ObjCMethodDecl *MD);
846
847 void updateSummaryFromAnnotations(RetainSummary &Summ,
848 const FunctionDecl *FD);
849
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000850 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000851
852 RetainSummary *copySummary(RetainSummary *OldSumm) {
853 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
854 new (Summ) RetainSummary(*OldSumm);
855 return Summ;
856 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000857};
858
859} // end anonymous namespace
860
861//===----------------------------------------------------------------------===//
862// Implementation of checker data structures.
863//===----------------------------------------------------------------------===//
864
Ted Kremeneka56ae162009-05-03 05:20:50 +0000865RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000866
Ted Kremeneka56ae162009-05-03 05:20:50 +0000867ArgEffects RetainSummaryManager::getArgEffects() {
868 ArgEffects AE = ScratchArgs;
869 ScratchArgs = AF.GetEmptyMap();
870 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000871}
872
Ted Kremenek266d8b62008-05-06 02:26:56 +0000873RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000874RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000875 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000876 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000877 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000878 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000879 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000880 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000881 return Summ;
882}
883
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000884//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000885// Predicates.
886//===----------------------------------------------------------------------===//
887
Ted Kremenek9b42e062009-05-03 04:42:10 +0000888bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000889 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000890 return false;
891
Ted Kremenek0d813552009-04-23 22:11:07 +0000892 // We assume that id<..>, id, and "Class" all represent tracked objects.
893 const PointerType *PT = Ty->getAsPointerType();
894 if (PT == 0)
895 return true;
896
897 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000898
899 // We assume that id<..>, id, and "Class" all represent tracked objects.
900 if (!OT)
901 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000902
Ted Kremenek5b44a402009-05-16 01:38:01 +0000903 // Does the interface subclass NSObject?
904 // FIXME: We can memoize here if this gets too expensive.
Ted Kremenek35920ed2009-01-07 00:39:56 +0000905 ObjCInterfaceDecl* ID = OT->getDecl();
906
Ted Kremenek5b44a402009-05-16 01:38:01 +0000907 // Assume that anything declared with a forward declaration and no
908 // @interface subclasses NSObject.
909 if (ID->isForwardDecl())
910 return true;
911
912 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
913
914
Ted Kremenek35920ed2009-01-07 00:39:56 +0000915 for ( ; ID ; ID = ID->getSuperClass())
916 if (ID->getIdentifier() == NSObjectII)
917 return true;
918
919 return false;
920}
921
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000922bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
923 return isRefType(T, "CF") || // Core Foundation.
924 isRefType(T, "CG") || // Core Graphics.
925 isRefType(T, "DADisk") || // Disk Arbitration API.
926 isRefType(T, "DADissenter") ||
927 isRefType(T, "DASessionRef");
928}
929
Ted Kremenek35920ed2009-01-07 00:39:56 +0000930//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000931// Summary creation for functions (largely uses of Core Foundation).
932//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000933
Ted Kremenek17144e82009-01-12 21:45:02 +0000934static bool isRetain(FunctionDecl* FD, const char* FName) {
935 const char* loc = strstr(FName, "Retain");
936 return loc && loc[sizeof("Retain")-1] == '\0';
937}
938
939static bool isRelease(FunctionDecl* FD, const char* FName) {
940 const char* loc = strstr(FName, "Release");
941 return loc && loc[sizeof("Release")-1] == '\0';
942}
943
Ted Kremenekd13c1872008-06-24 03:56:45 +0000944RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000945 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000946 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000947 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000948 return I->second;
949
Ted Kremenek64cddf12009-05-04 15:34:07 +0000950 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000951 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000952
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000953 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000954 // We generate "stop" summaries for implicitly defined functions.
955 if (FD->isImplicit()) {
956 S = getPersistentStopSummary();
957 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000958 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000959
Ted Kremenek064ef322009-02-23 16:51:39 +0000960 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000961 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000962 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000963 const char* FName = FD->getIdentifier()->getName();
964
Ted Kremenek38c6f022009-03-05 22:11:14 +0000965 // Strip away preceding '_'. Doing this here will effect all the checks
966 // down below.
967 while (*FName == '_') ++FName;
968
Ted Kremenek17144e82009-01-12 21:45:02 +0000969 // Inspect the result type.
970 QualType RetTy = FT->getResultType();
971
972 // FIXME: This should all be refactored into a chain of "summary lookup"
973 // filters.
974 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
975 // FIXES: <rdar://problem/6326900>
976 // This should be addressed using a API table. This strcmp is also
977 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000978 assert (ScratchArgs.isEmpty());
979 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000980 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
981 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000982 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000983
984 // Enable this code once the semantics of NSDeallocateObject are resolved
985 // for GC. <rdar://problem/6619988>
986#if 0
987 // Handle: NSDeallocateObject(id anObject);
988 // This method does allow 'nil' (although we don't check it now).
989 if (strcmp(FName, "NSDeallocateObject") == 0) {
990 return RetTy == Ctx.VoidTy
991 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
992 : getPersistentStopSummary();
993 }
994#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000995
996 // Handle: id NSMakeCollectable(CFTypeRef)
997 if (strcmp(FName, "NSMakeCollectable") == 0) {
998 S = (RetTy == Ctx.getObjCIdType())
999 ? getUnarySummary(FT, cfmakecollectable)
1000 : getPersistentStopSummary();
1001
1002 break;
1003 }
1004
1005 if (RetTy->isPointerType()) {
1006 // For CoreFoundation ('CF') types.
1007 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1008 if (isRetain(FD, FName))
1009 S = getUnarySummary(FT, cfretain);
1010 else if (strstr(FName, "MakeCollectable"))
1011 S = getUnarySummary(FT, cfmakecollectable);
1012 else
1013 S = getCFCreateGetRuleSummary(FD, FName);
1014
1015 break;
1016 }
1017
1018 // For CoreGraphics ('CG') types.
1019 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1020 if (isRetain(FD, FName))
1021 S = getUnarySummary(FT, cfretain);
1022 else
1023 S = getCFCreateGetRuleSummary(FD, FName);
1024
1025 break;
1026 }
1027
1028 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1029 if (isRefType(RetTy, "DADisk") ||
1030 isRefType(RetTy, "DADissenter") ||
1031 isRefType(RetTy, "DASessionRef")) {
1032 S = getCFCreateGetRuleSummary(FD, FName);
1033 break;
1034 }
1035
1036 break;
1037 }
1038
1039 // Check for release functions, the only kind of functions that we care
1040 // about that don't return a pointer type.
1041 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001042 // Test for 'CGCF'.
1043 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1044 FName += 4;
1045 else
1046 FName += 2;
1047
1048 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001049 S = getUnarySummary(FT, cfrelease);
1050 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001051 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001052 // Remaining CoreFoundation and CoreGraphics functions.
1053 // We use to assume that they all strictly followed the ownership idiom
1054 // and that ownership cannot be transferred. While this is technically
1055 // correct, many methods allow a tracked object to escape. For example:
1056 //
1057 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1058 // CFDictionaryAddValue(y, key, x);
1059 // CFRelease(x);
1060 // ... it is okay to use 'x' since 'y' has a reference to it
1061 //
1062 // We handle this and similar cases with the follow heuristic. If the
1063 // function name contains "InsertValue", "SetValue" or "AddValue" then
1064 // we assume that arguments may "escape."
1065 //
1066 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1067 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001068 CStrInCStrNoCase(FName, "SetValue") ||
1069 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001070 ? MayEscape : DoNothing;
1071
1072 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001073 }
1074 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001075 }
1076 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001077
1078 if (!S)
1079 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001080
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001081 // Annotations override defaults.
1082 assert(S);
1083 updateSummaryFromAnnotations(*S, FD);
1084
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001085 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001086 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001087}
1088
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001089RetainSummary*
1090RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1091 const char* FName) {
1092
Ted Kremenek562c1302008-05-05 16:51:50 +00001093 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1094 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001095
Ted Kremenek562c1302008-05-05 16:51:50 +00001096 if (strstr(FName, "Get"))
1097 return getCFSummaryGetRule(FD);
1098
Ted Kremenek286e9852009-05-04 04:57:00 +00001099 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001100}
1101
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001102RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001103RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1104 UnaryFuncKind func) {
1105
Ted Kremenek17144e82009-01-12 21:45:02 +00001106 // Sanity check that this is *really* a unary function. This can
1107 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001108 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001109 if (!FTP || FTP->getNumArgs() != 1)
1110 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001111
Ted Kremeneka56ae162009-05-03 05:20:50 +00001112 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001113
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001114 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001115 case cfretain: {
1116 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001117 return getPersistentSummary(RetEffect::MakeAlias(0),
1118 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001119 }
1120
1121 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001122 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001123 return getPersistentSummary(RetEffect::MakeNoRet(),
1124 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001125 }
1126
1127 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001128 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001129 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001130 }
1131
1132 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001133 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001134 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001135 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001136}
1137
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001138RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001139 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001140
1141 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001142 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1143 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001144 }
1145
Ted Kremenek68621b92009-01-28 05:56:51 +00001146 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001147}
1148
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001149RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001150 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001151 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1152 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001153}
1154
Ted Kremeneka7338b42008-03-11 06:39:11 +00001155//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001156// Summary creation for Selectors.
1157//===----------------------------------------------------------------------===//
1158
Ted Kremenekbcaff792008-05-06 15:44:25 +00001159RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001160RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001161 assert(ScratchArgs.isEmpty());
1162 // 'init' methods conceptually return a newly allocated object and claim
1163 // the receiver.
1164 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
Ted Kremenekd27ed0d2009-06-05 23:18:01 +00001165 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001166
1167 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001168}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001169
1170void
1171RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1172 const FunctionDecl *FD) {
1173 if (!FD)
1174 return;
1175
Ted Kremenek401674a2009-06-05 23:00:33 +00001176 QualType RetTy = FD->getResultType();
1177
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001178 // Determine if there is a special return effect for this method.
Ted Kremenek401674a2009-06-05 23:00:33 +00001179 if (isTrackedObjCObjectType(RetTy)) {
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001180 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1181 Summ.setRetEffect(ObjCAllocRetE);
1182 }
Ted Kremenek401674a2009-06-05 23:00:33 +00001183 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1184 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1185 }
1186 }
1187 else if (RetTy->getAsPointerType()) {
1188 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001189 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1190 }
1191 }
1192}
1193
1194void
1195RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1196 const ObjCMethodDecl *MD) {
1197 if (!MD)
1198 return;
1199
1200 // Determine if there is a special return effect for this method.
1201 if (isTrackedObjCObjectType(MD->getResultType())) {
1202 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1203 Summ.setRetEffect(ObjCAllocRetE);
1204 }
1205 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1206 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1207 }
1208 }
1209}
1210
Ted Kremenekbcaff792008-05-06 15:44:25 +00001211RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001212RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1213 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001214
Ted Kremenek578498a2009-04-29 00:42:39 +00001215 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001216 // Scan the method decl for 'void*' arguments. These should be treated
1217 // as 'StopTracking' because they are often used with delegates.
1218 // Delegates are a frequent form of false positives with the retain
1219 // count checker.
1220 unsigned i = 0;
1221 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1222 E = MD->param_end(); I != E; ++I, ++i)
1223 if (ParmVarDecl *PD = *I) {
1224 QualType Ty = Ctx.getCanonicalType(PD->getType());
1225 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001226 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001227 }
1228 }
1229
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001230 // Any special effect for the receiver?
1231 ArgEffect ReceiverEff = DoNothing;
1232
1233 // If one of the arguments in the selector has the keyword 'delegate' we
1234 // should stop tracking the reference count for the receiver. This is
1235 // because the reference count is quite possibly handled by a delegate
1236 // method.
1237 if (S.isKeywordSelector()) {
1238 const std::string &str = S.getAsString();
1239 assert(!str.empty());
1240 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1241 }
1242
Ted Kremenek174a0772009-04-23 23:08:22 +00001243 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001244 if (isTrackedObjCObjectType(RetTy)) {
1245 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1246 // by instance methods.
Ted Kremenek613ef972009-05-15 15:49:00 +00001247 RetEffect E = followsFundamentalRule(S)
1248 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001249
1250 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001251 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001252
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001253 // Look for methods that return an owned core foundation object.
1254 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek613ef972009-05-15 15:49:00 +00001255 RetEffect E = followsFundamentalRule(S)
1256 ? RetEffect::MakeOwned(RetEffect::CF, true)
1257 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001258
1259 return getPersistentSummary(E, ReceiverEff, MayEscape);
1260 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001261
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001262 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001263 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001264
Ted Kremenek2f226732009-05-04 05:31:22 +00001265 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001266}
1267
1268RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001269RetainSummaryManager::getInstanceMethodSummary(Selector S,
1270 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001271 const ObjCInterfaceDecl* ID,
1272 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001273 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001274
Ted Kremeneka821b792009-04-29 05:04:30 +00001275 // Look up a summary in our summary cache.
1276 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001277
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001278 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001279 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001280
Ted Kremeneka56ae162009-05-03 05:20:50 +00001281 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001282 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001283
Ted Kremenek2f226732009-05-04 05:31:22 +00001284 // "initXXX": pass-through for receiver.
Ted Kremenek613ef972009-05-15 15:49:00 +00001285 if (deriveNamingConvention(S) == InitRule)
Ted Kremenek2f226732009-05-04 05:31:22 +00001286 Summ = getInitMethodSummary(RetTy);
1287 else
1288 Summ = getCommonMethodSummary(MD, S, RetTy);
1289
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001290 // Annotations override defaults.
1291 updateSummaryFromAnnotations(*Summ, MD);
1292
Ted Kremenek2f226732009-05-04 05:31:22 +00001293 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001294 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001295 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001296}
1297
Ted Kremeneka7722b72008-05-06 21:26:51 +00001298RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001299RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001300 const ObjCInterfaceDecl *ID,
1301 const ObjCMethodDecl *MD,
1302 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001303
Ted Kremenek578498a2009-04-29 00:42:39 +00001304 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001305 ObjCMethodSummariesTy::iterator I =
1306 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001307
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001308 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001309 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001310
1311 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001312
1313 // Annotations override defaults.
1314 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001315
Ted Kremenek2f226732009-05-04 05:31:22 +00001316 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001317 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001318 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001319}
1320
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001321void RetainSummaryManager::InitializeClassMethodSummaries() {
1322 assert(ScratchArgs.isEmpty());
1323 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001324
Ted Kremenek272aa852008-06-25 21:21:56 +00001325 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1326 // NSObject and its derivatives.
1327 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1328 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1329 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001330
1331 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001332 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001333 GetNullarySelector("currentHandler", Ctx),
1334 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001335
1336 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001337 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001338 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1339 GetUnarySelector("addObject", Ctx),
1340 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001341 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001342
1343 // Create the summaries for [NSObject performSelector...]. We treat
1344 // these as 'stop tracking' for the arguments because they are often
1345 // used for delegates that can release the object. When we have better
1346 // inter-procedural analysis we can potentially do something better. This
1347 // workaround is to remove false positives.
1348 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1349 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1350 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1351 "afterDelay", NULL);
1352 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1353 "afterDelay", "inModes", NULL);
1354 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1355 "withObject", "waitUntilDone", NULL);
1356 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1357 "withObject", "waitUntilDone", "modes", NULL);
1358 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1359 "withObject", "waitUntilDone", NULL);
1360 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1361 "withObject", "waitUntilDone", "modes", NULL);
1362 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1363 "withObject", NULL);
Ted Kremenekdf100482009-05-14 21:29:16 +00001364
1365 // Specially handle NSData.
1366 RetainSummary *dataWithBytesNoCopySumm =
1367 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1368 DoNothing);
1369 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1370 "dataWithBytesNoCopy", "length", NULL);
1371 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1372 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001373}
1374
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001375void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001376
Ted Kremeneka56ae162009-05-03 05:20:50 +00001377 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001378
Ted Kremeneka7722b72008-05-06 21:26:51 +00001379 // Create the "init" selector. It just acts as a pass-through for the
1380 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001381 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
Ted Kremenekd27ed0d2009-06-05 23:18:01 +00001382 getPersistentSummary(ObjCInitRetE, DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001383
1384 // The next methods are allocators.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001385 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001386
1387 // Create the "copy" selector.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001388 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001389
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001390 // Create the "mutableCopy" selector.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001391 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001392
Ted Kremenek266d8b62008-05-06 02:26:56 +00001393 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001394 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001395 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001396 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001397
1398 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001399 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001400 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001401
1402 // Create the "drain" selector.
1403 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001404 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001405
1406 // Create the -dealloc summary.
1407 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1408 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001409
1410 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001411 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001412 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001413
Ted Kremenekaac82832009-02-23 17:45:03 +00001414 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001415 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001416 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001417 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001418
Ted Kremenek45642a42008-08-12 18:48:50 +00001419 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001420 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1421 // self-own themselves. However, they only do this once they are displayed.
1422 // Thus, we need to track an NSWindow's display status.
1423 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001424 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001425 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1426 StopTracking,
1427 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001428
1429 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1430
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001431#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001432 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001433 "styleMask", "backing", "defer", NULL);
1434
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001435 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001436 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001437#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001438
Ted Kremenek45642a42008-08-12 18:48:50 +00001439 // For NSPanel (which subclasses NSWindow), allocated objects are not
1440 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001441 // FIXME: For now we don't track NSPanels. object for the same reason
1442 // as for NSWindow objects.
1443 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1444
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001445#if 0
1446 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001447 "styleMask", "backing", "defer", NULL);
1448
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001449 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001450 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001451#endif
Ted Kremenek88294222009-05-18 23:14:34 +00001452
1453 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1454 // exit a method.
1455 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek272aa852008-06-25 21:21:56 +00001456
Ted Kremenekf2717b02008-07-18 17:24:20 +00001457 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001458 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1459 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001460
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001461 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1462 "file", "lineNumber", "description", NULL);
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001463
1464 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1465 addInstMethSummary("QCRenderer", AllocSumm,
1466 "createSnapshotImageOfType", NULL);
1467 addInstMethSummary("QCView", AllocSumm,
1468 "createSnapshotImageOfType", NULL);
1469
1470 // Create summaries for CIContext, 'createCGImage'.
1471 addInstMethSummary("CIContext", AllocSumm,
1472 "createCGImage", "fromRect", NULL);
1473 addInstMethSummary("CIContext", AllocSumm,
1474 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001475}
1476
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001477//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001478// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001479//===----------------------------------------------------------------------===//
1480
Ted Kremeneka7338b42008-03-11 06:39:11 +00001481namespace {
1482
Ted Kremenek7d421f32008-04-09 23:49:11 +00001483class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001484public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001485 enum Kind {
1486 Owned = 0, // Owning reference.
1487 NotOwned, // Reference is not owned by still valid (not freed).
1488 Released, // Object has been released.
1489 ReturnedOwned, // Returned object passes ownership to caller.
1490 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001491 ERROR_START,
1492 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1493 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001494 ErrorUseAfterRelease, // Object used after released.
1495 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001496 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001497 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001498 ErrorLeakReturned, // A memory leak due to the returning method not having
1499 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001500 ErrorGCLeakReturned,
1501 ErrorOverAutorelease,
1502 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001503 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001504
1505private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001506 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001507 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001508 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001509 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001510 QualType T;
1511
Ted Kremenek4d99d342009-05-08 20:01:42 +00001512 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1513 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001514
Ted Kremenek68621b92009-01-28 05:56:51 +00001515 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001516 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001517
1518public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001519 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001520
1521 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001522
Ted Kremenek4d99d342009-05-08 20:01:42 +00001523 unsigned getCount() const { return Cnt; }
1524 unsigned getAutoreleaseCount() const { return ACnt; }
1525 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1526 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001527 void setCount(unsigned i) { Cnt = i; }
1528 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001529
Ted Kremenek272aa852008-06-25 21:21:56 +00001530 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001531
1532 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001533
Ted Kremenek6537a642009-03-17 19:42:23 +00001534 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001535
Ted Kremenek6537a642009-03-17 19:42:23 +00001536 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001537
Ted Kremenekffefc352008-04-11 22:25:11 +00001538 bool isOwned() const {
1539 return getKind() == Owned;
1540 }
1541
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001542 bool isNotOwned() const {
1543 return getKind() == NotOwned;
1544 }
1545
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001546 bool isReturnedOwned() const {
1547 return getKind() == ReturnedOwned;
1548 }
1549
1550 bool isReturnedNotOwned() const {
1551 return getKind() == ReturnedNotOwned;
1552 }
1553
1554 bool isNonLeakError() const {
1555 Kind k = getKind();
1556 return isError(k) && !isLeak(k);
1557 }
1558
Ted Kremenek68621b92009-01-28 05:56:51 +00001559 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1560 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001561 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001562 }
1563
Ted Kremenek68621b92009-01-28 05:56:51 +00001564 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1565 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001566 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001567 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001568
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001569 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001570
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001571 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001572 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001573 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001574
Ted Kremenek272aa852008-06-25 21:21:56 +00001575 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001576 return RefVal(getKind(), getObjKind(), getCount() - i,
1577 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001578 }
1579
1580 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001581 return RefVal(getKind(), getObjKind(), getCount() + i,
1582 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001583 }
1584
1585 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001586 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1587 getType());
1588 }
1589
1590 RefVal autorelease() const {
1591 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1592 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001593 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001594
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001595 void Profile(llvm::FoldingSetNodeID& ID) const {
1596 ID.AddInteger((unsigned) kind);
1597 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001598 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001599 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001600 }
1601
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001602 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001603};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001604
1605void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001606 if (!T.isNull())
1607 Out << "Tracked Type:" << T.getAsString() << '\n';
1608
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001609 switch (getKind()) {
1610 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001611 case Owned: {
1612 Out << "Owned";
1613 unsigned cnt = getCount();
1614 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001615 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001616 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001617
Ted Kremenekc4f81022008-04-10 23:09:18 +00001618 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001619 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001620 unsigned cnt = getCount();
1621 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001622 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001623 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001624
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001625 case ReturnedOwned: {
1626 Out << "ReturnedOwned";
1627 unsigned cnt = getCount();
1628 if (cnt) Out << " (+ " << cnt << ")";
1629 break;
1630 }
1631
1632 case ReturnedNotOwned: {
1633 Out << "ReturnedNotOwned";
1634 unsigned cnt = getCount();
1635 if (cnt) Out << " (+ " << cnt << ")";
1636 break;
1637 }
1638
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001639 case Released:
1640 Out << "Released";
1641 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001642
1643 case ErrorDeallocGC:
1644 Out << "-dealloc (GC)";
1645 break;
1646
1647 case ErrorDeallocNotOwned:
1648 Out << "-dealloc (not-owned)";
1649 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001650
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001651 case ErrorLeak:
1652 Out << "Leaked";
1653 break;
1654
Ted Kremenek311f3d42008-10-22 23:56:21 +00001655 case ErrorLeakReturned:
1656 Out << "Leaked (Bad naming)";
1657 break;
1658
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001659 case ErrorGCLeakReturned:
1660 Out << "Leaked (GC-ed at return)";
1661 break;
1662
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001663 case ErrorUseAfterRelease:
1664 Out << "Use-After-Release [ERROR]";
1665 break;
1666
1667 case ErrorReleaseNotOwned:
1668 Out << "Release of Not-Owned [ERROR]";
1669 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001670
1671 case RefVal::ErrorOverAutorelease:
1672 Out << "Over autoreleased";
1673 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001674
1675 case RefVal::ErrorReturnedNotOwned:
1676 Out << "Non-owned object returned instead of owned";
1677 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001678 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001679
1680 if (ACnt) {
1681 Out << " [ARC +" << ACnt << ']';
1682 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001683}
Ted Kremenek0d721572008-03-11 17:48:22 +00001684
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001685} // end anonymous namespace
1686
1687//===----------------------------------------------------------------------===//
1688// RefBindings - State used to track object reference counts.
1689//===----------------------------------------------------------------------===//
1690
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001691typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001692static int RefBIndex = 0;
1693
1694namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001695 template<>
1696 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1697 static inline void* GDMIndex() { return &RefBIndex; }
1698 };
1699}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001700
1701//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001702// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001703//===----------------------------------------------------------------------===//
1704
Ted Kremenekb6578942009-02-24 19:15:11 +00001705typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1706typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1707typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001708
Ted Kremenekb6578942009-02-24 19:15:11 +00001709static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001710static int AutoRBIndex = 0;
1711
Ted Kremenekb6578942009-02-24 19:15:11 +00001712namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001713namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001714
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001715namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001716template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001717 : public GRStatePartialTrait<ARStack> {
1718 static inline void* GDMIndex() { return &AutoRBIndex; }
1719};
1720
1721template<> struct GRStateTrait<AutoreleasePoolContents>
1722 : public GRStatePartialTrait<ARPoolContents> {
1723 static inline void* GDMIndex() { return &AutoRCIndex; }
1724};
1725} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001726
Ted Kremenek681fb352009-03-20 17:34:15 +00001727static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1728 ARStack stack = state->get<AutoreleaseStack>();
1729 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1730}
1731
1732static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1733 SymbolRef sym) {
1734
1735 SymbolRef pool = GetCurrentAutoreleasePool(state);
1736 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1737 ARCounts newCnts(0);
1738
1739 if (cnts) {
1740 const unsigned *cnt = (*cnts).lookup(sym);
1741 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1742 }
1743 else
1744 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1745
1746 return state.set<AutoreleasePoolContents>(pool, newCnts);
1747}
1748
Ted Kremenek7aef4842008-04-16 20:40:59 +00001749//===----------------------------------------------------------------------===//
1750// Transfer functions.
1751//===----------------------------------------------------------------------===//
1752
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001753namespace {
1754
Ted Kremenek7d421f32008-04-09 23:49:11 +00001755class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001756public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001757 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001758 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001759 virtual void Print(std::ostream& Out, const GRState* state,
1760 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001761 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001762
1763private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001764 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1765 SummaryLogTy;
1766
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001767 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001768 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001769 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001770 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001771
Ted Kremenek708af042009-02-05 06:50:21 +00001772 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001773 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001774 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001775 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001776 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001777 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001778
Ted Kremenekb6578942009-02-24 19:15:11 +00001779 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1780 RefVal::Kind& hasErr);
1781
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001782 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1783 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001784 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001785 ExplodedNode<GRState>* Pred,
1786 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001787 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001788
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001789 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1790 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1791
1792 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1793 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1794 GenericNodeBuilder &Builder,
1795 GRExprEngine &Eng,
1796 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001797
Ted Kremenekb6578942009-02-24 19:15:11 +00001798public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001799 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001800 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001801 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1802 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001803 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1804 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001805
Ted Kremenek708af042009-02-05 06:50:21 +00001806 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001807
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001808 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001809
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001810 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1811 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001812 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001813
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001814 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001815 const LangOptions& getLangOptions() const { return LOpts; }
1816
Ted Kremenekc26c4692009-02-18 03:48:14 +00001817 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1818 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1819 return I == SummaryLog.end() ? 0 : I->second;
1820 }
1821
Ted Kremeneka7338b42008-03-11 06:39:11 +00001822 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001823
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001824 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001825 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001826 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001827 Expr* Ex,
1828 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001829 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001830 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001831 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001832
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001833 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001834 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001835 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001836 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001837 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001838
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001839
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001840 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001841 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001842 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001843 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001844 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001845
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001846 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001847 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001848 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001849 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001850 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001851
Ted Kremeneka42be302009-02-14 01:43:44 +00001852 // Stores.
1853 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1854
Ted Kremenekffefc352008-04-11 22:25:11 +00001855 // End-of-path.
1856
1857 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001858 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001859
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001860 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001861 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001862 GRStmtNodeBuilder<GRState>& Builder,
1863 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001864 Stmt* S, const GRState* state,
1865 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001866
1867 std::pair<ExplodedNode<GRState>*, GRStateRef>
1868 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001869 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1870 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001871 // Return statements.
1872
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001873 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001874 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001875 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001876 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001877 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001878
1879 // Assumptions.
1880
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001881 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001882 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001883 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001884};
1885
1886} // end anonymous namespace
1887
Ted Kremenek681fb352009-03-20 17:34:15 +00001888static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1889 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001890 if (Sym)
1891 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001892 else
1893 Out << "<pool>";
1894 Out << ":{";
1895
1896 // Get the contents of the pool.
1897 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1898 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1899 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1900
1901 Out << '}';
1902}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001903
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001904void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1905 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001906
1907
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001908
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001909 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001910
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001911 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001912 Out << sep << nl;
1913
1914 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1915 Out << (*I).first << " : ";
1916 (*I).second.print(Out);
1917 Out << nl;
1918 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001919
1920 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001921 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001922 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001923
Ted Kremenek681fb352009-03-20 17:34:15 +00001924 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1925 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1926 PrintPool(Out, *I, state);
1927
1928 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001929}
1930
Ted Kremenek47a72422009-04-29 18:50:19 +00001931//===----------------------------------------------------------------------===//
1932// Error reporting.
1933//===----------------------------------------------------------------------===//
1934
1935namespace {
1936
1937 //===-------------===//
1938 // Bug Descriptions. //
1939 //===-------------===//
1940
1941 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1942 protected:
1943 CFRefCount& TF;
1944
1945 CFRefBug(CFRefCount* tf, const char* name)
1946 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1947 public:
1948
1949 CFRefCount& getTF() { return TF; }
1950 const CFRefCount& getTF() const { return TF; }
1951
1952 // FIXME: Eventually remove.
1953 virtual const char* getDescription() const = 0;
1954
1955 virtual bool isLeak() const { return false; }
1956 };
1957
1958 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1959 public:
1960 UseAfterRelease(CFRefCount* tf)
1961 : CFRefBug(tf, "Use-after-release") {}
1962
1963 const char* getDescription() const {
1964 return "Reference-counted object is used after it is released";
1965 }
1966 };
1967
1968 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1969 public:
1970 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1971
1972 const char* getDescription() const {
1973 return "Incorrect decrement of the reference count of an "
1974 "object is not owned at this point by the caller";
1975 }
1976 };
1977
1978 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1979 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001980 DeallocGC(CFRefCount *tf)
1981 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001982
1983 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001984 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001985 }
1986 };
1987
1988 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1989 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001990 DeallocNotOwned(CFRefCount *tf)
1991 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001992
1993 const char *getDescription() const {
1994 return "-dealloc sent to object that may be referenced elsewhere";
1995 }
1996 };
1997
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001998 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1999 public:
2000 OverAutorelease(CFRefCount *tf) :
2001 CFRefBug(tf, "Object sent -autorelease too many times") {}
2002
2003 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00002004 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002005 }
2006 };
2007
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002008 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
2009 public:
2010 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2011 CFRefBug(tf, "Method should return an owned object") {}
2012
2013 const char *getDescription() const {
2014 return "Object with +0 retain counts returned to caller where a +1 "
2015 "(owning) retain count is expected";
2016 }
2017 };
2018
Ted Kremenek47a72422009-04-29 18:50:19 +00002019 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2020 const bool isReturn;
2021 protected:
2022 Leak(CFRefCount* tf, const char* name, bool isRet)
2023 : CFRefBug(tf, name), isReturn(isRet) {}
2024 public:
2025
2026 const char* getDescription() const { return ""; }
2027
2028 bool isLeak() const { return true; }
2029 };
2030
2031 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2032 public:
2033 LeakAtReturn(CFRefCount* tf, const char* name)
2034 : Leak(tf, name, true) {}
2035 };
2036
2037 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2038 public:
2039 LeakWithinFunction(CFRefCount* tf, const char* name)
2040 : Leak(tf, name, false) {}
2041 };
2042
2043 //===---------===//
2044 // Bug Reports. //
2045 //===---------===//
2046
2047 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2048 protected:
2049 SymbolRef Sym;
2050 const CFRefCount &TF;
2051 public:
2052 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2053 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002054 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2055
2056 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2057 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002058 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002059
2060 virtual ~CFRefReport() {}
2061
2062 CFRefBug& getBugType() {
2063 return (CFRefBug&) RangedBugReport::getBugType();
2064 }
2065 const CFRefBug& getBugType() const {
2066 return (const CFRefBug&) RangedBugReport::getBugType();
2067 }
2068
2069 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2070 const SourceRange*& end) {
2071
2072 if (!getBugType().isLeak())
2073 RangedBugReport::getRanges(BR, beg, end);
2074 else
2075 beg = end = 0;
2076 }
2077
2078 SymbolRef getSymbol() const { return Sym; }
2079
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002080 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002081 const ExplodedNode<GRState>* N);
2082
2083 std::pair<const char**,const char**> getExtraDescriptiveText();
2084
2085 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2086 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002087 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002088 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002089
Ted Kremenek47a72422009-04-29 18:50:19 +00002090 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2091 SourceLocation AllocSite;
2092 const MemRegion* AllocBinding;
2093 public:
2094 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2095 ExplodedNode<GRState> *n, SymbolRef sym,
2096 GRExprEngine& Eng);
2097
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002098 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002099 const ExplodedNode<GRState>* N);
2100
2101 SourceLocation getLocation() const { return AllocSite; }
2102 };
2103} // end anonymous namespace
2104
2105void CFRefCount::RegisterChecks(BugReporter& BR) {
2106 useAfterRelease = new UseAfterRelease(this);
2107 BR.Register(useAfterRelease);
2108
2109 releaseNotOwned = new BadRelease(this);
2110 BR.Register(releaseNotOwned);
2111
2112 deallocGC = new DeallocGC(this);
2113 BR.Register(deallocGC);
2114
2115 deallocNotOwned = new DeallocNotOwned(this);
2116 BR.Register(deallocNotOwned);
2117
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002118 overAutorelease = new OverAutorelease(this);
2119 BR.Register(overAutorelease);
2120
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002121 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2122 BR.Register(returnNotOwnedForOwned);
2123
Ted Kremenek47a72422009-04-29 18:50:19 +00002124 // First register "return" leaks.
2125 const char* name = 0;
2126
2127 if (isGCEnabled())
2128 name = "Leak of returned object when using garbage collection";
2129 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2130 name = "Leak of returned object when not using garbage collection (GC) in "
2131 "dual GC/non-GC code";
2132 else {
2133 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2134 name = "Leak of returned object";
2135 }
2136
2137 leakAtReturn = new LeakAtReturn(this, name);
2138 BR.Register(leakAtReturn);
2139
2140 // Second, register leaks within a function/method.
2141 if (isGCEnabled())
2142 name = "Leak of object when using garbage collection";
2143 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2144 name = "Leak of object when not using garbage collection (GC) in "
2145 "dual GC/non-GC code";
2146 else {
2147 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2148 name = "Leak";
2149 }
2150
2151 leakWithinFunction = new LeakWithinFunction(this, name);
2152 BR.Register(leakWithinFunction);
2153
2154 // Save the reference to the BugReporter.
2155 this->BR = &BR;
2156}
2157
2158static const char* Msgs[] = {
2159 // GC only
2160 "Code is compiled to only use garbage collection",
2161 // No GC.
2162 "Code is compiled to use reference counts",
2163 // Hybrid, with GC.
2164 "Code is compiled to use either garbage collection (GC) or reference counts"
2165 " (non-GC). The bug occurs with GC enabled",
2166 // Hybrid, without GC
2167 "Code is compiled to use either garbage collection (GC) or reference counts"
2168 " (non-GC). The bug occurs in non-GC mode"
2169};
2170
2171std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2172 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2173
2174 switch (TF.getLangOptions().getGCMode()) {
2175 default:
2176 assert(false);
2177
2178 case LangOptions::GCOnly:
2179 assert (TF.isGCEnabled());
2180 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2181
2182 case LangOptions::NonGC:
2183 assert (!TF.isGCEnabled());
2184 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2185
2186 case LangOptions::HybridGC:
2187 if (TF.isGCEnabled())
2188 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2189 else
2190 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2191 }
2192}
2193
2194static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2195 ArgEffect X) {
2196 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2197 I!=E; ++I)
2198 if (*I == X) return true;
2199
2200 return false;
2201}
2202
2203PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2204 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002205 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002206
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002207 if (!isa<PostStmt>(N->getLocation()))
2208 return NULL;
2209
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002210 // Check if the type state has changed.
2211 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002212 GRStateRef PrevSt(PrevN->getState(), StMgr);
2213 GRStateRef CurrSt(N->getState(), StMgr);
2214
2215 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2216 if (!CurrT) return NULL;
2217
2218 const RefVal& CurrV = *CurrT;
2219 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2220
2221 // Create a string buffer to constain all the useful things we want
2222 // to tell the user.
2223 std::string sbuf;
2224 llvm::raw_string_ostream os(sbuf);
2225
2226 // This is the allocation site since the previous node had no bindings
2227 // for this symbol.
2228 if (!PrevT) {
2229 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2230
2231 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2232 // Get the name of the callee (if it is available).
2233 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2234 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2235 os << "Call to function '" << FD->getNameAsString() <<'\'';
2236 else
2237 os << "function call";
2238 }
2239 else {
2240 assert (isa<ObjCMessageExpr>(S));
2241 os << "Method";
2242 }
2243
2244 if (CurrV.getObjKind() == RetEffect::CF) {
2245 os << " returns a Core Foundation object with a ";
2246 }
2247 else {
2248 assert (CurrV.getObjKind() == RetEffect::ObjC);
2249 os << " returns an Objective-C object with a ";
2250 }
2251
2252 if (CurrV.isOwned()) {
2253 os << "+1 retain count (owning reference).";
2254
2255 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2256 assert(CurrV.getObjKind() == RetEffect::CF);
2257 os << " "
2258 "Core Foundation objects are not automatically garbage collected.";
2259 }
2260 }
2261 else {
2262 assert (CurrV.isNotOwned());
2263 os << "+0 retain count (non-owning reference).";
2264 }
2265
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002266 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002267 return new PathDiagnosticEventPiece(Pos, os.str());
2268 }
2269
2270 // Gather up the effects that were performed on the object at this
2271 // program point
2272 llvm::SmallVector<ArgEffect, 2> AEffects;
2273
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002274 if (const RetainSummary *Summ =
2275 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002276 // We only have summaries attached to nodes after evaluating CallExpr and
2277 // ObjCMessageExprs.
2278 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2279
2280 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2281 // Iterate through the parameter expressions and see if the symbol
2282 // was ever passed as an argument.
2283 unsigned i = 0;
2284
2285 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2286 AI!=AE; ++AI, ++i) {
2287
2288 // Retrieve the value of the argument. Is it the symbol
2289 // we are interested in?
2290 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2291 continue;
2292
2293 // We have an argument. Get the effect!
2294 AEffects.push_back(Summ->getArg(i));
2295 }
2296 }
2297 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2298 if (Expr *receiver = ME->getReceiver())
2299 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2300 // The symbol we are tracking is the receiver.
2301 AEffects.push_back(Summ->getReceiverEffect());
2302 }
2303 }
2304 }
2305
2306 do {
2307 // Get the previous type state.
2308 RefVal PrevV = *PrevT;
2309
2310 // Specially handle -dealloc.
2311 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2312 // Determine if the object's reference count was pushed to zero.
2313 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2314 // We may not have transitioned to 'release' if we hit an error.
2315 // This case is handled elsewhere.
2316 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002317 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002318 os << "Object released by directly sending the '-dealloc' message";
2319 break;
2320 }
2321 }
2322
2323 // Specially handle CFMakeCollectable and friends.
2324 if (contains(AEffects, MakeCollectable)) {
2325 // Get the name of the function.
2326 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2327 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2328 const FunctionDecl* FD = X.getAsFunctionDecl();
2329 const std::string& FName = FD->getNameAsString();
2330
2331 if (TF.isGCEnabled()) {
2332 // Determine if the object's reference count was pushed to zero.
2333 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2334
2335 os << "In GC mode a call to '" << FName
2336 << "' decrements an object's retain count and registers the "
2337 "object with the garbage collector. ";
2338
2339 if (CurrV.getKind() == RefVal::Released) {
2340 assert(CurrV.getCount() == 0);
2341 os << "Since it now has a 0 retain count the object can be "
2342 "automatically collected by the garbage collector.";
2343 }
2344 else
2345 os << "An object must have a 0 retain count to be garbage collected. "
2346 "After this call its retain count is +" << CurrV.getCount()
2347 << '.';
2348 }
2349 else
2350 os << "When GC is not enabled a call to '" << FName
2351 << "' has no effect on its argument.";
2352
2353 // Nothing more to say.
2354 break;
2355 }
2356
2357 // Determine if the typestate has changed.
2358 if (!(PrevV == CurrV))
2359 switch (CurrV.getKind()) {
2360 case RefVal::Owned:
2361 case RefVal::NotOwned:
2362
Ted Kremenek4d99d342009-05-08 20:01:42 +00002363 if (PrevV.getCount() == CurrV.getCount()) {
2364 // Did an autorelease message get sent?
2365 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2366 return 0;
2367
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002368 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002369 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002370 break;
2371 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002372
2373 if (PrevV.getCount() > CurrV.getCount())
2374 os << "Reference count decremented.";
2375 else
2376 os << "Reference count incremented.";
2377
2378 if (unsigned Count = CurrV.getCount())
2379 os << " The object now has a +" << Count << " retain count.";
2380
2381 if (PrevV.getKind() == RefVal::Released) {
2382 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2383 os << " The object is not eligible for garbage collection until the "
2384 "retain count reaches 0 again.";
2385 }
2386
2387 break;
2388
2389 case RefVal::Released:
2390 os << "Object released.";
2391 break;
2392
2393 case RefVal::ReturnedOwned:
2394 os << "Object returned to caller as an owning reference (single retain "
2395 "count transferred to caller).";
2396 break;
2397
2398 case RefVal::ReturnedNotOwned:
2399 os << "Object returned to caller with a +0 (non-owning) retain count.";
2400 break;
2401
2402 default:
2403 return NULL;
2404 }
2405
2406 // Emit any remaining diagnostics for the argument effects (if any).
2407 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2408 E=AEffects.end(); I != E; ++I) {
2409
2410 // A bunch of things have alternate behavior under GC.
2411 if (TF.isGCEnabled())
2412 switch (*I) {
2413 default: break;
2414 case Autorelease:
2415 os << "In GC mode an 'autorelease' has no effect.";
2416 continue;
2417 case IncRefMsg:
2418 os << "In GC mode the 'retain' message has no effect.";
2419 continue;
2420 case DecRefMsg:
2421 os << "In GC mode the 'release' message has no effect.";
2422 continue;
2423 }
2424 }
2425 } while(0);
2426
2427 if (os.str().empty())
2428 return 0; // We have nothing to say!
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002429
2430 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002431 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002432 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2433
2434 // Add the range by scanning the children of the statement for any bindings
2435 // to Sym.
2436 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2437 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2438 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2439 P->addRange(Exp->getSourceRange());
2440 break;
2441 }
2442
2443 return P;
2444}
2445
2446namespace {
2447 class VISIBILITY_HIDDEN FindUniqueBinding :
2448 public StoreManager::BindingsHandler {
2449 SymbolRef Sym;
2450 const MemRegion* Binding;
2451 bool First;
2452
2453 public:
2454 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2455
2456 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2457 SVal val) {
2458
2459 SymbolRef SymV = val.getAsSymbol();
2460 if (!SymV || SymV != Sym)
2461 return true;
2462
2463 if (Binding) {
2464 First = false;
2465 return false;
2466 }
2467 else
2468 Binding = R;
2469
2470 return true;
2471 }
2472
2473 operator bool() { return First && Binding; }
2474 const MemRegion* getRegion() { return Binding; }
2475 };
2476}
2477
2478static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2479GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2480 SymbolRef Sym) {
2481
2482 // Find both first node that referred to the tracked symbol and the
2483 // memory location that value was store to.
2484 const ExplodedNode<GRState>* Last = N;
2485 const MemRegion* FirstBinding = 0;
2486
2487 while (N) {
2488 const GRState* St = N->getState();
2489 RefBindings B = St->get<RefBindings>();
2490
2491 if (!B.lookup(Sym))
2492 break;
2493
2494 FindUniqueBinding FB(Sym);
2495 StateMgr.iterBindings(St, FB);
2496 if (FB) FirstBinding = FB.getRegion();
2497
2498 Last = N;
2499 N = N->pred_empty() ? NULL : *(N->pred_begin());
2500 }
2501
2502 return std::make_pair(Last, FirstBinding);
2503}
2504
2505PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002506CFRefReport::getEndPath(BugReporterContext& BRC,
2507 const ExplodedNode<GRState>* EndN) {
2508 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002509 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002510 BRC.addNotableSymbol(Sym);
2511 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002512}
2513
2514PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002515CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2516 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002517
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002518 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002519 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002520 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002521
2522 // We are reporting a leak. Walk up the graph to get to the first node where
2523 // the symbol appeared, and also get the first VarDecl that tracked object
2524 // is stored to.
2525 const ExplodedNode<GRState>* AllocNode = 0;
2526 const MemRegion* FirstBinding = 0;
2527
2528 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002529 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002530
2531 // Get the allocate site.
2532 assert(AllocNode);
2533 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2534
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002535 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002536 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2537
2538 // Compute an actual location for the leak. Sometimes a leak doesn't
2539 // occur at an actual statement (e.g., transition between blocks; end
2540 // of function) so we need to walk the graph and compute a real location.
2541 const ExplodedNode<GRState>* LeakN = EndN;
2542 PathDiagnosticLocation L;
2543
2544 while (LeakN) {
2545 ProgramPoint P = LeakN->getLocation();
2546
2547 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2548 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2549 break;
2550 }
2551 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2552 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2553 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2554 break;
2555 }
2556 }
2557
2558 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2559 }
2560
2561 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002562 const Decl &D = BRC.getCodeDecl();
2563 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002564 }
2565
2566 std::string sbuf;
2567 llvm::raw_string_ostream os(sbuf);
2568
2569 os << "Object allocated on line " << AllocLine;
2570
2571 if (FirstBinding)
2572 os << " and stored into '" << FirstBinding->getString() << '\'';
2573
2574 // Get the retain count.
2575 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2576
2577 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2578 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2579 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2580 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002581 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002582 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002583 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002584 << "') does not contain 'copy' or otherwise starts with"
2585 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002586 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002587 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002588 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2589 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2590 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002591 << "' is potentially leaked when using garbage collection. Callers "
2592 "of this method do not expect a returned object with a +1 retain "
2593 "count since they expect the object to be managed by the garbage "
2594 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002595 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002596 else
2597 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002598 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002599
2600 return new PathDiagnosticEventPiece(L, os.str());
2601}
2602
Ted Kremenek47a72422009-04-29 18:50:19 +00002603CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2604 ExplodedNode<GRState> *n,
2605 SymbolRef sym, GRExprEngine& Eng)
2606: CFRefReport(D, tf, n, sym)
2607{
2608
2609 // Most bug reports are cached at the location where they occured.
2610 // With leaks, we want to unique them by the location where they were
2611 // allocated, and only report a single path. To do this, we need to find
2612 // the allocation site of a piece of tracked memory, which we do via a
2613 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2614 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2615 // that all ancestor nodes that represent the allocation site have the
2616 // same SourceLocation.
2617 const ExplodedNode<GRState>* AllocNode = 0;
2618
2619 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002620 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002621
2622 // Get the SourceLocation for the allocation site.
2623 ProgramPoint P = AllocNode->getLocation();
2624 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2625
2626 // Fill in the description of the bug.
2627 Description.clear();
2628 llvm::raw_string_ostream os(Description);
2629 SourceManager& SMgr = Eng.getContext().getSourceManager();
2630 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002631 os << "Potential leak ";
2632 if (tf.isGCEnabled()) {
2633 os << "(when using garbage collection) ";
2634 }
2635 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002636
2637 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2638 if (AllocBinding)
2639 os << " and stored into '" << AllocBinding->getString() << '\'';
2640}
2641
2642//===----------------------------------------------------------------------===//
2643// Main checker logic.
2644//===----------------------------------------------------------------------===//
2645
Ted Kremenek272aa852008-06-25 21:21:56 +00002646/// GetReturnType - Used to get the return type of a message expression or
2647/// function call with the intention of affixing that type to a tracked symbol.
2648/// While the the return type can be queried directly from RetEx, when
2649/// invoking class methods we augment to the return type to be that of
2650/// a pointer to the class (as opposed it just being id).
2651static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2652
2653 QualType RetTy = RetE->getType();
2654
2655 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002656 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002657 if (!PT)
2658 return RetTy;
2659
2660 // If RetEx is not a message expression just return its type.
2661 // If RetEx is a message expression, return its types if it is something
2662 /// more specific than id.
2663
2664 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2665
Steve Naroff17c03822009-02-12 17:52:19 +00002666 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002667 return RetTy;
2668
2669 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2670
2671 // At this point we know the return type of the message expression is id.
2672 // If we have an ObjCInterceDecl, we know this is a call to a class method
2673 // whose type we can resolve. In such cases, promote the return type to
2674 // Class*.
2675 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2676}
2677
2678
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002679void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002680 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002681 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002682 Expr* Ex,
2683 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002684 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002685 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002686 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002687
Ted Kremeneka7338b42008-03-11 06:39:11 +00002688 // Get the state.
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002689 GRStateManager& StateMgr = Eng.getStateManager();
2690 GRStateRef state(Builder.GetState(Pred), StateMgr);
2691 ASTContext& Ctx = StateMgr.getContext();
2692 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek227c5372008-05-06 02:41:27 +00002693
2694 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002695 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002696 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002697 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002698 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002699
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002700 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002701 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002702 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002703
Ted Kremenek74556a12009-03-26 03:35:11 +00002704 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002705 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002706 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002707 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002708 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002709 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002710 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002711 }
2712 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002713 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002714
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002715 if (isa<Loc>(V)) {
2716 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002717 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002718 continue;
2719
2720 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002721
2722 // FIXME: Either this logic should also be replicated in GRSimpleVals
2723 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002724
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002725 // FIXME: We can have collisions on the conjured symbol if the
2726 // expression *I also creates conjured symbols. We probably want
2727 // to identify conjured symbols by an expression pair: the enclosing
2728 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002729 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002730
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002731 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002732
Ted Kremenek73ec7732009-05-06 18:19:24 +00002733 if (R) {
2734 // Are we dealing with an ElementRegion? If the element type is
2735 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xuea6851b2009-05-11 14:28:14 +00002736 // is a variable region then strip off the ElementRegion.
Ted Kremenek73ec7732009-05-06 18:19:24 +00002737 // FIXME: We really need to think about this for the general case
2738 // as sometimes we are reasoning about arrays and other times
2739 // about (char*), etc., is just a form of passing raw bytes.
2740 // e.g., void *p = alloca(); foo((char*)p);
2741 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2742 // Checking for 'integral type' is probably too promiscuous, but
2743 // we'll leave it in for now until we have a systematic way of
2744 // handling all of these cases. Eventually we need to come up
2745 // with an interface to StoreManager so that this logic can be
2746 // approriately delegated to the respective StoreManagers while
2747 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002748 // invalidating reference counts), probably via callbacks.
Ted Kremenek1cba5772009-05-11 22:55:17 +00002749 if (ER->getElementType()->isIntegralType()) {
2750 const MemRegion *superReg = ER->getSuperRegion();
2751 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2752 isa<ObjCIvarRegion>(superReg))
2753 R = cast<TypedRegion>(superReg);
2754 }
2755
Ted Kremenek73ec7732009-05-06 18:19:24 +00002756 // FIXME: What about layers of ElementRegions?
2757 }
2758
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002759 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002760 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002761
Ted Kremenek53b24182009-03-04 22:56:43 +00002762 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002763 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002764
Ted Kremenek53b24182009-03-04 22:56:43 +00002765 if (R->isBoundable(Ctx)) {
2766 // Set the value of the variable to be a conjured symbol.
2767 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002768 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002769
Zhongxing Xu079dc352009-04-09 06:03:54 +00002770 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002771 ValueManager &ValMgr = Eng.getValueManager();
2772 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002773 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002774 }
2775 else if (const RecordType *RT = T->getAsStructureType()) {
2776 // Handle structs in a not so awesome way. Here we just
2777 // eagerly bind new symbols to the fields. In reality we
2778 // should have the store manager handle this. The idea is just
2779 // to prototype some basic functionality here. All of this logic
2780 // should one day soon just go away.
2781 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2782
2783 // No record definition. There is nothing we can do.
2784 if (!RD)
2785 continue;
2786
2787 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2788
2789 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002790 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2791 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002792
2793 // For now just handle scalar fields.
2794 FieldDecl *FD = *FI;
2795 QualType FT = FD->getType();
2796
2797 if (Loc::IsLocType(FT) ||
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002798 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002799 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002800
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002801 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002802 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002803 }
2804 }
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002805 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2806 // Set the default value of the array to conjured symbol.
2807 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2808 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2809 Count);
2810 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2811 StateMgr);
2812 } else {
Ted Kremenek53b24182009-03-04 22:56:43 +00002813 // Just blast away other values.
2814 state = state.BindLoc(*MR, UnknownVal());
2815 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002816 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002817 }
2818 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002819 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002820 }
2821 else {
2822 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002823 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002824 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002825 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002826 else if (isa<nonloc::LocAsInteger>(V))
2827 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002828 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002829
Ted Kremenek272aa852008-06-25 21:21:56 +00002830 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002831 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002832 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002833 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002834 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002835 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002836 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002837 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002838 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002839 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002840 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002841 }
2842 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002843
Ted Kremenek272aa852008-06-25 21:21:56 +00002844 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002845 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002846 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002847 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002848 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002849 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002850
Ted Kremenekf2717b02008-07-18 17:24:20 +00002851 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002852 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002853
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002854 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2855 assert(Receiver);
2856 SVal V = state.GetSValAsScalarOrLoc(Receiver);
2857 bool found = false;
2858 if (SymbolRef Sym = V.getAsLocSymbol())
2859 if (state.get<RefBindings>(Sym)) {
2860 found = true;
2861 RE = Summaries.getObjAllocRetEffect();
2862 }
2863
2864 if (!found)
2865 RE = RetEffect::MakeNoRet();
2866 }
2867
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002868 switch (RE.getKind()) {
2869 default:
2870 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002871
Ted Kremenek8f90e712008-10-17 22:23:12 +00002872 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002873
Ted Kremenek455dd862008-04-11 20:23:24 +00002874 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002875 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2876 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002877
Ted Kremenek8f90e712008-10-17 22:23:12 +00002878 // FIXME: We eventually should handle structs and other compound types
2879 // that are returned by value.
2880
2881 QualType T = Ex->getType();
2882
Ted Kremenek79413a52008-11-13 06:10:40 +00002883 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002884 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002885 ValueManager &ValMgr = Eng.getValueManager();
2886 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002887 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002888 }
2889
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002890 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002891 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002892
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002893 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002894 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002895 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002896 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002897 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002898 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002899 break;
2900 }
2901
Ted Kremenek227c5372008-05-06 02:41:27 +00002902 case RetEffect::ReceiverAlias: {
2903 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002904 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002905 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002906 break;
2907 }
2908
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002909 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002910 case RetEffect::OwnedSymbol: {
2911 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002912 ValueManager &ValMgr = Eng.getValueManager();
2913 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2914 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2915 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2916 RetT));
2917 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002918
2919 // FIXME: Add a flag to the checker where allocations are assumed to
2920 // *not fail.
2921#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002922 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2923 bool isFeasible;
2924 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2925 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2926 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002927#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002928
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002929 break;
2930 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002931
2932 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002933 case RetEffect::NotOwnedSymbol: {
2934 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002935 ValueManager &ValMgr = Eng.getValueManager();
2936 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2937 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2938 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2939 RetT));
2940 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002941 break;
2942 }
2943 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002944
Ted Kremenek0dd65012009-02-18 02:00:25 +00002945 // Generate a sink node if we are at the end of a path.
2946 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002947 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2948 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002949
2950 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002951 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002952}
2953
2954
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002955void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002956 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002957 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002958 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002959 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002960 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002961 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002962 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002963
Ted Kremenek286e9852009-05-04 04:57:00 +00002964 assert(Summ);
2965 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002966 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002967}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002968
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002969void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002970 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002971 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002972 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002973 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002974 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002975
Ted Kremenek272aa852008-06-25 21:21:56 +00002976 if (Expr* Receiver = ME->getReceiver()) {
2977 // We need the type-information of the tracked receiver object
2978 // Retrieve it from the state.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002979 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek272aa852008-06-25 21:21:56 +00002980
2981 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2982 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002983 // FIXME: Is this really working as expected? There are cases where
2984 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002985 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002986 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002987
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002988 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002989 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002990 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002991 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002992
2993 if (const PointerType* PT = Ty->getAsPointerType()) {
2994 QualType PointeeTy = PT->getPointeeType();
2995
2996 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2997 ID = IT->getDecl();
2998 }
2999 }
3000 }
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00003001
3002 // FIXME: this is a hack. This may or may not be the actual method
3003 // that is called.
3004 if (!ID) {
3005 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
3006 if (const ObjCInterfaceType *p =
3007 PT->getPointeeType()->getAsObjCInterfaceType())
3008 ID = p->getDecl();
3009 }
3010
Ted Kremenek04e00302009-04-29 17:09:14 +00003011 // FIXME: The receiver could be a reference to a class, meaning that
3012 // we should use the class method.
3013 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00003014
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003015 // Special-case: are we sending a mesage to "self"?
3016 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00003017 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
3018 if (Expr* Receiver = ME->getReceiver()) {
3019 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
3020 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
3021 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
3022 // Update the summary to make the default argument effect
3023 // 'StopTracking'.
3024 Summ = Summaries.copySummary(Summ);
3025 Summ->setDefaultArgEffect(StopTracking);
3026 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003027 }
3028 }
Ted Kremenek272aa852008-06-25 21:21:56 +00003029 }
Ted Kremenek1feab292008-04-16 04:28:53 +00003030 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00003031 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00003032
Ted Kremenek286e9852009-05-04 04:57:00 +00003033 if (!Summ)
3034 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00003035
Ted Kremenek286e9852009-05-04 04:57:00 +00003036 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00003037 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00003038}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003039
3040namespace {
3041class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
3042 GRStateRef state;
3043public:
3044 StopTrackingCallback(GRStateRef st) : state(st) {}
3045 GRStateRef getState() { return state; }
3046
3047 bool VisitSymbol(SymbolRef sym) {
3048 state = state.remove<RefBindings>(sym);
3049 return true;
3050 }
Ted Kremenek926abf22008-05-06 04:20:12 +00003051
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003052 const GRState* getState() const { return state.getState(); }
3053};
3054} // end anonymous namespace
3055
3056
Ted Kremeneka42be302009-02-14 01:43:44 +00003057void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00003058 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00003059 bool escapes = false;
3060
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003061 // A value escapes in three possible cases (this may change):
3062 //
3063 // (1) we are binding to something that is not a memory region.
3064 // (2) we are binding to a memregion that does not have stack storage
3065 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003066 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00003067 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003068
Ted Kremeneka42be302009-02-14 01:43:44 +00003069 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003070 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003071 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003072 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3073 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003074
3075 if (!escapes) {
3076 // To test (3), generate a new state with the binding removed. If it is
3077 // the same state, then it escapes (since the store cannot represent
3078 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00003079 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003080 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003081 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003082
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003083 // If our store can represent the binding and we aren't storing to something
3084 // that doesn't have local storage then just return and have the simulation
3085 // state continue as is.
3086 if (!escapes)
3087 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003088
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003089 // Otherwise, find all symbols referenced by 'val' that we are tracking
3090 // and stop tracking them.
3091 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003092}
3093
Ted Kremenek541db372008-04-24 23:57:27 +00003094
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003095 // Return statements.
3096
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003097void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003098 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003099 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003100 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003101 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003102
3103 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003104 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003105 return;
3106
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003107 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00003108 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003109
Ted Kremenek74556a12009-03-26 03:35:11 +00003110 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003111 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003112
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003113 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003114 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003115
3116 if (!T)
3117 return;
3118
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003119 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003120 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003121
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003122 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003123 case RefVal::Owned: {
3124 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003125 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003126 X.setCount(cnt - 1);
3127 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003128 break;
3129 }
3130
3131 case RefVal::NotOwned: {
3132 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003133 if (cnt) {
3134 X.setCount(cnt - 1);
3135 X = X ^ RefVal::ReturnedOwned;
3136 }
3137 else {
3138 X = X ^ RefVal::ReturnedNotOwned;
3139 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003140 break;
3141 }
3142
3143 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003144 return;
3145 }
3146
3147 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003148 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003149 Pred = Builder.MakeNode(Dst, S, Pred, state);
3150
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003151 // Did we cache out?
3152 if (!Pred)
3153 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003154
3155 // Update the autorelease counts.
3156 static unsigned autoreleasetag = 0;
3157 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3158 bool stop = false;
3159 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3160 X, stop);
3161
3162 // Did we cache out?
3163 if (!Pred || stop)
3164 return;
3165
3166 // Get the updated binding.
3167 T = state.get<RefBindings>(Sym);
3168 assert(T);
3169 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003170
Ted Kremenek47a72422009-04-29 18:50:19 +00003171 // Any leaks or other errors?
3172 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003173 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003174 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003175 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003176 RetEffect RE = Summ.getRetEffect();
3177 bool hasError = false;
3178
Ted Kremenek5b44a402009-05-16 01:38:01 +00003179 if (RE.getKind() != RetEffect::NoRet) {
3180 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3181 // Things are more complicated with garbage collection. If the
3182 // returned object is suppose to be an Objective-C object, we have
3183 // a leak (as the caller expects a GC'ed object) because no
3184 // method should return ownership unless it returns a CF object.
3185 X = X ^ RefVal::ErrorGCLeakReturned;
3186
3187 // Keep this false until this is properly tested.
3188 hasError = true;
3189 }
3190 else if (!RE.isOwned()) {
3191 // Either we are using GC and the returned object is a CF type
3192 // or we aren't using GC. In either case, we expect that the
3193 // enclosing method is expected to return ownership.
3194 hasError = true;
3195 X = X ^ RefVal::ErrorLeakReturned;
3196 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003197 }
3198
3199 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003200 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003201 static int ReturnOwnLeakTag = 0;
3202 state = state.set<RefBindings>(Sym, X);
3203 ExplodedNode<GRState> *N =
3204 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3205 if (N) {
3206 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003207 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3208 N, Sym, Eng);
3209 BR->EmitReport(report);
3210 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003211 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003212 }
3213 }
3214 else if (X.isReturnedNotOwned()) {
3215 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3216 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3217 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3218 if (Summ.getRetEffect().isOwned()) {
3219 // Trying to return a not owned object to a caller expecting an
3220 // owned object.
3221
3222 static int ReturnNotOwnedForOwnedTag = 0;
3223 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3224 if (ExplodedNode<GRState> *N =
3225 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3226 state, Pred)) {
3227 CFRefReport *report =
3228 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3229 *this, N, Sym);
3230 BR->EmitReport(report);
3231 }
3232 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003233 }
3234 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003235}
3236
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003237// Assumptions.
3238
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003239const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3240 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003241 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003242 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003243
3244 // FIXME: We may add to the interface of EvalAssume the list of symbols
3245 // whose assumptions have changed. For now we just iterate through the
3246 // bindings and check if any of the tracked symbols are NULL. This isn't
3247 // too bad since the number of symbols we will track in practice are
3248 // probably small and EvalAssume is only called at branches and a few
3249 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003250 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003251
3252 if (B.isEmpty())
3253 return St;
3254
3255 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003256
3257 GRStateRef state(St, VMgr);
3258 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003259
3260 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003261 // Check if the symbol is null (or equal to any constant).
3262 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003263 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003264 changed = true;
3265 B = RefBFactory.Remove(B, I.getKey());
3266 }
3267 }
3268
Ted Kremenek91781202008-08-17 03:20:02 +00003269 if (changed)
3270 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003271
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003272 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003273}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003274
Ted Kremenekb6578942009-02-24 19:15:11 +00003275GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3276 RefVal V, ArgEffect E,
3277 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003278
3279 // In GC mode [... release] and [... retain] do nothing.
3280 switch (E) {
3281 default: break;
3282 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3283 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003284 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003285 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3286 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003287 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003288
Ted Kremenek6537a642009-03-17 19:42:23 +00003289 // Handle all use-after-releases.
3290 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3291 V = V ^ RefVal::ErrorUseAfterRelease;
3292 hasErr = V.getKind();
3293 return state.set<RefBindings>(sym, V);
3294 }
3295
Ted Kremenek0d721572008-03-11 17:48:22 +00003296 switch (E) {
3297 default:
3298 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003299
3300 case Dealloc:
3301 // Any use of -dealloc in GC is *bad*.
3302 if (isGCEnabled()) {
3303 V = V ^ RefVal::ErrorDeallocGC;
3304 hasErr = V.getKind();
3305 break;
3306 }
3307
3308 switch (V.getKind()) {
3309 default:
3310 assert(false && "Invalid case.");
3311 case RefVal::Owned:
3312 // The object immediately transitions to the released state.
3313 V = V ^ RefVal::Released;
3314 V.clearCounts();
3315 return state.set<RefBindings>(sym, V);
3316 case RefVal::NotOwned:
3317 V = V ^ RefVal::ErrorDeallocNotOwned;
3318 hasErr = V.getKind();
3319 break;
3320 }
3321 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003322
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003323 case NewAutoreleasePool:
3324 assert(!isGCEnabled());
3325 return state.add<AutoreleaseStack>(sym);
3326
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003327 case MayEscape:
3328 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003329 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003330 break;
3331 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003332
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003333 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003334
Ted Kremenekede40b72008-07-09 18:11:16 +00003335 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003336 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003337 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003338
Ted Kremenek9b112d22009-01-28 21:44:40 +00003339 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003340 if (isGCEnabled())
3341 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003342
3343 // Update the autorelease counts.
3344 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003345 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003346 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003347
Ted Kremenek227c5372008-05-06 02:41:27 +00003348 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003349 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003350
Ted Kremenek0d721572008-03-11 17:48:22 +00003351 case IncRef:
3352 switch (V.getKind()) {
3353 default:
3354 assert(false);
3355
3356 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003357 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003358 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003359 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003360 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003361 // Non-GC cases are handled above.
3362 assert(isGCEnabled());
3363 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003364 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003365 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003366 break;
3367
Ted Kremenek272aa852008-06-25 21:21:56 +00003368 case SelfOwn:
3369 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003370 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003371 case DecRef:
3372 switch (V.getKind()) {
3373 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003374 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003375 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003376
Ted Kremenek272aa852008-06-25 21:21:56 +00003377 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003378 assert(V.getCount() > 0);
3379 if (V.getCount() == 1) V = V ^ RefVal::Released;
3380 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003381 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003382
Ted Kremenek272aa852008-06-25 21:21:56 +00003383 case RefVal::NotOwned:
3384 if (V.getCount() > 0)
3385 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003386 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003387 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003388 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003389 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003390 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003391
Ted Kremenek0d721572008-03-11 17:48:22 +00003392 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003393 // Non-GC cases are handled above.
3394 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003395 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003396 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003397 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003398 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003399 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003400 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003401 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003402}
3403
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003404//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003405// Handle dead symbols and end-of-path.
3406//===----------------------------------------------------------------------===//
3407
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003408std::pair<ExplodedNode<GRState>*, GRStateRef>
3409CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3410 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003411 GRExprEngine &Eng,
3412 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003413
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003414 unsigned ACnt = V.getAutoreleaseCount();
3415 stop = false;
3416
3417 // No autorelease counts? Nothing to be done.
3418 if (!ACnt)
3419 return std::make_pair(Pred, state);
3420
3421 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3422 unsigned Cnt = V.getCount();
3423
Ted Kremenek0603cf52009-05-11 15:26:06 +00003424 // FIXME: Handle sending 'autorelease' to already released object.
3425
3426 if (V.getKind() == RefVal::ReturnedOwned)
3427 ++Cnt;
3428
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003429 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003430 if (ACnt == Cnt) {
3431 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003432 if (V.getKind() == RefVal::ReturnedOwned)
3433 V = V ^ RefVal::ReturnedNotOwned;
3434 else
3435 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003436 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003437 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003438 V.setCount(Cnt - ACnt);
3439 V.setAutoreleaseCount(0);
3440 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003441 state = state.set<RefBindings>(Sym, V);
3442 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3443 stop = (N == 0);
3444 return std::make_pair(N, state);
3445 }
3446
3447 // Woah! More autorelease counts then retain counts left.
3448 // Emit hard error.
3449 stop = true;
3450 V = V ^ RefVal::ErrorOverAutorelease;
3451 state = state.set<RefBindings>(Sym, V);
3452
3453 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003454 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003455
3456 std::string sbuf;
3457 llvm::raw_string_ostream os(sbuf);
Ted Kremenek2e6ce412009-05-15 06:02:08 +00003458 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekbd271be2009-05-10 05:11:21 +00003459 if (V.getAutoreleaseCount() > 1)
3460 os << V.getAutoreleaseCount() << " times";
3461 os << " but the object has ";
3462 if (V.getCount() == 0)
3463 os << "zero (locally visible)";
3464 else
3465 os << "+" << V.getCount();
3466 os << " retain counts";
3467
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003468 CFRefReport *report =
3469 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003470 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003471 BR->EmitReport(report);
3472 }
3473
3474 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003475}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003476
3477GRStateRef
3478CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3479 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3480
3481 bool hasLeak = V.isOwned() ||
3482 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3483
3484 if (!hasLeak)
3485 return state.remove<RefBindings>(sid);
3486
3487 Leaked.push_back(sid);
3488 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3489}
3490
3491ExplodedNode<GRState>*
3492CFRefCount::ProcessLeaks(GRStateRef state,
3493 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3494 GenericNodeBuilder &Builder,
3495 GRExprEngine& Eng,
3496 ExplodedNode<GRState> *Pred) {
3497
3498 if (Leaked.empty())
3499 return Pred;
3500
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003501 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003502 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003503
3504 if (N) {
3505 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3506 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3507
3508 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3509 : leakAtReturn);
3510 assert(BT && "BugType not initialized.");
3511 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3512 BR->EmitReport(report);
3513 }
3514 }
3515
3516 return N;
3517}
3518
Ted Kremenek708af042009-02-05 06:50:21 +00003519void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3520 GREndPathNodeBuilder<GRState>& Builder) {
3521
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003522 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003523 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003524 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003525 ExplodedNode<GRState> *Pred = 0;
3526
3527 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003528 bool stop = false;
3529 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3530 (*I).first,
3531 (*I).second, stop);
3532
3533 if (stop)
3534 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003535 }
3536
3537 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003538 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003539
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003540 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3541 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3542
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003543 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003544}
3545
3546void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3547 GRExprEngine& Eng,
3548 GRStmtNodeBuilder<GRState>& Builder,
3549 ExplodedNode<GRState>* Pred,
3550 Stmt* S,
3551 const GRState* St,
3552 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003553
3554 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003555 RefBindings B = state.get<RefBindings>();
3556
3557 // Update counts from autorelease pools
3558 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3559 E = SymReaper.dead_end(); I != E; ++I) {
3560 SymbolRef Sym = *I;
3561 if (const RefVal* T = B.lookup(Sym)){
3562 // Use the symbol as the tag.
3563 // FIXME: This might not be as unique as we would like.
3564 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003565 bool stop = false;
3566 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3567 Sym, *T, stop);
3568 if (stop)
3569 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003570 }
3571 }
3572
3573 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003574 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003575
3576 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003577 E = SymReaper.dead_end(); I != E; ++I) {
3578 if (const RefVal* T = B.lookup(*I))
3579 state = HandleSymbolDeath(state, *I, *T, Leaked);
3580 }
Ted Kremenek708af042009-02-05 06:50:21 +00003581
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003582 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003583 {
3584 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3585 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3586 }
Ted Kremenek708af042009-02-05 06:50:21 +00003587
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003588 // Did we cache out?
3589 if (!Pred)
3590 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003591
3592 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003593 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003594
Ted Kremenek876d8df2009-02-19 23:47:02 +00003595 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003596 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3597
Ted Kremenek876d8df2009-02-19 23:47:02 +00003598 state = state.set<RefBindings>(B);
3599 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003600}
3601
3602void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3603 GRStmtNodeBuilder<GRState>& Builder,
3604 Expr* NodeExpr, Expr* ErrorExpr,
3605 ExplodedNode<GRState>* Pred,
3606 const GRState* St,
3607 RefVal::Kind hasErr, SymbolRef Sym) {
3608 Builder.BuildSinks = true;
3609 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3610
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003611 if (!N)
3612 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003613
3614 CFRefBug *BT = 0;
3615
Ted Kremenek6537a642009-03-17 19:42:23 +00003616 switch (hasErr) {
3617 default:
3618 assert(false && "Unhandled error.");
3619 return;
3620 case RefVal::ErrorUseAfterRelease:
3621 BT = static_cast<CFRefBug*>(useAfterRelease);
3622 break;
3623 case RefVal::ErrorReleaseNotOwned:
3624 BT = static_cast<CFRefBug*>(releaseNotOwned);
3625 break;
3626 case RefVal::ErrorDeallocGC:
3627 BT = static_cast<CFRefBug*>(deallocGC);
3628 break;
3629 case RefVal::ErrorDeallocNotOwned:
3630 BT = static_cast<CFRefBug*>(deallocNotOwned);
3631 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003632 }
3633
Ted Kremenekc26c4692009-02-18 03:48:14 +00003634 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003635 report->addRange(ErrorExpr->getSourceRange());
3636 BR->EmitReport(report);
3637}
3638
3639//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003640// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003641//===----------------------------------------------------------------------===//
3642
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003643GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3644 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003645 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003646}