blob: d3f6ffbb60db6f2d703bccd91ebb3f3f443e3173 [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenekc3bc6c82009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
Ted Kremenek613ef972009-05-15 15:49:00 +000079static NamingConvention deriveNamingConvention(Selector S) {
80 IdentifierInfo *II = S.getIdentifierInfoForSlot(0);
81
82 if (!II)
83 return NoConvention;
84
85 const char *s = II->getName();
86
Ted Kremenek4395b452009-02-21 05:13:43 +000087 // A method/function name may contain a prefix. We don't know it is there,
88 // however, until we encounter the first '_'.
89 bool InPossiblePrefix = true;
90 bool AtBeginning = true;
91 NamingConvention C = NoConvention;
92
93 while (*s != '\0') {
94 // Skip '_'.
95 if (*s == '_') {
96 if (InPossiblePrefix) {
97 InPossiblePrefix = false;
98 AtBeginning = true;
99 // Discard whatever 'convention' we
100 // had already derived since it occurs
101 // in the prefix.
102 C = NoConvention;
103 }
104 ++s;
105 continue;
106 }
107
108 // Skip numbers, ':', etc.
109 if (!isalpha(*s)) {
110 ++s;
111 continue;
112 }
113
114 const char *wordEnd = parseWord(s);
115 assert(wordEnd > s);
116 unsigned len = wordEnd - s;
117
118 switch (len) {
119 default:
120 break;
121 case 3:
122 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000123 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000124 C = CreateRule;
125 break;
126 case 4:
127 // Methods starting with 'alloc' or contain 'copy' follow the
128 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000129 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000130 C = CreateRule;
131 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000132 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000133 C = InitRule;
134 break;
135 case 5:
136 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
137 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000138 break;
139 }
140
141 // If we aren't in the prefix and have a derived convention then just
142 // return it now.
143 if (!InPossiblePrefix && C != NoConvention)
144 return C;
145
146 AtBeginning = false;
147 s = wordEnd;
148 }
149
150 // We will get here if there wasn't more than one word
151 // after the prefix.
152 return C;
153}
154
Ted Kremenek613ef972009-05-15 15:49:00 +0000155static bool followsFundamentalRule(Selector S) {
156 return deriveNamingConvention(S) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000157}
158
Ted Kremenek314b1952009-04-29 23:03:22 +0000159static const ObjCMethodDecl*
160ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
161 ObjCInterfaceDecl *ID =
162 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
163
164 return MD->isInstanceMethod()
165 ? ID->lookupInstanceMethod(Context, MD->getSelector())
166 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000167}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000168
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000169namespace {
170class VISIBILITY_HIDDEN GenericNodeBuilder {
171 GRStmtNodeBuilder<GRState> *SNB;
172 Stmt *S;
173 const void *tag;
174 GREndPathNodeBuilder<GRState> *ENB;
175public:
176 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
177 const void *t)
178 : SNB(&snb), S(s), tag(t), ENB(0) {}
179 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
180 : SNB(0), S(0), tag(0), ENB(&enb) {}
181
182 ExplodedNode<GRState> *MakeNode(const GRState *state,
183 ExplodedNode<GRState> *Pred) {
184 if (SNB)
Ted Kremenek3e3328d2009-05-09 01:50:57 +0000185 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000186
187 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000188 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000189 }
190};
191} // end anonymous namespace
192
Ted Kremenek7d421f32008-04-09 23:49:11 +0000193//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000194// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000195//===----------------------------------------------------------------------===//
196
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000197static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000198 IdentifierInfo* II = &Ctx.Idents.get(name);
199 return Ctx.Selectors.getSelector(0, &II);
200}
201
Ted Kremenek0e344d42008-05-06 00:30:21 +0000202static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
203 IdentifierInfo* II = &Ctx.Idents.get(name);
204 return Ctx.Selectors.getSelector(1, &II);
205}
206
Ted Kremenek272aa852008-06-25 21:21:56 +0000207//===----------------------------------------------------------------------===//
208// Type querying functions.
209//===----------------------------------------------------------------------===//
210
Ted Kremenek17144e82009-01-12 21:45:02 +0000211static bool hasPrefix(const char* s, const char* prefix) {
212 if (!prefix)
213 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000214
Ted Kremenek17144e82009-01-12 21:45:02 +0000215 char c = *s;
216 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000217
Ted Kremenek17144e82009-01-12 21:45:02 +0000218 while (c != '\0' && cP != '\0') {
219 if (c != cP) break;
220 c = *(++s);
221 cP = *(++prefix);
222 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000223
Ted Kremenek17144e82009-01-12 21:45:02 +0000224 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000225}
226
Ted Kremenek17144e82009-01-12 21:45:02 +0000227static bool hasSuffix(const char* s, const char* suffix) {
228 const char* loc = strstr(s, suffix);
229 return loc && strcmp(suffix, loc) == 0;
230}
231
232static bool isRefType(QualType RetTy, const char* prefix,
233 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000234
Ted Kremenek2f289b62009-05-12 04:53:03 +0000235 // Recursively walk the typedef stack, allowing typedefs of reference types.
236 while (1) {
237 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
238 const char* TDName = TD->getDecl()->getIdentifier()->getName();
239 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
240 return true;
241
242 RetTy = TD->getDecl()->getUnderlyingType();
243 continue;
244 }
245 break;
Ted Kremenek17144e82009-01-12 21:45:02 +0000246 }
247
248 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000249 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000250
251 // Is the type void*?
252 const PointerType* PT = RetTy->getAsPointerType();
253 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000254 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000255
256 // Does the name start with the prefix?
257 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000258}
259
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000260//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000261// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000262//===----------------------------------------------------------------------===//
263
Ted Kremenek272aa852008-06-25 21:21:56 +0000264/// ArgEffect is used to summarize a function/method call's effect on a
265/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000266enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
267 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
268 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000269
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000271template <> struct FoldingSetTrait<ArgEffect> {
272static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
273 ID.AddInteger((unsigned) X);
274}
Ted Kremenek272aa852008-06-25 21:21:56 +0000275};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000276} // end llvm namespace
277
Ted Kremeneka56ae162009-05-03 05:20:50 +0000278/// ArgEffects summarizes the effects of a function/method call on all of
279/// its arguments.
280typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
281
Ted Kremeneka7338b42008-03-11 06:39:11 +0000282namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000283
284/// RetEffect is used to summarize a function/method call's behavior with
285/// respect to its return value.
286class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000287public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000288 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000289 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
290 OwnedWhenTrackedReceiver };
Ted Kremenek68621b92009-01-28 05:56:51 +0000291
292 enum ObjKind { CF, ObjC, AnyObj };
293
Ted Kremeneka7338b42008-03-11 06:39:11 +0000294private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000295 Kind K;
296 ObjKind O;
297 unsigned index;
298
299 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
300 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000301
Ted Kremeneka7338b42008-03-11 06:39:11 +0000302public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000303 Kind getKind() const { return K; }
304
305 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000306
307 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000308 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000309 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000310 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000311
Ted Kremenek314b1952009-04-29 23:03:22 +0000312 bool isOwned() const {
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000313 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
314 K == OwnedWhenTrackedReceiver;
Ted Kremenek314b1952009-04-29 23:03:22 +0000315 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +0000316
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000317 static RetEffect MakeOwnedWhenTrackedReceiver() {
318 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
319 }
320
Ted Kremenek272aa852008-06-25 21:21:56 +0000321 static RetEffect MakeAlias(unsigned Idx) {
322 return RetEffect(Alias, Idx);
323 }
324 static RetEffect MakeReceiverAlias() {
325 return RetEffect(ReceiverAlias);
326 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000327 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
328 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000329 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000330 static RetEffect MakeNotOwned(ObjKind o) {
331 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000332 }
333 static RetEffect MakeGCNotOwned() {
334 return RetEffect(GCNotOwnedSymbol, ObjC);
335 }
336
Ted Kremenek272aa852008-06-25 21:21:56 +0000337 static RetEffect MakeNoRet() {
338 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000339 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000340
Ted Kremenek272aa852008-06-25 21:21:56 +0000341 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000342 ID.AddInteger((unsigned)K);
343 ID.AddInteger((unsigned)O);
344 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000345 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000346};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000347
Ted Kremenek272aa852008-06-25 21:21:56 +0000348
Ted Kremenek2f226732009-05-04 05:31:22 +0000349class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000350 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
351 /// specifies the argument (starting from 0). This can be sparsely
352 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000354
355 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
356 /// do not have an entry in Args.
357 ArgEffect DefaultArgEffect;
358
Ted Kremenek272aa852008-06-25 21:21:56 +0000359 /// Receiver - If this summary applies to an Objective-C message expression,
360 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000361 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000362
363 /// Ret - The effect on the return value. Used to indicate if the
364 /// function/method call returns a new tracked symbol, returns an
365 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000366 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000367
Ted Kremenekf2717b02008-07-18 17:24:20 +0000368 /// EndPath - Indicates that execution of this method/function should
369 /// terminate the simulation of a path.
370 bool EndPath;
371
Ted Kremeneka7338b42008-03-11 06:39:11 +0000372public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000373 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000374 ArgEffect ReceiverEff, bool endpath = false)
375 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
376 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000377
Ted Kremenek272aa852008-06-25 21:21:56 +0000378 /// getArg - Return the argument effect on the argument specified by
379 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000380 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000381 if (const ArgEffect *AE = Args.lookup(idx))
382 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000383
Ted Kremenekbcaff792008-05-06 15:44:25 +0000384 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000385 }
386
Ted Kremenek2f226732009-05-04 05:31:22 +0000387 /// setDefaultArgEffect - Set the default argument effect.
388 void setDefaultArgEffect(ArgEffect E) {
389 DefaultArgEffect = E;
390 }
391
392 /// setArg - Set the argument effect on the argument specified by idx.
393 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
394 Args = AF.Add(Args, idx, E);
395 }
396
Ted Kremenek272aa852008-06-25 21:21:56 +0000397 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000398 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000399
Ted Kremenek2f226732009-05-04 05:31:22 +0000400 /// setRetEffect - Set the effect of the return value of the call.
401 void setRetEffect(RetEffect E) { Ret = E; }
402
Ted Kremenekf2717b02008-07-18 17:24:20 +0000403 /// isEndPath - Returns true if executing the given method/function should
404 /// terminate the path.
405 bool isEndPath() const { return EndPath; }
406
Ted Kremenek272aa852008-06-25 21:21:56 +0000407 /// getReceiverEffect - Returns the effect on the receiver of the call.
408 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000409 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000410
Ted Kremenek2f226732009-05-04 05:31:22 +0000411 /// setReceiverEffect - Set the effect on the receiver of the call.
412 void setReceiverEffect(ArgEffect E) { Receiver = E; }
413
Ted Kremeneka56ae162009-05-03 05:20:50 +0000414 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000415
Ted Kremeneka56ae162009-05-03 05:20:50 +0000416 ExprIterator begin_args() const { return Args.begin(); }
417 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000418
Ted Kremeneka56ae162009-05-03 05:20:50 +0000419 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000420 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000421 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000422 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000423 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000424 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000425 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000426 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000427 }
428
429 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000430 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000431 }
432};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000433} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000434
Ted Kremenek272aa852008-06-25 21:21:56 +0000435//===----------------------------------------------------------------------===//
436// Data structures for constructing summaries.
437//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000438
Ted Kremenek272aa852008-06-25 21:21:56 +0000439namespace {
440class VISIBILITY_HIDDEN ObjCSummaryKey {
441 IdentifierInfo* II;
442 Selector S;
443public:
444 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
445 : II(ii), S(s) {}
446
Ted Kremenek314b1952009-04-29 23:03:22 +0000447 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000448 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +0000449
450 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
451 : II(d ? d->getIdentifier() : ii), S(s) {}
Ted Kremenek272aa852008-06-25 21:21:56 +0000452
453 ObjCSummaryKey(Selector s)
454 : II(0), S(s) {}
455
456 IdentifierInfo* getIdentifier() const { return II; }
457 Selector getSelector() const { return S; }
458};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000459}
460
461namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000462template <> struct DenseMapInfo<ObjCSummaryKey> {
463 static inline ObjCSummaryKey getEmptyKey() {
464 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
465 DenseMapInfo<Selector>::getEmptyKey());
466 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000467
Ted Kremenek272aa852008-06-25 21:21:56 +0000468 static inline ObjCSummaryKey getTombstoneKey() {
469 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
470 DenseMapInfo<Selector>::getTombstoneKey());
471 }
472
473 static unsigned getHashValue(const ObjCSummaryKey &V) {
474 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
475 & 0x88888888)
476 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
477 & 0x55555555);
478 }
479
480 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
481 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
482 RHS.getIdentifier()) &&
483 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
484 RHS.getSelector());
485 }
486
487 static bool isPod() {
488 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
489 DenseMapInfo<Selector>::isPod();
490 }
491};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000492} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000493
Ted Kremenek84f010c2008-06-23 23:30:29 +0000494namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000495class VISIBILITY_HIDDEN ObjCSummaryCache {
496 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
497 MapTy M;
498public:
499 ObjCSummaryCache() {}
500
501 typedef MapTy::iterator iterator;
502
Ted Kremenek314b1952009-04-29 23:03:22 +0000503 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
504 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000505 // Lookup the method using the decl for the class @interface. If we
506 // have no decl, lookup using the class name.
507 return D ? find(D, S) : find(ClsName, S);
508 }
509
Ted Kremenek314b1952009-04-29 23:03:22 +0000510 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000511 // Do a lookup with the (D,S) pair. If we find a match return
512 // the iterator.
513 ObjCSummaryKey K(D, S);
514 MapTy::iterator I = M.find(K);
515
516 if (I != M.end() || !D)
517 return I;
518
519 // Walk the super chain. If we find a hit with a parent, we'll end
520 // up returning that summary. We actually allow that key (null,S), as
521 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
522 // generate initial summaries without having to worry about NSObject
523 // being declared.
524 // FIXME: We may change this at some point.
525 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
526 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
527 break;
528
529 if (!C)
530 return I;
531 }
532
533 // Cache the summary with original key to make the next lookup faster
534 // and return the iterator.
535 M[K] = I->second;
536 return I;
537 }
538
Ted Kremenek9449ca92008-08-12 20:41:56 +0000539
Ted Kremenek272aa852008-06-25 21:21:56 +0000540 iterator find(Expr* Receiver, Selector S) {
541 return find(getReceiverDecl(Receiver), S);
542 }
543
544 iterator find(IdentifierInfo* II, Selector S) {
545 // FIXME: Class method lookup. Right now we dont' have a good way
546 // of going between IdentifierInfo* and the class hierarchy.
547 iterator I = M.find(ObjCSummaryKey(II, S));
548 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
549 }
550
551 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
552
553 const PointerType* PT = E->getType()->getAsPointerType();
554 if (!PT) return 0;
555
556 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
557 if (!OI) return 0;
558
559 return OI ? OI->getDecl() : 0;
560 }
561
562 iterator end() { return M.end(); }
563
564 RetainSummary*& operator[](ObjCMessageExpr* ME) {
565
566 Selector S = ME->getSelector();
567
568 if (Expr* Receiver = ME->getReceiver()) {
569 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
570 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
571 }
572
573 return M[ObjCSummaryKey(ME->getClassName(), S)];
574 }
575
576 RetainSummary*& operator[](ObjCSummaryKey K) {
577 return M[K];
578 }
579
580 RetainSummary*& operator[](Selector S) {
581 return M[ ObjCSummaryKey(S) ];
582 }
583};
584} // end anonymous namespace
585
586//===----------------------------------------------------------------------===//
587// Data structures for managing collections of summaries.
588//===----------------------------------------------------------------------===//
589
590namespace {
591class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000592
593 //==-----------------------------------------------------------------==//
594 // Typedefs.
595 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000596
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000597 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
598 FuncSummariesTy;
599
Ted Kremenek84f010c2008-06-23 23:30:29 +0000600 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000601
602 //==-----------------------------------------------------------------==//
603 // Data.
604 //==-----------------------------------------------------------------==//
605
Ted Kremenek272aa852008-06-25 21:21:56 +0000606 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000607 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000608
Ted Kremenekede40b72008-07-09 18:11:16 +0000609 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
610 /// "CFDictionaryCreate".
611 IdentifierInfo* CFDictionaryCreateII;
612
Ted Kremenek272aa852008-06-25 21:21:56 +0000613 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000614 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000615
Ted Kremenek272aa852008-06-25 21:21:56 +0000616 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000617 FuncSummariesTy FuncSummaries;
618
Ted Kremenek272aa852008-06-25 21:21:56 +0000619 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
620 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000621 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000622
Ted Kremenek272aa852008-06-25 21:21:56 +0000623 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000624 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000625
Ted Kremenek272aa852008-06-25 21:21:56 +0000626 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
627 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000628 llvm::BumpPtrAllocator BPAlloc;
629
Ted Kremeneka56ae162009-05-03 05:20:50 +0000630 /// AF - A factory for ArgEffects objects.
631 ArgEffects::Factory AF;
632
Ted Kremenek272aa852008-06-25 21:21:56 +0000633 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000634 ArgEffects ScratchArgs;
635
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000636 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
637 /// objects.
638 RetEffect ObjCAllocRetE;
639
Ted Kremenek286e9852009-05-04 04:57:00 +0000640 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000641 RetainSummary* StopSummary;
642
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000643 //==-----------------------------------------------------------------==//
644 // Methods.
645 //==-----------------------------------------------------------------==//
646
Ted Kremenek272aa852008-06-25 21:21:56 +0000647 /// getArgEffects - Returns a persistent ArgEffects object based on the
648 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000649 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000650
Ted Kremenek562c1302008-05-05 16:51:50 +0000651 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000652
653public:
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000654 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
655
Ted Kremenek2f226732009-05-04 05:31:22 +0000656 RetainSummary *getDefaultSummary() {
657 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
658 return new (Summ) RetainSummary(DefaultSummary);
659 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000660
Ted Kremenek064ef322009-02-23 16:51:39 +0000661 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000662
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000663 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
664 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000665 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000666
Ted Kremeneka56ae162009-05-03 05:20:50 +0000667 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000668 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000669 ArgEffect DefaultEff = MayEscape,
670 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000671
Ted Kremenek266d8b62008-05-06 02:26:56 +0000672 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000673 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000674 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000675 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000676 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000677
Ted Kremeneka821b792009-04-29 05:04:30 +0000678 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000679 if (StopSummary)
680 return StopSummary;
681
682 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
683 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000684
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000685 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000686 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000687
Ted Kremeneka821b792009-04-29 05:04:30 +0000688 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000689
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000690 void InitializeClassMethodSummaries();
691 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000692
Ted Kremenek9b42e062009-05-03 04:42:10 +0000693 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000694 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000695
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000696private:
697
Ted Kremenekf2717b02008-07-18 17:24:20 +0000698 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
699 RetainSummary* Summ) {
700 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
701 }
702
Ted Kremenek272aa852008-06-25 21:21:56 +0000703 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
704 ObjCClassMethodSummaries[S] = Summ;
705 }
706
707 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
708 ObjCMethodSummaries[S] = Summ;
709 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000710
711 void addClassMethSummary(const char* Cls, const char* nullaryName,
712 RetainSummary *Summ) {
713 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
714 Selector S = GetNullarySelector(nullaryName, Ctx);
715 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
716 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000717
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000718 void addInstMethSummary(const char* Cls, const char* nullaryName,
719 RetainSummary *Summ) {
720 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
721 Selector S = GetNullarySelector(nullaryName, Ctx);
722 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
723 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000724
725 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000726 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000727
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000728 while (const char* s = va_arg(argp, const char*))
729 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000730
731 return Ctx.Selectors.getSelector(II.size(), &II[0]);
732 }
733
734 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
735 RetainSummary* Summ, va_list argp) {
736 Selector S = generateSelector(argp);
737 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000738 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000739
740 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
741 va_list argp;
742 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000743 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000744 va_end(argp);
745 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000746
747 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
748 va_list argp;
749 va_start(argp, Summ);
750 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
751 va_end(argp);
752 }
753
754 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
755 va_list argp;
756 va_start(argp, Summ);
757 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
758 va_end(argp);
759 }
760
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000761 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000762 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
763 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000764 DoNothing, DoNothing, true);
765 va_list argp;
766 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000767 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000768 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000769 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000770
Ted Kremeneka7338b42008-03-11 06:39:11 +0000771public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000772
773 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000774 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000775 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000776 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000777 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
778 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000779 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
780 RetEffect::MakeNoRet() /* return effect */,
Ted Kremeneka13b0862009-05-11 18:30:24 +0000781 MayEscape, /* default argument effect */
782 DoNothing /* receiver effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000783 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000784
785 InitializeClassMethodSummaries();
786 InitializeMethodSummaries();
787 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000788
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000789 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000790
Ted Kremenekd13c1872008-06-24 03:56:45 +0000791 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000792
Ted Kremenek314b1952009-04-29 23:03:22 +0000793 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
794 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000795 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000796 ID, ME->getMethodDecl(), ME->getType());
797 }
798
Ted Kremenek04e00302009-04-29 17:09:14 +0000799 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000800 const ObjCInterfaceDecl* ID,
801 const ObjCMethodDecl *MD,
802 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000803
804 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000805 const ObjCInterfaceDecl *ID,
806 const ObjCMethodDecl *MD,
807 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000808
809 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
810 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
811 ME->getClassInfo().first,
812 ME->getMethodDecl(), ME->getType());
813 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000814
815 /// getMethodSummary - This version of getMethodSummary is used to query
816 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000817 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
818 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000819 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000820 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000821 IdentifierInfo *ClsName = ID->getIdentifier();
822 QualType ResultTy = MD->getResultType();
823
Ted Kremenek81eb4642009-04-30 05:47:23 +0000824 // Resolve the method decl last.
825 if (const ObjCMethodDecl *InterfaceMD =
826 ResolveToInterfaceMethodDecl(MD, Ctx))
827 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000828
Ted Kremenek91b89a42009-04-29 17:17:48 +0000829 if (MD->isInstanceMethod())
830 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
831 else
832 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
833 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000834
Ted Kremenek314b1952009-04-29 23:03:22 +0000835 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
836 Selector S, QualType RetTy);
837
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000838 void updateSummaryFromAnnotations(RetainSummary &Summ,
839 const ObjCMethodDecl *MD);
840
841 void updateSummaryFromAnnotations(RetainSummary &Summ,
842 const FunctionDecl *FD);
843
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000844 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000845
846 RetainSummary *copySummary(RetainSummary *OldSumm) {
847 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
848 new (Summ) RetainSummary(*OldSumm);
849 return Summ;
850 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000851};
852
853} // end anonymous namespace
854
855//===----------------------------------------------------------------------===//
856// Implementation of checker data structures.
857//===----------------------------------------------------------------------===//
858
Ted Kremeneka56ae162009-05-03 05:20:50 +0000859RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000860
Ted Kremeneka56ae162009-05-03 05:20:50 +0000861ArgEffects RetainSummaryManager::getArgEffects() {
862 ArgEffects AE = ScratchArgs;
863 ScratchArgs = AF.GetEmptyMap();
864 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000865}
866
Ted Kremenek266d8b62008-05-06 02:26:56 +0000867RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000868RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000869 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000870 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000871 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000872 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000873 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000874 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000875 return Summ;
876}
877
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000878//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000879// Predicates.
880//===----------------------------------------------------------------------===//
881
Ted Kremenek9b42e062009-05-03 04:42:10 +0000882bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000883 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000884 return false;
885
Ted Kremenek0d813552009-04-23 22:11:07 +0000886 // We assume that id<..>, id, and "Class" all represent tracked objects.
887 const PointerType *PT = Ty->getAsPointerType();
888 if (PT == 0)
889 return true;
890
891 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000892
893 // We assume that id<..>, id, and "Class" all represent tracked objects.
894 if (!OT)
895 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000896
Ted Kremenek5b44a402009-05-16 01:38:01 +0000897 // Does the interface subclass NSObject?
898 // FIXME: We can memoize here if this gets too expensive.
Ted Kremenek35920ed2009-01-07 00:39:56 +0000899 ObjCInterfaceDecl* ID = OT->getDecl();
900
Ted Kremenek5b44a402009-05-16 01:38:01 +0000901 // Assume that anything declared with a forward declaration and no
902 // @interface subclasses NSObject.
903 if (ID->isForwardDecl())
904 return true;
905
906 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
907
908
Ted Kremenek35920ed2009-01-07 00:39:56 +0000909 for ( ; ID ; ID = ID->getSuperClass())
910 if (ID->getIdentifier() == NSObjectII)
911 return true;
912
913 return false;
914}
915
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000916bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
917 return isRefType(T, "CF") || // Core Foundation.
918 isRefType(T, "CG") || // Core Graphics.
919 isRefType(T, "DADisk") || // Disk Arbitration API.
920 isRefType(T, "DADissenter") ||
921 isRefType(T, "DASessionRef");
922}
923
Ted Kremenek35920ed2009-01-07 00:39:56 +0000924//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000925// Summary creation for functions (largely uses of Core Foundation).
926//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000927
Ted Kremenek17144e82009-01-12 21:45:02 +0000928static bool isRetain(FunctionDecl* FD, const char* FName) {
929 const char* loc = strstr(FName, "Retain");
930 return loc && loc[sizeof("Retain")-1] == '\0';
931}
932
933static bool isRelease(FunctionDecl* FD, const char* FName) {
934 const char* loc = strstr(FName, "Release");
935 return loc && loc[sizeof("Release")-1] == '\0';
936}
937
Ted Kremenekd13c1872008-06-24 03:56:45 +0000938RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000939 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000940 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000941 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000942 return I->second;
943
Ted Kremenek64cddf12009-05-04 15:34:07 +0000944 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000945 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000946
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000947 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000948 // We generate "stop" summaries for implicitly defined functions.
949 if (FD->isImplicit()) {
950 S = getPersistentStopSummary();
951 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000952 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000953
Ted Kremenek064ef322009-02-23 16:51:39 +0000954 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000955 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000956 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000957 const char* FName = FD->getIdentifier()->getName();
958
Ted Kremenek38c6f022009-03-05 22:11:14 +0000959 // Strip away preceding '_'. Doing this here will effect all the checks
960 // down below.
961 while (*FName == '_') ++FName;
962
Ted Kremenek17144e82009-01-12 21:45:02 +0000963 // Inspect the result type.
964 QualType RetTy = FT->getResultType();
965
966 // FIXME: This should all be refactored into a chain of "summary lookup"
967 // filters.
968 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
969 // FIXES: <rdar://problem/6326900>
970 // This should be addressed using a API table. This strcmp is also
971 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000972 assert (ScratchArgs.isEmpty());
973 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000974 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
975 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000976 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000977
978 // Enable this code once the semantics of NSDeallocateObject are resolved
979 // for GC. <rdar://problem/6619988>
980#if 0
981 // Handle: NSDeallocateObject(id anObject);
982 // This method does allow 'nil' (although we don't check it now).
983 if (strcmp(FName, "NSDeallocateObject") == 0) {
984 return RetTy == Ctx.VoidTy
985 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
986 : getPersistentStopSummary();
987 }
988#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000989
990 // Handle: id NSMakeCollectable(CFTypeRef)
991 if (strcmp(FName, "NSMakeCollectable") == 0) {
992 S = (RetTy == Ctx.getObjCIdType())
993 ? getUnarySummary(FT, cfmakecollectable)
994 : getPersistentStopSummary();
995
996 break;
997 }
998
999 if (RetTy->isPointerType()) {
1000 // For CoreFoundation ('CF') types.
1001 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1002 if (isRetain(FD, FName))
1003 S = getUnarySummary(FT, cfretain);
1004 else if (strstr(FName, "MakeCollectable"))
1005 S = getUnarySummary(FT, cfmakecollectable);
1006 else
1007 S = getCFCreateGetRuleSummary(FD, FName);
1008
1009 break;
1010 }
1011
1012 // For CoreGraphics ('CG') types.
1013 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1014 if (isRetain(FD, FName))
1015 S = getUnarySummary(FT, cfretain);
1016 else
1017 S = getCFCreateGetRuleSummary(FD, FName);
1018
1019 break;
1020 }
1021
1022 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1023 if (isRefType(RetTy, "DADisk") ||
1024 isRefType(RetTy, "DADissenter") ||
1025 isRefType(RetTy, "DASessionRef")) {
1026 S = getCFCreateGetRuleSummary(FD, FName);
1027 break;
1028 }
1029
1030 break;
1031 }
1032
1033 // Check for release functions, the only kind of functions that we care
1034 // about that don't return a pointer type.
1035 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001036 // Test for 'CGCF'.
1037 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1038 FName += 4;
1039 else
1040 FName += 2;
1041
1042 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001043 S = getUnarySummary(FT, cfrelease);
1044 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001045 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001046 // Remaining CoreFoundation and CoreGraphics functions.
1047 // We use to assume that they all strictly followed the ownership idiom
1048 // and that ownership cannot be transferred. While this is technically
1049 // correct, many methods allow a tracked object to escape. For example:
1050 //
1051 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1052 // CFDictionaryAddValue(y, key, x);
1053 // CFRelease(x);
1054 // ... it is okay to use 'x' since 'y' has a reference to it
1055 //
1056 // We handle this and similar cases with the follow heuristic. If the
1057 // function name contains "InsertValue", "SetValue" or "AddValue" then
1058 // we assume that arguments may "escape."
1059 //
1060 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1061 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001062 CStrInCStrNoCase(FName, "SetValue") ||
1063 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001064 ? MayEscape : DoNothing;
1065
1066 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001067 }
1068 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001069 }
1070 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001071
1072 if (!S)
1073 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001074
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001075 // Annotations override defaults.
1076 assert(S);
1077 updateSummaryFromAnnotations(*S, FD);
1078
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001079 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001080 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001081}
1082
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001083RetainSummary*
1084RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1085 const char* FName) {
1086
Ted Kremenek562c1302008-05-05 16:51:50 +00001087 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1088 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001089
Ted Kremenek562c1302008-05-05 16:51:50 +00001090 if (strstr(FName, "Get"))
1091 return getCFSummaryGetRule(FD);
1092
Ted Kremenek286e9852009-05-04 04:57:00 +00001093 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001094}
1095
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001096RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001097RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1098 UnaryFuncKind func) {
1099
Ted Kremenek17144e82009-01-12 21:45:02 +00001100 // Sanity check that this is *really* a unary function. This can
1101 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001102 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001103 if (!FTP || FTP->getNumArgs() != 1)
1104 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001105
Ted Kremeneka56ae162009-05-03 05:20:50 +00001106 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001107
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001108 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001109 case cfretain: {
1110 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001111 return getPersistentSummary(RetEffect::MakeAlias(0),
1112 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001113 }
1114
1115 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001116 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001117 return getPersistentSummary(RetEffect::MakeNoRet(),
1118 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001119 }
1120
1121 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001122 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001123 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001124 }
1125
1126 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001127 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001128 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001129 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001130}
1131
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001132RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001133 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001134
1135 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001136 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1137 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001138 }
1139
Ted Kremenek68621b92009-01-28 05:56:51 +00001140 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001141}
1142
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001143RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001144 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001145 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1146 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001147}
1148
Ted Kremeneka7338b42008-03-11 06:39:11 +00001149//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001150// Summary creation for Selectors.
1151//===----------------------------------------------------------------------===//
1152
Ted Kremenekbcaff792008-05-06 15:44:25 +00001153RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001154RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001155 assert(ScratchArgs.isEmpty());
1156 // 'init' methods conceptually return a newly allocated object and claim
1157 // the receiver.
1158 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
1159 return getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1160 DecRefMsg);
1161
1162 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001163}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001164
1165void
1166RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1167 const FunctionDecl *FD) {
1168 if (!FD)
1169 return;
1170
1171 // Determine if there is a special return effect for this method.
1172 if (isTrackedObjCObjectType(FD->getResultType())) {
1173 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1174 Summ.setRetEffect(ObjCAllocRetE);
1175 }
1176 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1177 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1178 }
1179 }
1180}
1181
1182void
1183RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1184 const ObjCMethodDecl *MD) {
1185 if (!MD)
1186 return;
1187
1188 // Determine if there is a special return effect for this method.
1189 if (isTrackedObjCObjectType(MD->getResultType())) {
1190 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1191 Summ.setRetEffect(ObjCAllocRetE);
1192 }
1193 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1194 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1195 }
1196 }
1197}
1198
Ted Kremenekbcaff792008-05-06 15:44:25 +00001199RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001200RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1201 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001202
Ted Kremenek578498a2009-04-29 00:42:39 +00001203 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001204 // Scan the method decl for 'void*' arguments. These should be treated
1205 // as 'StopTracking' because they are often used with delegates.
1206 // Delegates are a frequent form of false positives with the retain
1207 // count checker.
1208 unsigned i = 0;
1209 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1210 E = MD->param_end(); I != E; ++I, ++i)
1211 if (ParmVarDecl *PD = *I) {
1212 QualType Ty = Ctx.getCanonicalType(PD->getType());
1213 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001214 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001215 }
1216 }
1217
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001218 // Any special effect for the receiver?
1219 ArgEffect ReceiverEff = DoNothing;
1220
1221 // If one of the arguments in the selector has the keyword 'delegate' we
1222 // should stop tracking the reference count for the receiver. This is
1223 // because the reference count is quite possibly handled by a delegate
1224 // method.
1225 if (S.isKeywordSelector()) {
1226 const std::string &str = S.getAsString();
1227 assert(!str.empty());
1228 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1229 }
1230
Ted Kremenek174a0772009-04-23 23:08:22 +00001231 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001232 if (isTrackedObjCObjectType(RetTy)) {
1233 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1234 // by instance methods.
Ted Kremenek613ef972009-05-15 15:49:00 +00001235 RetEffect E = followsFundamentalRule(S)
1236 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001237
1238 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001239 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001240
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001241 // Look for methods that return an owned core foundation object.
1242 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek613ef972009-05-15 15:49:00 +00001243 RetEffect E = followsFundamentalRule(S)
1244 ? RetEffect::MakeOwned(RetEffect::CF, true)
1245 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001246
1247 return getPersistentSummary(E, ReceiverEff, MayEscape);
1248 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001249
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001250 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001251 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001252
Ted Kremenek2f226732009-05-04 05:31:22 +00001253 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001254}
1255
1256RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001257RetainSummaryManager::getInstanceMethodSummary(Selector S,
1258 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001259 const ObjCInterfaceDecl* ID,
1260 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001261 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001262
Ted Kremeneka821b792009-04-29 05:04:30 +00001263 // Look up a summary in our summary cache.
1264 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001265
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001266 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001267 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001268
Ted Kremeneka56ae162009-05-03 05:20:50 +00001269 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001270 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001271
Ted Kremenek2f226732009-05-04 05:31:22 +00001272 // "initXXX": pass-through for receiver.
Ted Kremenek613ef972009-05-15 15:49:00 +00001273 if (deriveNamingConvention(S) == InitRule)
Ted Kremenek2f226732009-05-04 05:31:22 +00001274 Summ = getInitMethodSummary(RetTy);
1275 else
1276 Summ = getCommonMethodSummary(MD, S, RetTy);
1277
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001278 // Annotations override defaults.
1279 updateSummaryFromAnnotations(*Summ, MD);
1280
Ted Kremenek2f226732009-05-04 05:31:22 +00001281 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001282 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001283 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001284}
1285
Ted Kremeneka7722b72008-05-06 21:26:51 +00001286RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001287RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001288 const ObjCInterfaceDecl *ID,
1289 const ObjCMethodDecl *MD,
1290 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001291
Ted Kremenek578498a2009-04-29 00:42:39 +00001292 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001293 ObjCMethodSummariesTy::iterator I =
1294 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001295
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001296 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001297 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001298
1299 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001300
1301 // Annotations override defaults.
1302 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001303
Ted Kremenek2f226732009-05-04 05:31:22 +00001304 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001305 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001306 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001307}
1308
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001309void RetainSummaryManager::InitializeClassMethodSummaries() {
1310 assert(ScratchArgs.isEmpty());
1311 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001312
Ted Kremenek272aa852008-06-25 21:21:56 +00001313 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1314 // NSObject and its derivatives.
1315 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1316 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1317 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001318
1319 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001320 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001321 GetNullarySelector("currentHandler", Ctx),
1322 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001323
1324 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001325 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001326 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1327 GetUnarySelector("addObject", Ctx),
1328 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001329 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001330
1331 // Create the summaries for [NSObject performSelector...]. We treat
1332 // these as 'stop tracking' for the arguments because they are often
1333 // used for delegates that can release the object. When we have better
1334 // inter-procedural analysis we can potentially do something better. This
1335 // workaround is to remove false positives.
1336 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1337 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1338 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1339 "afterDelay", NULL);
1340 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1341 "afterDelay", "inModes", NULL);
1342 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1343 "withObject", "waitUntilDone", NULL);
1344 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1345 "withObject", "waitUntilDone", "modes", NULL);
1346 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1347 "withObject", "waitUntilDone", NULL);
1348 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1349 "withObject", "waitUntilDone", "modes", NULL);
1350 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1351 "withObject", NULL);
Ted Kremenekdf100482009-05-14 21:29:16 +00001352
1353 // Specially handle NSData.
1354 RetainSummary *dataWithBytesNoCopySumm =
1355 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1356 DoNothing);
1357 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1358 "dataWithBytesNoCopy", "length", NULL);
1359 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1360 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001361}
1362
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001363void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001364
Ted Kremeneka56ae162009-05-03 05:20:50 +00001365 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001366
Ted Kremeneka7722b72008-05-06 21:26:51 +00001367 // Create the "init" selector. It just acts as a pass-through for the
1368 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001369 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
1370 getPersistentSummary(RetEffect::MakeOwnedWhenTrackedReceiver(),
1371 DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001372
1373 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001374 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001375
1376 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001377 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1378
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001379 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001380 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001381
Ted Kremenek266d8b62008-05-06 02:26:56 +00001382 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001383 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001384 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001385 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001386
1387 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001388 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001389 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001390
1391 // Create the "drain" selector.
1392 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001393 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001394
1395 // Create the -dealloc summary.
1396 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1397 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001398
1399 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001400 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001401 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001402
Ted Kremenekaac82832009-02-23 17:45:03 +00001403 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001404 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001405 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001406 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001407
Ted Kremenek45642a42008-08-12 18:48:50 +00001408 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001409 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1410 // self-own themselves. However, they only do this once they are displayed.
1411 // Thus, we need to track an NSWindow's display status.
1412 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001413 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001414 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1415 StopTracking,
1416 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001417
1418 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1419
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001420#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001421 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001422 "styleMask", "backing", "defer", NULL);
1423
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001424 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001425 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001426#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001427
Ted Kremenek45642a42008-08-12 18:48:50 +00001428 // For NSPanel (which subclasses NSWindow), allocated objects are not
1429 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001430 // FIXME: For now we don't track NSPanels. object for the same reason
1431 // as for NSWindow objects.
1432 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1433
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001434#if 0
1435 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001436 "styleMask", "backing", "defer", NULL);
1437
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001438 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001439 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001440#endif
Ted Kremenek88294222009-05-18 23:14:34 +00001441
1442 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1443 // exit a method.
1444 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek272aa852008-06-25 21:21:56 +00001445
Ted Kremenekf2717b02008-07-18 17:24:20 +00001446 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001447 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1448 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001449
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001450 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1451 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001452}
1453
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001454//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001455// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001456//===----------------------------------------------------------------------===//
1457
Ted Kremeneka7338b42008-03-11 06:39:11 +00001458namespace {
1459
Ted Kremenek7d421f32008-04-09 23:49:11 +00001460class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001461public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001462 enum Kind {
1463 Owned = 0, // Owning reference.
1464 NotOwned, // Reference is not owned by still valid (not freed).
1465 Released, // Object has been released.
1466 ReturnedOwned, // Returned object passes ownership to caller.
1467 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001468 ERROR_START,
1469 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1470 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001471 ErrorUseAfterRelease, // Object used after released.
1472 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001473 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001474 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001475 ErrorLeakReturned, // A memory leak due to the returning method not having
1476 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001477 ErrorGCLeakReturned,
1478 ErrorOverAutorelease,
1479 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001480 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001481
1482private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001483 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001484 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001485 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001486 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001487 QualType T;
1488
Ted Kremenek4d99d342009-05-08 20:01:42 +00001489 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1490 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001491
Ted Kremenek68621b92009-01-28 05:56:51 +00001492 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001493 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001494
1495public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001496 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001497
1498 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001499
Ted Kremenek4d99d342009-05-08 20:01:42 +00001500 unsigned getCount() const { return Cnt; }
1501 unsigned getAutoreleaseCount() const { return ACnt; }
1502 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1503 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001504 void setCount(unsigned i) { Cnt = i; }
1505 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001506
Ted Kremenek272aa852008-06-25 21:21:56 +00001507 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001508
1509 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001510
Ted Kremenek6537a642009-03-17 19:42:23 +00001511 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001512
Ted Kremenek6537a642009-03-17 19:42:23 +00001513 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001514
Ted Kremenekffefc352008-04-11 22:25:11 +00001515 bool isOwned() const {
1516 return getKind() == Owned;
1517 }
1518
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001519 bool isNotOwned() const {
1520 return getKind() == NotOwned;
1521 }
1522
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001523 bool isReturnedOwned() const {
1524 return getKind() == ReturnedOwned;
1525 }
1526
1527 bool isReturnedNotOwned() const {
1528 return getKind() == ReturnedNotOwned;
1529 }
1530
1531 bool isNonLeakError() const {
1532 Kind k = getKind();
1533 return isError(k) && !isLeak(k);
1534 }
1535
Ted Kremenek68621b92009-01-28 05:56:51 +00001536 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1537 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001538 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001539 }
1540
Ted Kremenek68621b92009-01-28 05:56:51 +00001541 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1542 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001543 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001544 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001545
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001546 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001547
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001548 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001549 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001550 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001551
Ted Kremenek272aa852008-06-25 21:21:56 +00001552 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001553 return RefVal(getKind(), getObjKind(), getCount() - i,
1554 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001555 }
1556
1557 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001558 return RefVal(getKind(), getObjKind(), getCount() + i,
1559 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001560 }
1561
1562 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001563 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1564 getType());
1565 }
1566
1567 RefVal autorelease() const {
1568 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1569 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001570 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001571
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001572 void Profile(llvm::FoldingSetNodeID& ID) const {
1573 ID.AddInteger((unsigned) kind);
1574 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001575 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001576 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001577 }
1578
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001579 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001580};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001581
1582void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001583 if (!T.isNull())
1584 Out << "Tracked Type:" << T.getAsString() << '\n';
1585
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001586 switch (getKind()) {
1587 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001588 case Owned: {
1589 Out << "Owned";
1590 unsigned cnt = getCount();
1591 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001592 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001593 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001594
Ted Kremenekc4f81022008-04-10 23:09:18 +00001595 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001596 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001597 unsigned cnt = getCount();
1598 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001599 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001600 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001601
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001602 case ReturnedOwned: {
1603 Out << "ReturnedOwned";
1604 unsigned cnt = getCount();
1605 if (cnt) Out << " (+ " << cnt << ")";
1606 break;
1607 }
1608
1609 case ReturnedNotOwned: {
1610 Out << "ReturnedNotOwned";
1611 unsigned cnt = getCount();
1612 if (cnt) Out << " (+ " << cnt << ")";
1613 break;
1614 }
1615
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001616 case Released:
1617 Out << "Released";
1618 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001619
1620 case ErrorDeallocGC:
1621 Out << "-dealloc (GC)";
1622 break;
1623
1624 case ErrorDeallocNotOwned:
1625 Out << "-dealloc (not-owned)";
1626 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001627
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001628 case ErrorLeak:
1629 Out << "Leaked";
1630 break;
1631
Ted Kremenek311f3d42008-10-22 23:56:21 +00001632 case ErrorLeakReturned:
1633 Out << "Leaked (Bad naming)";
1634 break;
1635
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001636 case ErrorGCLeakReturned:
1637 Out << "Leaked (GC-ed at return)";
1638 break;
1639
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001640 case ErrorUseAfterRelease:
1641 Out << "Use-After-Release [ERROR]";
1642 break;
1643
1644 case ErrorReleaseNotOwned:
1645 Out << "Release of Not-Owned [ERROR]";
1646 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001647
1648 case RefVal::ErrorOverAutorelease:
1649 Out << "Over autoreleased";
1650 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001651
1652 case RefVal::ErrorReturnedNotOwned:
1653 Out << "Non-owned object returned instead of owned";
1654 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001655 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001656
1657 if (ACnt) {
1658 Out << " [ARC +" << ACnt << ']';
1659 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001660}
Ted Kremenek0d721572008-03-11 17:48:22 +00001661
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001662} // end anonymous namespace
1663
1664//===----------------------------------------------------------------------===//
1665// RefBindings - State used to track object reference counts.
1666//===----------------------------------------------------------------------===//
1667
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001668typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001669static int RefBIndex = 0;
1670
1671namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001672 template<>
1673 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1674 static inline void* GDMIndex() { return &RefBIndex; }
1675 };
1676}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001677
1678//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001679// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001680//===----------------------------------------------------------------------===//
1681
Ted Kremenekb6578942009-02-24 19:15:11 +00001682typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1683typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1684typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001685
Ted Kremenekb6578942009-02-24 19:15:11 +00001686static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001687static int AutoRBIndex = 0;
1688
Ted Kremenekb6578942009-02-24 19:15:11 +00001689namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001690namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001691
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001692namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001693template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001694 : public GRStatePartialTrait<ARStack> {
1695 static inline void* GDMIndex() { return &AutoRBIndex; }
1696};
1697
1698template<> struct GRStateTrait<AutoreleasePoolContents>
1699 : public GRStatePartialTrait<ARPoolContents> {
1700 static inline void* GDMIndex() { return &AutoRCIndex; }
1701};
1702} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001703
Ted Kremenek681fb352009-03-20 17:34:15 +00001704static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1705 ARStack stack = state->get<AutoreleaseStack>();
1706 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1707}
1708
1709static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1710 SymbolRef sym) {
1711
1712 SymbolRef pool = GetCurrentAutoreleasePool(state);
1713 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1714 ARCounts newCnts(0);
1715
1716 if (cnts) {
1717 const unsigned *cnt = (*cnts).lookup(sym);
1718 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1719 }
1720 else
1721 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1722
1723 return state.set<AutoreleasePoolContents>(pool, newCnts);
1724}
1725
Ted Kremenek7aef4842008-04-16 20:40:59 +00001726//===----------------------------------------------------------------------===//
1727// Transfer functions.
1728//===----------------------------------------------------------------------===//
1729
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001730namespace {
1731
Ted Kremenek7d421f32008-04-09 23:49:11 +00001732class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001733public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001734 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001735 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001736 virtual void Print(std::ostream& Out, const GRState* state,
1737 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001738 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001739
1740private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001741 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1742 SummaryLogTy;
1743
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001744 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001745 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001746 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001747 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001748
Ted Kremenek708af042009-02-05 06:50:21 +00001749 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001750 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001751 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001752 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001753 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001754 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001755
Ted Kremenekb6578942009-02-24 19:15:11 +00001756 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1757 RefVal::Kind& hasErr);
1758
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001759 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1760 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001761 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001762 ExplodedNode<GRState>* Pred,
1763 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001764 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001765
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001766 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1767 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1768
1769 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1770 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1771 GenericNodeBuilder &Builder,
1772 GRExprEngine &Eng,
1773 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001774
Ted Kremenekb6578942009-02-24 19:15:11 +00001775public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001776 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001777 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001778 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1779 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001780 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1781 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001782
Ted Kremenek708af042009-02-05 06:50:21 +00001783 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001784
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001785 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001786
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001787 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1788 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001789 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001790
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001791 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001792 const LangOptions& getLangOptions() const { return LOpts; }
1793
Ted Kremenekc26c4692009-02-18 03:48:14 +00001794 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1795 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1796 return I == SummaryLog.end() ? 0 : I->second;
1797 }
1798
Ted Kremeneka7338b42008-03-11 06:39:11 +00001799 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001800
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001801 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001802 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001803 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001804 Expr* Ex,
1805 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001806 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001807 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001808 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001809
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001810 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001811 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001812 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001813 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001814 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001815
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001816
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001817 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001818 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001819 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001820 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001821 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001822
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001823 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001824 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001825 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001826 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001827 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001828
Ted Kremeneka42be302009-02-14 01:43:44 +00001829 // Stores.
1830 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1831
Ted Kremenekffefc352008-04-11 22:25:11 +00001832 // End-of-path.
1833
1834 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001835 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001836
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001837 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001838 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001839 GRStmtNodeBuilder<GRState>& Builder,
1840 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001841 Stmt* S, const GRState* state,
1842 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001843
1844 std::pair<ExplodedNode<GRState>*, GRStateRef>
1845 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001846 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1847 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001848 // Return statements.
1849
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001850 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001851 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001852 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001853 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001854 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001855
1856 // Assumptions.
1857
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001858 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001859 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001860 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001861};
1862
1863} // end anonymous namespace
1864
Ted Kremenek681fb352009-03-20 17:34:15 +00001865static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1866 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001867 if (Sym)
1868 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001869 else
1870 Out << "<pool>";
1871 Out << ":{";
1872
1873 // Get the contents of the pool.
1874 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1875 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1876 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1877
1878 Out << '}';
1879}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001880
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001881void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1882 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001883
1884
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001885
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001886 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001887
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001888 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001889 Out << sep << nl;
1890
1891 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1892 Out << (*I).first << " : ";
1893 (*I).second.print(Out);
1894 Out << nl;
1895 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001896
1897 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001898 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001899 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001900
Ted Kremenek681fb352009-03-20 17:34:15 +00001901 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1902 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1903 PrintPool(Out, *I, state);
1904
1905 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001906}
1907
Ted Kremenek47a72422009-04-29 18:50:19 +00001908//===----------------------------------------------------------------------===//
1909// Error reporting.
1910//===----------------------------------------------------------------------===//
1911
1912namespace {
1913
1914 //===-------------===//
1915 // Bug Descriptions. //
1916 //===-------------===//
1917
1918 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1919 protected:
1920 CFRefCount& TF;
1921
1922 CFRefBug(CFRefCount* tf, const char* name)
1923 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1924 public:
1925
1926 CFRefCount& getTF() { return TF; }
1927 const CFRefCount& getTF() const { return TF; }
1928
1929 // FIXME: Eventually remove.
1930 virtual const char* getDescription() const = 0;
1931
1932 virtual bool isLeak() const { return false; }
1933 };
1934
1935 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1936 public:
1937 UseAfterRelease(CFRefCount* tf)
1938 : CFRefBug(tf, "Use-after-release") {}
1939
1940 const char* getDescription() const {
1941 return "Reference-counted object is used after it is released";
1942 }
1943 };
1944
1945 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1946 public:
1947 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1948
1949 const char* getDescription() const {
1950 return "Incorrect decrement of the reference count of an "
1951 "object is not owned at this point by the caller";
1952 }
1953 };
1954
1955 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1956 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001957 DeallocGC(CFRefCount *tf)
1958 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001959
1960 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001961 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001962 }
1963 };
1964
1965 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1966 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001967 DeallocNotOwned(CFRefCount *tf)
1968 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001969
1970 const char *getDescription() const {
1971 return "-dealloc sent to object that may be referenced elsewhere";
1972 }
1973 };
1974
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001975 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1976 public:
1977 OverAutorelease(CFRefCount *tf) :
1978 CFRefBug(tf, "Object sent -autorelease too many times") {}
1979
1980 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001981 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001982 }
1983 };
1984
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001985 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1986 public:
1987 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1988 CFRefBug(tf, "Method should return an owned object") {}
1989
1990 const char *getDescription() const {
1991 return "Object with +0 retain counts returned to caller where a +1 "
1992 "(owning) retain count is expected";
1993 }
1994 };
1995
Ted Kremenek47a72422009-04-29 18:50:19 +00001996 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1997 const bool isReturn;
1998 protected:
1999 Leak(CFRefCount* tf, const char* name, bool isRet)
2000 : CFRefBug(tf, name), isReturn(isRet) {}
2001 public:
2002
2003 const char* getDescription() const { return ""; }
2004
2005 bool isLeak() const { return true; }
2006 };
2007
2008 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2009 public:
2010 LeakAtReturn(CFRefCount* tf, const char* name)
2011 : Leak(tf, name, true) {}
2012 };
2013
2014 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2015 public:
2016 LeakWithinFunction(CFRefCount* tf, const char* name)
2017 : Leak(tf, name, false) {}
2018 };
2019
2020 //===---------===//
2021 // Bug Reports. //
2022 //===---------===//
2023
2024 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2025 protected:
2026 SymbolRef Sym;
2027 const CFRefCount &TF;
2028 public:
2029 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2030 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002031 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2032
2033 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2034 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002035 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002036
2037 virtual ~CFRefReport() {}
2038
2039 CFRefBug& getBugType() {
2040 return (CFRefBug&) RangedBugReport::getBugType();
2041 }
2042 const CFRefBug& getBugType() const {
2043 return (const CFRefBug&) RangedBugReport::getBugType();
2044 }
2045
2046 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2047 const SourceRange*& end) {
2048
2049 if (!getBugType().isLeak())
2050 RangedBugReport::getRanges(BR, beg, end);
2051 else
2052 beg = end = 0;
2053 }
2054
2055 SymbolRef getSymbol() const { return Sym; }
2056
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002057 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002058 const ExplodedNode<GRState>* N);
2059
2060 std::pair<const char**,const char**> getExtraDescriptiveText();
2061
2062 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2063 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002064 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002065 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002066
Ted Kremenek47a72422009-04-29 18:50:19 +00002067 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2068 SourceLocation AllocSite;
2069 const MemRegion* AllocBinding;
2070 public:
2071 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2072 ExplodedNode<GRState> *n, SymbolRef sym,
2073 GRExprEngine& Eng);
2074
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002075 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002076 const ExplodedNode<GRState>* N);
2077
2078 SourceLocation getLocation() const { return AllocSite; }
2079 };
2080} // end anonymous namespace
2081
2082void CFRefCount::RegisterChecks(BugReporter& BR) {
2083 useAfterRelease = new UseAfterRelease(this);
2084 BR.Register(useAfterRelease);
2085
2086 releaseNotOwned = new BadRelease(this);
2087 BR.Register(releaseNotOwned);
2088
2089 deallocGC = new DeallocGC(this);
2090 BR.Register(deallocGC);
2091
2092 deallocNotOwned = new DeallocNotOwned(this);
2093 BR.Register(deallocNotOwned);
2094
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002095 overAutorelease = new OverAutorelease(this);
2096 BR.Register(overAutorelease);
2097
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002098 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2099 BR.Register(returnNotOwnedForOwned);
2100
Ted Kremenek47a72422009-04-29 18:50:19 +00002101 // First register "return" leaks.
2102 const char* name = 0;
2103
2104 if (isGCEnabled())
2105 name = "Leak of returned object when using garbage collection";
2106 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2107 name = "Leak of returned object when not using garbage collection (GC) in "
2108 "dual GC/non-GC code";
2109 else {
2110 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2111 name = "Leak of returned object";
2112 }
2113
2114 leakAtReturn = new LeakAtReturn(this, name);
2115 BR.Register(leakAtReturn);
2116
2117 // Second, register leaks within a function/method.
2118 if (isGCEnabled())
2119 name = "Leak of object when using garbage collection";
2120 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2121 name = "Leak of object when not using garbage collection (GC) in "
2122 "dual GC/non-GC code";
2123 else {
2124 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2125 name = "Leak";
2126 }
2127
2128 leakWithinFunction = new LeakWithinFunction(this, name);
2129 BR.Register(leakWithinFunction);
2130
2131 // Save the reference to the BugReporter.
2132 this->BR = &BR;
2133}
2134
2135static const char* Msgs[] = {
2136 // GC only
2137 "Code is compiled to only use garbage collection",
2138 // No GC.
2139 "Code is compiled to use reference counts",
2140 // Hybrid, with GC.
2141 "Code is compiled to use either garbage collection (GC) or reference counts"
2142 " (non-GC). The bug occurs with GC enabled",
2143 // Hybrid, without GC
2144 "Code is compiled to use either garbage collection (GC) or reference counts"
2145 " (non-GC). The bug occurs in non-GC mode"
2146};
2147
2148std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2149 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2150
2151 switch (TF.getLangOptions().getGCMode()) {
2152 default:
2153 assert(false);
2154
2155 case LangOptions::GCOnly:
2156 assert (TF.isGCEnabled());
2157 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2158
2159 case LangOptions::NonGC:
2160 assert (!TF.isGCEnabled());
2161 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2162
2163 case LangOptions::HybridGC:
2164 if (TF.isGCEnabled())
2165 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2166 else
2167 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2168 }
2169}
2170
2171static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2172 ArgEffect X) {
2173 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2174 I!=E; ++I)
2175 if (*I == X) return true;
2176
2177 return false;
2178}
2179
2180PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2181 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002182 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002183
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002184 if (!isa<PostStmt>(N->getLocation()))
2185 return NULL;
2186
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002187 // Check if the type state has changed.
2188 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002189 GRStateRef PrevSt(PrevN->getState(), StMgr);
2190 GRStateRef CurrSt(N->getState(), StMgr);
2191
2192 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2193 if (!CurrT) return NULL;
2194
2195 const RefVal& CurrV = *CurrT;
2196 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2197
2198 // Create a string buffer to constain all the useful things we want
2199 // to tell the user.
2200 std::string sbuf;
2201 llvm::raw_string_ostream os(sbuf);
2202
2203 // This is the allocation site since the previous node had no bindings
2204 // for this symbol.
2205 if (!PrevT) {
2206 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2207
2208 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2209 // Get the name of the callee (if it is available).
2210 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2211 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2212 os << "Call to function '" << FD->getNameAsString() <<'\'';
2213 else
2214 os << "function call";
2215 }
2216 else {
2217 assert (isa<ObjCMessageExpr>(S));
2218 os << "Method";
2219 }
2220
2221 if (CurrV.getObjKind() == RetEffect::CF) {
2222 os << " returns a Core Foundation object with a ";
2223 }
2224 else {
2225 assert (CurrV.getObjKind() == RetEffect::ObjC);
2226 os << " returns an Objective-C object with a ";
2227 }
2228
2229 if (CurrV.isOwned()) {
2230 os << "+1 retain count (owning reference).";
2231
2232 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2233 assert(CurrV.getObjKind() == RetEffect::CF);
2234 os << " "
2235 "Core Foundation objects are not automatically garbage collected.";
2236 }
2237 }
2238 else {
2239 assert (CurrV.isNotOwned());
2240 os << "+0 retain count (non-owning reference).";
2241 }
2242
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002243 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002244 return new PathDiagnosticEventPiece(Pos, os.str());
2245 }
2246
2247 // Gather up the effects that were performed on the object at this
2248 // program point
2249 llvm::SmallVector<ArgEffect, 2> AEffects;
2250
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002251 if (const RetainSummary *Summ =
2252 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002253 // We only have summaries attached to nodes after evaluating CallExpr and
2254 // ObjCMessageExprs.
2255 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2256
2257 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2258 // Iterate through the parameter expressions and see if the symbol
2259 // was ever passed as an argument.
2260 unsigned i = 0;
2261
2262 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2263 AI!=AE; ++AI, ++i) {
2264
2265 // Retrieve the value of the argument. Is it the symbol
2266 // we are interested in?
2267 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2268 continue;
2269
2270 // We have an argument. Get the effect!
2271 AEffects.push_back(Summ->getArg(i));
2272 }
2273 }
2274 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2275 if (Expr *receiver = ME->getReceiver())
2276 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2277 // The symbol we are tracking is the receiver.
2278 AEffects.push_back(Summ->getReceiverEffect());
2279 }
2280 }
2281 }
2282
2283 do {
2284 // Get the previous type state.
2285 RefVal PrevV = *PrevT;
2286
2287 // Specially handle -dealloc.
2288 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2289 // Determine if the object's reference count was pushed to zero.
2290 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2291 // We may not have transitioned to 'release' if we hit an error.
2292 // This case is handled elsewhere.
2293 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002294 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002295 os << "Object released by directly sending the '-dealloc' message";
2296 break;
2297 }
2298 }
2299
2300 // Specially handle CFMakeCollectable and friends.
2301 if (contains(AEffects, MakeCollectable)) {
2302 // Get the name of the function.
2303 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2304 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2305 const FunctionDecl* FD = X.getAsFunctionDecl();
2306 const std::string& FName = FD->getNameAsString();
2307
2308 if (TF.isGCEnabled()) {
2309 // Determine if the object's reference count was pushed to zero.
2310 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2311
2312 os << "In GC mode a call to '" << FName
2313 << "' decrements an object's retain count and registers the "
2314 "object with the garbage collector. ";
2315
2316 if (CurrV.getKind() == RefVal::Released) {
2317 assert(CurrV.getCount() == 0);
2318 os << "Since it now has a 0 retain count the object can be "
2319 "automatically collected by the garbage collector.";
2320 }
2321 else
2322 os << "An object must have a 0 retain count to be garbage collected. "
2323 "After this call its retain count is +" << CurrV.getCount()
2324 << '.';
2325 }
2326 else
2327 os << "When GC is not enabled a call to '" << FName
2328 << "' has no effect on its argument.";
2329
2330 // Nothing more to say.
2331 break;
2332 }
2333
2334 // Determine if the typestate has changed.
2335 if (!(PrevV == CurrV))
2336 switch (CurrV.getKind()) {
2337 case RefVal::Owned:
2338 case RefVal::NotOwned:
2339
Ted Kremenek4d99d342009-05-08 20:01:42 +00002340 if (PrevV.getCount() == CurrV.getCount()) {
2341 // Did an autorelease message get sent?
2342 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2343 return 0;
2344
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002345 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002346 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002347 break;
2348 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002349
2350 if (PrevV.getCount() > CurrV.getCount())
2351 os << "Reference count decremented.";
2352 else
2353 os << "Reference count incremented.";
2354
2355 if (unsigned Count = CurrV.getCount())
2356 os << " The object now has a +" << Count << " retain count.";
2357
2358 if (PrevV.getKind() == RefVal::Released) {
2359 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2360 os << " The object is not eligible for garbage collection until the "
2361 "retain count reaches 0 again.";
2362 }
2363
2364 break;
2365
2366 case RefVal::Released:
2367 os << "Object released.";
2368 break;
2369
2370 case RefVal::ReturnedOwned:
2371 os << "Object returned to caller as an owning reference (single retain "
2372 "count transferred to caller).";
2373 break;
2374
2375 case RefVal::ReturnedNotOwned:
2376 os << "Object returned to caller with a +0 (non-owning) retain count.";
2377 break;
2378
2379 default:
2380 return NULL;
2381 }
2382
2383 // Emit any remaining diagnostics for the argument effects (if any).
2384 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2385 E=AEffects.end(); I != E; ++I) {
2386
2387 // A bunch of things have alternate behavior under GC.
2388 if (TF.isGCEnabled())
2389 switch (*I) {
2390 default: break;
2391 case Autorelease:
2392 os << "In GC mode an 'autorelease' has no effect.";
2393 continue;
2394 case IncRefMsg:
2395 os << "In GC mode the 'retain' message has no effect.";
2396 continue;
2397 case DecRefMsg:
2398 os << "In GC mode the 'release' message has no effect.";
2399 continue;
2400 }
2401 }
2402 } while(0);
2403
2404 if (os.str().empty())
2405 return 0; // We have nothing to say!
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002406
2407 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002408 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002409 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2410
2411 // Add the range by scanning the children of the statement for any bindings
2412 // to Sym.
2413 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2414 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2415 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2416 P->addRange(Exp->getSourceRange());
2417 break;
2418 }
2419
2420 return P;
2421}
2422
2423namespace {
2424 class VISIBILITY_HIDDEN FindUniqueBinding :
2425 public StoreManager::BindingsHandler {
2426 SymbolRef Sym;
2427 const MemRegion* Binding;
2428 bool First;
2429
2430 public:
2431 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2432
2433 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2434 SVal val) {
2435
2436 SymbolRef SymV = val.getAsSymbol();
2437 if (!SymV || SymV != Sym)
2438 return true;
2439
2440 if (Binding) {
2441 First = false;
2442 return false;
2443 }
2444 else
2445 Binding = R;
2446
2447 return true;
2448 }
2449
2450 operator bool() { return First && Binding; }
2451 const MemRegion* getRegion() { return Binding; }
2452 };
2453}
2454
2455static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2456GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2457 SymbolRef Sym) {
2458
2459 // Find both first node that referred to the tracked symbol and the
2460 // memory location that value was store to.
2461 const ExplodedNode<GRState>* Last = N;
2462 const MemRegion* FirstBinding = 0;
2463
2464 while (N) {
2465 const GRState* St = N->getState();
2466 RefBindings B = St->get<RefBindings>();
2467
2468 if (!B.lookup(Sym))
2469 break;
2470
2471 FindUniqueBinding FB(Sym);
2472 StateMgr.iterBindings(St, FB);
2473 if (FB) FirstBinding = FB.getRegion();
2474
2475 Last = N;
2476 N = N->pred_empty() ? NULL : *(N->pred_begin());
2477 }
2478
2479 return std::make_pair(Last, FirstBinding);
2480}
2481
2482PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002483CFRefReport::getEndPath(BugReporterContext& BRC,
2484 const ExplodedNode<GRState>* EndN) {
2485 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002486 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002487 BRC.addNotableSymbol(Sym);
2488 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002489}
2490
2491PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002492CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2493 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002494
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002495 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002496 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002497 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002498
2499 // We are reporting a leak. Walk up the graph to get to the first node where
2500 // the symbol appeared, and also get the first VarDecl that tracked object
2501 // is stored to.
2502 const ExplodedNode<GRState>* AllocNode = 0;
2503 const MemRegion* FirstBinding = 0;
2504
2505 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002506 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002507
2508 // Get the allocate site.
2509 assert(AllocNode);
2510 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2511
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002512 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002513 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2514
2515 // Compute an actual location for the leak. Sometimes a leak doesn't
2516 // occur at an actual statement (e.g., transition between blocks; end
2517 // of function) so we need to walk the graph and compute a real location.
2518 const ExplodedNode<GRState>* LeakN = EndN;
2519 PathDiagnosticLocation L;
2520
2521 while (LeakN) {
2522 ProgramPoint P = LeakN->getLocation();
2523
2524 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2525 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2526 break;
2527 }
2528 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2529 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2530 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2531 break;
2532 }
2533 }
2534
2535 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2536 }
2537
2538 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002539 const Decl &D = BRC.getCodeDecl();
2540 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002541 }
2542
2543 std::string sbuf;
2544 llvm::raw_string_ostream os(sbuf);
2545
2546 os << "Object allocated on line " << AllocLine;
2547
2548 if (FirstBinding)
2549 os << " and stored into '" << FirstBinding->getString() << '\'';
2550
2551 // Get the retain count.
2552 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2553
2554 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2555 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2556 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2557 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002558 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002559 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002560 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002561 << "') does not contain 'copy' or otherwise starts with"
2562 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002563 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002564 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002565 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2566 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2567 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002568 << "' is potentially leaked when using garbage collection. Callers "
2569 "of this method do not expect a returned object with a +1 retain "
2570 "count since they expect the object to be managed by the garbage "
2571 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002572 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002573 else
2574 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002575 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002576
2577 return new PathDiagnosticEventPiece(L, os.str());
2578}
2579
Ted Kremenek47a72422009-04-29 18:50:19 +00002580CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2581 ExplodedNode<GRState> *n,
2582 SymbolRef sym, GRExprEngine& Eng)
2583: CFRefReport(D, tf, n, sym)
2584{
2585
2586 // Most bug reports are cached at the location where they occured.
2587 // With leaks, we want to unique them by the location where they were
2588 // allocated, and only report a single path. To do this, we need to find
2589 // the allocation site of a piece of tracked memory, which we do via a
2590 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2591 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2592 // that all ancestor nodes that represent the allocation site have the
2593 // same SourceLocation.
2594 const ExplodedNode<GRState>* AllocNode = 0;
2595
2596 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002597 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002598
2599 // Get the SourceLocation for the allocation site.
2600 ProgramPoint P = AllocNode->getLocation();
2601 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2602
2603 // Fill in the description of the bug.
2604 Description.clear();
2605 llvm::raw_string_ostream os(Description);
2606 SourceManager& SMgr = Eng.getContext().getSourceManager();
2607 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002608 os << "Potential leak ";
2609 if (tf.isGCEnabled()) {
2610 os << "(when using garbage collection) ";
2611 }
2612 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002613
2614 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2615 if (AllocBinding)
2616 os << " and stored into '" << AllocBinding->getString() << '\'';
2617}
2618
2619//===----------------------------------------------------------------------===//
2620// Main checker logic.
2621//===----------------------------------------------------------------------===//
2622
Ted Kremenek272aa852008-06-25 21:21:56 +00002623/// GetReturnType - Used to get the return type of a message expression or
2624/// function call with the intention of affixing that type to a tracked symbol.
2625/// While the the return type can be queried directly from RetEx, when
2626/// invoking class methods we augment to the return type to be that of
2627/// a pointer to the class (as opposed it just being id).
2628static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2629
2630 QualType RetTy = RetE->getType();
2631
2632 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002633 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002634 if (!PT)
2635 return RetTy;
2636
2637 // If RetEx is not a message expression just return its type.
2638 // If RetEx is a message expression, return its types if it is something
2639 /// more specific than id.
2640
2641 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2642
Steve Naroff17c03822009-02-12 17:52:19 +00002643 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002644 return RetTy;
2645
2646 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2647
2648 // At this point we know the return type of the message expression is id.
2649 // If we have an ObjCInterceDecl, we know this is a call to a class method
2650 // whose type we can resolve. In such cases, promote the return type to
2651 // Class*.
2652 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2653}
2654
2655
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002656void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002657 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002658 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002659 Expr* Ex,
2660 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002661 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002662 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002663 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002664
Ted Kremeneka7338b42008-03-11 06:39:11 +00002665 // Get the state.
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002666 GRStateManager& StateMgr = Eng.getStateManager();
2667 GRStateRef state(Builder.GetState(Pred), StateMgr);
2668 ASTContext& Ctx = StateMgr.getContext();
2669 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek227c5372008-05-06 02:41:27 +00002670
2671 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002672 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002673 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002674 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002675 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002676
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002677 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002678 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002679 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002680
Ted Kremenek74556a12009-03-26 03:35:11 +00002681 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002682 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002683 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002684 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002685 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002686 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002687 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002688 }
2689 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002690 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002691
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002692 if (isa<Loc>(V)) {
2693 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002694 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002695 continue;
2696
2697 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002698
2699 // FIXME: Either this logic should also be replicated in GRSimpleVals
2700 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002701
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002702 // FIXME: We can have collisions on the conjured symbol if the
2703 // expression *I also creates conjured symbols. We probably want
2704 // to identify conjured symbols by an expression pair: the enclosing
2705 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002706 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002707
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002708 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002709
Ted Kremenek73ec7732009-05-06 18:19:24 +00002710 if (R) {
2711 // Are we dealing with an ElementRegion? If the element type is
2712 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xuea6851b2009-05-11 14:28:14 +00002713 // is a variable region then strip off the ElementRegion.
Ted Kremenek73ec7732009-05-06 18:19:24 +00002714 // FIXME: We really need to think about this for the general case
2715 // as sometimes we are reasoning about arrays and other times
2716 // about (char*), etc., is just a form of passing raw bytes.
2717 // e.g., void *p = alloca(); foo((char*)p);
2718 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2719 // Checking for 'integral type' is probably too promiscuous, but
2720 // we'll leave it in for now until we have a systematic way of
2721 // handling all of these cases. Eventually we need to come up
2722 // with an interface to StoreManager so that this logic can be
2723 // approriately delegated to the respective StoreManagers while
2724 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002725 // invalidating reference counts), probably via callbacks.
Ted Kremenek1cba5772009-05-11 22:55:17 +00002726 if (ER->getElementType()->isIntegralType()) {
2727 const MemRegion *superReg = ER->getSuperRegion();
2728 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2729 isa<ObjCIvarRegion>(superReg))
2730 R = cast<TypedRegion>(superReg);
2731 }
2732
Ted Kremenek73ec7732009-05-06 18:19:24 +00002733 // FIXME: What about layers of ElementRegions?
2734 }
2735
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002736 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002737 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002738
Ted Kremenek53b24182009-03-04 22:56:43 +00002739 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002740 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002741
Ted Kremenek53b24182009-03-04 22:56:43 +00002742 if (R->isBoundable(Ctx)) {
2743 // Set the value of the variable to be a conjured symbol.
2744 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002745 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002746
Zhongxing Xu079dc352009-04-09 06:03:54 +00002747 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002748 ValueManager &ValMgr = Eng.getValueManager();
2749 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002750 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002751 }
2752 else if (const RecordType *RT = T->getAsStructureType()) {
2753 // Handle structs in a not so awesome way. Here we just
2754 // eagerly bind new symbols to the fields. In reality we
2755 // should have the store manager handle this. The idea is just
2756 // to prototype some basic functionality here. All of this logic
2757 // should one day soon just go away.
2758 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2759
2760 // No record definition. There is nothing we can do.
2761 if (!RD)
2762 continue;
2763
2764 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2765
2766 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002767 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2768 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002769
2770 // For now just handle scalar fields.
2771 FieldDecl *FD = *FI;
2772 QualType FT = FD->getType();
2773
2774 if (Loc::IsLocType(FT) ||
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002775 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002776 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002777
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002778 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002779 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002780 }
2781 }
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002782 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2783 // Set the default value of the array to conjured symbol.
2784 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2785 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2786 Count);
2787 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2788 StateMgr);
2789 } else {
Ted Kremenek53b24182009-03-04 22:56:43 +00002790 // Just blast away other values.
2791 state = state.BindLoc(*MR, UnknownVal());
2792 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002793 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002794 }
2795 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002796 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002797 }
2798 else {
2799 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002800 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002801 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002802 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002803 else if (isa<nonloc::LocAsInteger>(V))
2804 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002805 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002806
Ted Kremenek272aa852008-06-25 21:21:56 +00002807 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002808 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002809 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002810 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002811 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002812 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002813 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002814 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002815 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002816 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002817 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002818 }
2819 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002820
Ted Kremenek272aa852008-06-25 21:21:56 +00002821 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002822 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002823 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002824 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002825 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002826 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002827
Ted Kremenekf2717b02008-07-18 17:24:20 +00002828 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002829 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002830
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002831 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2832 assert(Receiver);
2833 SVal V = state.GetSValAsScalarOrLoc(Receiver);
2834 bool found = false;
2835 if (SymbolRef Sym = V.getAsLocSymbol())
2836 if (state.get<RefBindings>(Sym)) {
2837 found = true;
2838 RE = Summaries.getObjAllocRetEffect();
2839 }
2840
2841 if (!found)
2842 RE = RetEffect::MakeNoRet();
2843 }
2844
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002845 switch (RE.getKind()) {
2846 default:
2847 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002848
Ted Kremenek8f90e712008-10-17 22:23:12 +00002849 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002850
Ted Kremenek455dd862008-04-11 20:23:24 +00002851 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002852 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2853 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002854
Ted Kremenek8f90e712008-10-17 22:23:12 +00002855 // FIXME: We eventually should handle structs and other compound types
2856 // that are returned by value.
2857
2858 QualType T = Ex->getType();
2859
Ted Kremenek79413a52008-11-13 06:10:40 +00002860 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002861 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002862 ValueManager &ValMgr = Eng.getValueManager();
2863 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002864 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002865 }
2866
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002867 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002868 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002869
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002870 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002871 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002872 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002873 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002874 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002875 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002876 break;
2877 }
2878
Ted Kremenek227c5372008-05-06 02:41:27 +00002879 case RetEffect::ReceiverAlias: {
2880 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002881 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002882 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002883 break;
2884 }
2885
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002886 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002887 case RetEffect::OwnedSymbol: {
2888 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002889 ValueManager &ValMgr = Eng.getValueManager();
2890 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2891 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2892 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2893 RetT));
2894 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002895
2896 // FIXME: Add a flag to the checker where allocations are assumed to
2897 // *not fail.
2898#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002899 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2900 bool isFeasible;
2901 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2902 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2903 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002904#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002905
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002906 break;
2907 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002908
2909 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002910 case RetEffect::NotOwnedSymbol: {
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::makeNotOwned(RE.getObjKind(),
2916 RetT));
2917 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002918 break;
2919 }
2920 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002921
Ted Kremenek0dd65012009-02-18 02:00:25 +00002922 // Generate a sink node if we are at the end of a path.
2923 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002924 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2925 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002926
2927 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002928 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002929}
2930
2931
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002932void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002933 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002934 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002935 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002936 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002937 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002938 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002939 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002940
Ted Kremenek286e9852009-05-04 04:57:00 +00002941 assert(Summ);
2942 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002943 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002944}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002945
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002946void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002947 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002948 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002949 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002950 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002951 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002952
Ted Kremenek272aa852008-06-25 21:21:56 +00002953 if (Expr* Receiver = ME->getReceiver()) {
2954 // We need the type-information of the tracked receiver object
2955 // Retrieve it from the state.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002956 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek272aa852008-06-25 21:21:56 +00002957
2958 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2959 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002960 // FIXME: Is this really working as expected? There are cases where
2961 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002962 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002963 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002964
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002965 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002966 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002967 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002968 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002969
2970 if (const PointerType* PT = Ty->getAsPointerType()) {
2971 QualType PointeeTy = PT->getPointeeType();
2972
2973 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2974 ID = IT->getDecl();
2975 }
2976 }
2977 }
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002978
2979 // FIXME: this is a hack. This may or may not be the actual method
2980 // that is called.
2981 if (!ID) {
2982 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
2983 if (const ObjCInterfaceType *p =
2984 PT->getPointeeType()->getAsObjCInterfaceType())
2985 ID = p->getDecl();
2986 }
2987
Ted Kremenek04e00302009-04-29 17:09:14 +00002988 // FIXME: The receiver could be a reference to a class, meaning that
2989 // we should use the class method.
2990 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002991
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002992 // Special-case: are we sending a mesage to "self"?
2993 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002994 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2995 if (Expr* Receiver = ME->getReceiver()) {
2996 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2997 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2998 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2999 // Update the summary to make the default argument effect
3000 // 'StopTracking'.
3001 Summ = Summaries.copySummary(Summ);
3002 Summ->setDefaultArgEffect(StopTracking);
3003 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003004 }
3005 }
Ted Kremenek272aa852008-06-25 21:21:56 +00003006 }
Ted Kremenek1feab292008-04-16 04:28:53 +00003007 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00003008 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00003009
Ted Kremenek286e9852009-05-04 04:57:00 +00003010 if (!Summ)
3011 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00003012
Ted Kremenek286e9852009-05-04 04:57:00 +00003013 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00003014 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00003015}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003016
3017namespace {
3018class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
3019 GRStateRef state;
3020public:
3021 StopTrackingCallback(GRStateRef st) : state(st) {}
3022 GRStateRef getState() { return state; }
3023
3024 bool VisitSymbol(SymbolRef sym) {
3025 state = state.remove<RefBindings>(sym);
3026 return true;
3027 }
Ted Kremenek926abf22008-05-06 04:20:12 +00003028
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003029 const GRState* getState() const { return state.getState(); }
3030};
3031} // end anonymous namespace
3032
3033
Ted Kremeneka42be302009-02-14 01:43:44 +00003034void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00003035 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00003036 bool escapes = false;
3037
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003038 // A value escapes in three possible cases (this may change):
3039 //
3040 // (1) we are binding to something that is not a memory region.
3041 // (2) we are binding to a memregion that does not have stack storage
3042 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003043 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00003044 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003045
Ted Kremeneka42be302009-02-14 01:43:44 +00003046 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003047 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003048 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003049 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
3050 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003051
3052 if (!escapes) {
3053 // To test (3), generate a new state with the binding removed. If it is
3054 // the same state, then it escapes (since the store cannot represent
3055 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00003056 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003057 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003058 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003059
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003060 // If our store can represent the binding and we aren't storing to something
3061 // that doesn't have local storage then just return and have the simulation
3062 // state continue as is.
3063 if (!escapes)
3064 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003065
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003066 // Otherwise, find all symbols referenced by 'val' that we are tracking
3067 // and stop tracking them.
3068 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003069}
3070
Ted Kremenek541db372008-04-24 23:57:27 +00003071
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003072 // Return statements.
3073
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003074void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003075 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003076 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003077 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003078 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003079
3080 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003081 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003082 return;
3083
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003084 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00003085 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003086
Ted Kremenek74556a12009-03-26 03:35:11 +00003087 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003088 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003089
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003090 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003091 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003092
3093 if (!T)
3094 return;
3095
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003096 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003097 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003098
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003099 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003100 case RefVal::Owned: {
3101 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003102 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003103 X.setCount(cnt - 1);
3104 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003105 break;
3106 }
3107
3108 case RefVal::NotOwned: {
3109 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003110 if (cnt) {
3111 X.setCount(cnt - 1);
3112 X = X ^ RefVal::ReturnedOwned;
3113 }
3114 else {
3115 X = X ^ RefVal::ReturnedNotOwned;
3116 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003117 break;
3118 }
3119
3120 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003121 return;
3122 }
3123
3124 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003125 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003126 Pred = Builder.MakeNode(Dst, S, Pred, state);
3127
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003128 // Did we cache out?
3129 if (!Pred)
3130 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003131
3132 // Update the autorelease counts.
3133 static unsigned autoreleasetag = 0;
3134 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3135 bool stop = false;
3136 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3137 X, stop);
3138
3139 // Did we cache out?
3140 if (!Pred || stop)
3141 return;
3142
3143 // Get the updated binding.
3144 T = state.get<RefBindings>(Sym);
3145 assert(T);
3146 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003147
Ted Kremenek47a72422009-04-29 18:50:19 +00003148 // Any leaks or other errors?
3149 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003150 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003151 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003152 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003153 RetEffect RE = Summ.getRetEffect();
3154 bool hasError = false;
3155
Ted Kremenek5b44a402009-05-16 01:38:01 +00003156 if (RE.getKind() != RetEffect::NoRet) {
3157 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3158 // Things are more complicated with garbage collection. If the
3159 // returned object is suppose to be an Objective-C object, we have
3160 // a leak (as the caller expects a GC'ed object) because no
3161 // method should return ownership unless it returns a CF object.
3162 X = X ^ RefVal::ErrorGCLeakReturned;
3163
3164 // Keep this false until this is properly tested.
3165 hasError = true;
3166 }
3167 else if (!RE.isOwned()) {
3168 // Either we are using GC and the returned object is a CF type
3169 // or we aren't using GC. In either case, we expect that the
3170 // enclosing method is expected to return ownership.
3171 hasError = true;
3172 X = X ^ RefVal::ErrorLeakReturned;
3173 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003174 }
3175
3176 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003177 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003178 static int ReturnOwnLeakTag = 0;
3179 state = state.set<RefBindings>(Sym, X);
3180 ExplodedNode<GRState> *N =
3181 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3182 if (N) {
3183 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003184 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3185 N, Sym, Eng);
3186 BR->EmitReport(report);
3187 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003188 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003189 }
3190 }
3191 else if (X.isReturnedNotOwned()) {
3192 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3193 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3194 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3195 if (Summ.getRetEffect().isOwned()) {
3196 // Trying to return a not owned object to a caller expecting an
3197 // owned object.
3198
3199 static int ReturnNotOwnedForOwnedTag = 0;
3200 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3201 if (ExplodedNode<GRState> *N =
3202 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3203 state, Pred)) {
3204 CFRefReport *report =
3205 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3206 *this, N, Sym);
3207 BR->EmitReport(report);
3208 }
3209 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003210 }
3211 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003212}
3213
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003214// Assumptions.
3215
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003216const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3217 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003218 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003219 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003220
3221 // FIXME: We may add to the interface of EvalAssume the list of symbols
3222 // whose assumptions have changed. For now we just iterate through the
3223 // bindings and check if any of the tracked symbols are NULL. This isn't
3224 // too bad since the number of symbols we will track in practice are
3225 // probably small and EvalAssume is only called at branches and a few
3226 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003227 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003228
3229 if (B.isEmpty())
3230 return St;
3231
3232 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003233
3234 GRStateRef state(St, VMgr);
3235 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003236
3237 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003238 // Check if the symbol is null (or equal to any constant).
3239 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003240 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003241 changed = true;
3242 B = RefBFactory.Remove(B, I.getKey());
3243 }
3244 }
3245
Ted Kremenek91781202008-08-17 03:20:02 +00003246 if (changed)
3247 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003248
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003249 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003250}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003251
Ted Kremenekb6578942009-02-24 19:15:11 +00003252GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3253 RefVal V, ArgEffect E,
3254 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003255
3256 // In GC mode [... release] and [... retain] do nothing.
3257 switch (E) {
3258 default: break;
3259 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3260 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003261 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003262 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3263 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003264 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003265
Ted Kremenek6537a642009-03-17 19:42:23 +00003266 // Handle all use-after-releases.
3267 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3268 V = V ^ RefVal::ErrorUseAfterRelease;
3269 hasErr = V.getKind();
3270 return state.set<RefBindings>(sym, V);
3271 }
3272
Ted Kremenek0d721572008-03-11 17:48:22 +00003273 switch (E) {
3274 default:
3275 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003276
3277 case Dealloc:
3278 // Any use of -dealloc in GC is *bad*.
3279 if (isGCEnabled()) {
3280 V = V ^ RefVal::ErrorDeallocGC;
3281 hasErr = V.getKind();
3282 break;
3283 }
3284
3285 switch (V.getKind()) {
3286 default:
3287 assert(false && "Invalid case.");
3288 case RefVal::Owned:
3289 // The object immediately transitions to the released state.
3290 V = V ^ RefVal::Released;
3291 V.clearCounts();
3292 return state.set<RefBindings>(sym, V);
3293 case RefVal::NotOwned:
3294 V = V ^ RefVal::ErrorDeallocNotOwned;
3295 hasErr = V.getKind();
3296 break;
3297 }
3298 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003299
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003300 case NewAutoreleasePool:
3301 assert(!isGCEnabled());
3302 return state.add<AutoreleaseStack>(sym);
3303
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003304 case MayEscape:
3305 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003306 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003307 break;
3308 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003309
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003310 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003311
Ted Kremenekede40b72008-07-09 18:11:16 +00003312 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003313 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003314 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003315
Ted Kremenek9b112d22009-01-28 21:44:40 +00003316 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003317 if (isGCEnabled())
3318 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003319
3320 // Update the autorelease counts.
3321 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003322 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003323 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003324
Ted Kremenek227c5372008-05-06 02:41:27 +00003325 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003326 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003327
Ted Kremenek0d721572008-03-11 17:48:22 +00003328 case IncRef:
3329 switch (V.getKind()) {
3330 default:
3331 assert(false);
3332
3333 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003334 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003335 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003336 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003337 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003338 // Non-GC cases are handled above.
3339 assert(isGCEnabled());
3340 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003341 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003342 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003343 break;
3344
Ted Kremenek272aa852008-06-25 21:21:56 +00003345 case SelfOwn:
3346 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003347 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003348 case DecRef:
3349 switch (V.getKind()) {
3350 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003351 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003352 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003353
Ted Kremenek272aa852008-06-25 21:21:56 +00003354 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003355 assert(V.getCount() > 0);
3356 if (V.getCount() == 1) V = V ^ RefVal::Released;
3357 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003358 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003359
Ted Kremenek272aa852008-06-25 21:21:56 +00003360 case RefVal::NotOwned:
3361 if (V.getCount() > 0)
3362 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003363 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003364 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003365 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003366 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003367 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003368
Ted Kremenek0d721572008-03-11 17:48:22 +00003369 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003370 // Non-GC cases are handled above.
3371 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003372 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003373 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003374 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003375 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003376 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003377 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003378 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003379}
3380
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003381//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003382// Handle dead symbols and end-of-path.
3383//===----------------------------------------------------------------------===//
3384
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003385std::pair<ExplodedNode<GRState>*, GRStateRef>
3386CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3387 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003388 GRExprEngine &Eng,
3389 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003390
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003391 unsigned ACnt = V.getAutoreleaseCount();
3392 stop = false;
3393
3394 // No autorelease counts? Nothing to be done.
3395 if (!ACnt)
3396 return std::make_pair(Pred, state);
3397
3398 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3399 unsigned Cnt = V.getCount();
3400
Ted Kremenek0603cf52009-05-11 15:26:06 +00003401 // FIXME: Handle sending 'autorelease' to already released object.
3402
3403 if (V.getKind() == RefVal::ReturnedOwned)
3404 ++Cnt;
3405
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003406 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003407 if (ACnt == Cnt) {
3408 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003409 if (V.getKind() == RefVal::ReturnedOwned)
3410 V = V ^ RefVal::ReturnedNotOwned;
3411 else
3412 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003413 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003414 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003415 V.setCount(Cnt - ACnt);
3416 V.setAutoreleaseCount(0);
3417 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003418 state = state.set<RefBindings>(Sym, V);
3419 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3420 stop = (N == 0);
3421 return std::make_pair(N, state);
3422 }
3423
3424 // Woah! More autorelease counts then retain counts left.
3425 // Emit hard error.
3426 stop = true;
3427 V = V ^ RefVal::ErrorOverAutorelease;
3428 state = state.set<RefBindings>(Sym, V);
3429
3430 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003431 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003432
3433 std::string sbuf;
3434 llvm::raw_string_ostream os(sbuf);
Ted Kremenek2e6ce412009-05-15 06:02:08 +00003435 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekbd271be2009-05-10 05:11:21 +00003436 if (V.getAutoreleaseCount() > 1)
3437 os << V.getAutoreleaseCount() << " times";
3438 os << " but the object has ";
3439 if (V.getCount() == 0)
3440 os << "zero (locally visible)";
3441 else
3442 os << "+" << V.getCount();
3443 os << " retain counts";
3444
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003445 CFRefReport *report =
3446 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003447 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003448 BR->EmitReport(report);
3449 }
3450
3451 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003452}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003453
3454GRStateRef
3455CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3456 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3457
3458 bool hasLeak = V.isOwned() ||
3459 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3460
3461 if (!hasLeak)
3462 return state.remove<RefBindings>(sid);
3463
3464 Leaked.push_back(sid);
3465 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3466}
3467
3468ExplodedNode<GRState>*
3469CFRefCount::ProcessLeaks(GRStateRef state,
3470 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3471 GenericNodeBuilder &Builder,
3472 GRExprEngine& Eng,
3473 ExplodedNode<GRState> *Pred) {
3474
3475 if (Leaked.empty())
3476 return Pred;
3477
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003478 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003479 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003480
3481 if (N) {
3482 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3483 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3484
3485 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3486 : leakAtReturn);
3487 assert(BT && "BugType not initialized.");
3488 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3489 BR->EmitReport(report);
3490 }
3491 }
3492
3493 return N;
3494}
3495
Ted Kremenek708af042009-02-05 06:50:21 +00003496void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3497 GREndPathNodeBuilder<GRState>& Builder) {
3498
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003499 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003500 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003501 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003502 ExplodedNode<GRState> *Pred = 0;
3503
3504 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003505 bool stop = false;
3506 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3507 (*I).first,
3508 (*I).second, stop);
3509
3510 if (stop)
3511 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003512 }
3513
3514 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003515 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003516
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003517 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3518 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3519
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003520 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003521}
3522
3523void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3524 GRExprEngine& Eng,
3525 GRStmtNodeBuilder<GRState>& Builder,
3526 ExplodedNode<GRState>* Pred,
3527 Stmt* S,
3528 const GRState* St,
3529 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003530
3531 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003532 RefBindings B = state.get<RefBindings>();
3533
3534 // Update counts from autorelease pools
3535 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3536 E = SymReaper.dead_end(); I != E; ++I) {
3537 SymbolRef Sym = *I;
3538 if (const RefVal* T = B.lookup(Sym)){
3539 // Use the symbol as the tag.
3540 // FIXME: This might not be as unique as we would like.
3541 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003542 bool stop = false;
3543 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3544 Sym, *T, stop);
3545 if (stop)
3546 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003547 }
3548 }
3549
3550 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003551 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003552
3553 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003554 E = SymReaper.dead_end(); I != E; ++I) {
3555 if (const RefVal* T = B.lookup(*I))
3556 state = HandleSymbolDeath(state, *I, *T, Leaked);
3557 }
Ted Kremenek708af042009-02-05 06:50:21 +00003558
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003559 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003560 {
3561 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3562 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3563 }
Ted Kremenek708af042009-02-05 06:50:21 +00003564
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003565 // Did we cache out?
3566 if (!Pred)
3567 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003568
3569 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003570 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003571
Ted Kremenek876d8df2009-02-19 23:47:02 +00003572 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003573 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3574
Ted Kremenek876d8df2009-02-19 23:47:02 +00003575 state = state.set<RefBindings>(B);
3576 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003577}
3578
3579void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3580 GRStmtNodeBuilder<GRState>& Builder,
3581 Expr* NodeExpr, Expr* ErrorExpr,
3582 ExplodedNode<GRState>* Pred,
3583 const GRState* St,
3584 RefVal::Kind hasErr, SymbolRef Sym) {
3585 Builder.BuildSinks = true;
3586 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3587
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003588 if (!N)
3589 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003590
3591 CFRefBug *BT = 0;
3592
Ted Kremenek6537a642009-03-17 19:42:23 +00003593 switch (hasErr) {
3594 default:
3595 assert(false && "Unhandled error.");
3596 return;
3597 case RefVal::ErrorUseAfterRelease:
3598 BT = static_cast<CFRefBug*>(useAfterRelease);
3599 break;
3600 case RefVal::ErrorReleaseNotOwned:
3601 BT = static_cast<CFRefBug*>(releaseNotOwned);
3602 break;
3603 case RefVal::ErrorDeallocGC:
3604 BT = static_cast<CFRefBug*>(deallocGC);
3605 break;
3606 case RefVal::ErrorDeallocNotOwned:
3607 BT = static_cast<CFRefBug*>(deallocNotOwned);
3608 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003609 }
3610
Ted Kremenekc26c4692009-02-18 03:48:14 +00003611 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003612 report->addRange(ErrorExpr->getSourceRange());
3613 BR->EmitReport(report);
3614}
3615
3616//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003617// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003618//===----------------------------------------------------------------------===//
3619
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003620GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3621 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003622 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003623}