blob: c74668cf0fc91c8454a8afd94e0a34a229154254 [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 Kremenekfe30beb2008-04-30 23:47:44 +000015#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000016#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000017#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000018#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000019#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000020#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000023#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenekd1c53ff2009-06-26 00:05:51 +000024#include "clang/Analysis/PathSensitive/GRTransferFuncs.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 Kremenek9449ca92008-08-12 20:41:56 +000033#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000034
35using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000036
37//===----------------------------------------------------------------------===//
38// Utility functions.
39//===----------------------------------------------------------------------===//
40
Ted Kremenekb6f09542008-10-24 21:18:08 +000041// The "fundamental rule" for naming conventions of methods:
42// (url broken into two lines)
43// http://developer.apple.com/documentation/Cocoa/Conceptual/
44// MemoryMgmt/Tasks/MemoryManagementRules.html
45//
46// "You take ownership of an object if you create it using a method whose name
47// begins with “alloc” or “new” or contains “copy” (for example, alloc,
48// newObject, or mutableCopy), or if you send it a retain message. You are
49// responsible for relinquishing ownership of objects you own using release
50// or autorelease. Any other time you receive an object, you must
51// not release it."
52//
Ted Kremenek4395b452009-02-21 05:13:43 +000053
54using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000055using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000056
57enum NamingConvention { NoConvention, CreateRule, InitRule };
58
59static inline bool isWordEnd(char ch, char prev, char next) {
60 return ch == '\0'
61 || (islower(prev) && isupper(ch)) // xxxC
62 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
63 || !isalpha(ch);
64}
65
66static inline const char* parseWord(const char* s) {
67 char ch = *s, prev = '\0';
68 assert(ch != '\0');
69 char next = *(s+1);
70 while (!isWordEnd(ch, prev, next)) {
71 prev = ch;
72 ch = next;
73 next = *((++s)+1);
74 }
75 return s;
76}
77
Ted Kremenek613ef972009-05-15 15:49:00 +000078static NamingConvention deriveNamingConvention(Selector S) {
79 IdentifierInfo *II = S.getIdentifierInfoForSlot(0);
80
81 if (!II)
82 return NoConvention;
83
84 const char *s = II->getName();
85
Ted Kremenek4395b452009-02-21 05:13:43 +000086 // A method/function name may contain a prefix. We don't know it is there,
87 // however, until we encounter the first '_'.
88 bool InPossiblePrefix = true;
89 bool AtBeginning = true;
90 NamingConvention C = NoConvention;
91
92 while (*s != '\0') {
93 // Skip '_'.
94 if (*s == '_') {
95 if (InPossiblePrefix) {
96 InPossiblePrefix = false;
97 AtBeginning = true;
98 // Discard whatever 'convention' we
99 // had already derived since it occurs
100 // in the prefix.
101 C = NoConvention;
102 }
103 ++s;
104 continue;
105 }
106
107 // Skip numbers, ':', etc.
108 if (!isalpha(*s)) {
109 ++s;
110 continue;
111 }
112
113 const char *wordEnd = parseWord(s);
114 assert(wordEnd > s);
115 unsigned len = wordEnd - s;
116
117 switch (len) {
118 default:
119 break;
120 case 3:
121 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000122 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 break;
125 case 4:
126 // Methods starting with 'alloc' or contain 'copy' follow the
127 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000128 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000129 C = CreateRule;
130 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000131 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000132 C = InitRule;
133 break;
134 case 5:
135 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
136 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000137 break;
138 }
139
140 // If we aren't in the prefix and have a derived convention then just
141 // return it now.
142 if (!InPossiblePrefix && C != NoConvention)
143 return C;
144
145 AtBeginning = false;
146 s = wordEnd;
147 }
148
149 // We will get here if there wasn't more than one word
150 // after the prefix.
151 return C;
152}
153
Ted Kremenek613ef972009-05-15 15:49:00 +0000154static bool followsFundamentalRule(Selector S) {
155 return deriveNamingConvention(S) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000156}
157
Ted Kremenek314b1952009-04-29 23:03:22 +0000158static const ObjCMethodDecl*
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000159ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD) {
Ted Kremenek314b1952009-04-29 23:03:22 +0000160 ObjCInterfaceDecl *ID =
161 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
162
163 return MD->isInstanceMethod()
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000164 ? ID->lookupInstanceMethod(MD->getSelector())
165 : ID->lookupClassMethod(MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000166}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000167
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000168namespace {
169class VISIBILITY_HIDDEN GenericNodeBuilder {
170 GRStmtNodeBuilder<GRState> *SNB;
171 Stmt *S;
172 const void *tag;
173 GREndPathNodeBuilder<GRState> *ENB;
174public:
175 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
176 const void *t)
177 : SNB(&snb), S(s), tag(t), ENB(0) {}
178 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
179 : SNB(0), S(0), tag(0), ENB(&enb) {}
180
181 ExplodedNode<GRState> *MakeNode(const GRState *state,
182 ExplodedNode<GRState> *Pred) {
183 if (SNB)
Ted Kremenek3e3328d2009-05-09 01:50:57 +0000184 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000185
186 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000187 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000188 }
189};
190} // end anonymous namespace
191
Ted Kremenek7d421f32008-04-09 23:49:11 +0000192//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000193// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000194//===----------------------------------------------------------------------===//
195
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000196static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000197 IdentifierInfo* II = &Ctx.Idents.get(name);
198 return Ctx.Selectors.getSelector(0, &II);
199}
200
Ted Kremenek0e344d42008-05-06 00:30:21 +0000201static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
202 IdentifierInfo* II = &Ctx.Idents.get(name);
203 return Ctx.Selectors.getSelector(1, &II);
204}
205
Ted Kremenek272aa852008-06-25 21:21:56 +0000206//===----------------------------------------------------------------------===//
207// Type querying functions.
208//===----------------------------------------------------------------------===//
209
Ted Kremenek17144e82009-01-12 21:45:02 +0000210static bool hasPrefix(const char* s, const char* prefix) {
211 if (!prefix)
212 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000213
Ted Kremenek17144e82009-01-12 21:45:02 +0000214 char c = *s;
215 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000216
Ted Kremenek17144e82009-01-12 21:45:02 +0000217 while (c != '\0' && cP != '\0') {
218 if (c != cP) break;
219 c = *(++s);
220 cP = *(++prefix);
221 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000222
Ted Kremenek17144e82009-01-12 21:45:02 +0000223 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000224}
225
Ted Kremenek17144e82009-01-12 21:45:02 +0000226static bool hasSuffix(const char* s, const char* suffix) {
227 const char* loc = strstr(s, suffix);
228 return loc && strcmp(suffix, loc) == 0;
229}
230
231static bool isRefType(QualType RetTy, const char* prefix,
232 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000233
Ted Kremenek2f289b62009-05-12 04:53:03 +0000234 // Recursively walk the typedef stack, allowing typedefs of reference types.
235 while (1) {
236 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
237 const char* TDName = TD->getDecl()->getIdentifier()->getName();
238 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
239 return true;
240
241 RetTy = TD->getDecl()->getUnderlyingType();
242 continue;
243 }
244 break;
Ted Kremenek17144e82009-01-12 21:45:02 +0000245 }
246
247 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000248 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000249
250 // Is the type void*?
251 const PointerType* PT = RetTy->getAsPointerType();
252 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000253 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000254
255 // Does the name start with the prefix?
256 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000257}
258
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000259//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000260// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000261//===----------------------------------------------------------------------===//
262
Ted Kremenek272aa852008-06-25 21:21:56 +0000263/// ArgEffect is used to summarize a function/method call's effect on a
264/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000265enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
266 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
267 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000268
Ted Kremeneka7338b42008-03-11 06:39:11 +0000269namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000270template <> struct FoldingSetTrait<ArgEffect> {
271static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
272 ID.AddInteger((unsigned) X);
273}
Ted Kremenek272aa852008-06-25 21:21:56 +0000274};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000275} // end llvm namespace
276
Ted Kremeneka56ae162009-05-03 05:20:50 +0000277/// ArgEffects summarizes the effects of a function/method call on all of
278/// its arguments.
279typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
280
Ted Kremeneka7338b42008-03-11 06:39:11 +0000281namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000282
283/// RetEffect is used to summarize a function/method call's behavior with
284/// respect to its return value.
285class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000286public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000287 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000288 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
289 OwnedWhenTrackedReceiver };
Ted Kremenek68621b92009-01-28 05:56:51 +0000290
291 enum ObjKind { CF, ObjC, AnyObj };
292
Ted Kremeneka7338b42008-03-11 06:39:11 +0000293private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000294 Kind K;
295 ObjKind O;
296 unsigned index;
297
298 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
299 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000300
Ted Kremeneka7338b42008-03-11 06:39:11 +0000301public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000302 Kind getKind() const { return K; }
303
304 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000305
306 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000307 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000308 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000309 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000310
Ted Kremenek314b1952009-04-29 23:03:22 +0000311 bool isOwned() const {
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000312 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
313 K == OwnedWhenTrackedReceiver;
Ted Kremenek314b1952009-04-29 23:03:22 +0000314 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +0000315
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000316 static RetEffect MakeOwnedWhenTrackedReceiver() {
317 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
318 }
319
Ted Kremenek272aa852008-06-25 21:21:56 +0000320 static RetEffect MakeAlias(unsigned Idx) {
321 return RetEffect(Alias, Idx);
322 }
323 static RetEffect MakeReceiverAlias() {
324 return RetEffect(ReceiverAlias);
325 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000326 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
327 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000328 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000329 static RetEffect MakeNotOwned(ObjKind o) {
330 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000331 }
332 static RetEffect MakeGCNotOwned() {
333 return RetEffect(GCNotOwnedSymbol, ObjC);
334 }
335
Ted Kremenek272aa852008-06-25 21:21:56 +0000336 static RetEffect MakeNoRet() {
337 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000338 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000339
Ted Kremenek272aa852008-06-25 21:21:56 +0000340 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000341 ID.AddInteger((unsigned)K);
342 ID.AddInteger((unsigned)O);
343 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000344 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000345};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000346
Ted Kremenek272aa852008-06-25 21:21:56 +0000347
Ted Kremenek2f226732009-05-04 05:31:22 +0000348class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000349 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
350 /// specifies the argument (starting from 0). This can be sparsely
351 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000352 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000353
354 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
355 /// do not have an entry in Args.
356 ArgEffect DefaultArgEffect;
357
Ted Kremenek272aa852008-06-25 21:21:56 +0000358 /// Receiver - If this summary applies to an Objective-C message expression,
359 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000360 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000361
362 /// Ret - The effect on the return value. Used to indicate if the
363 /// function/method call returns a new tracked symbol, returns an
364 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000365 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000366
Ted Kremenekf2717b02008-07-18 17:24:20 +0000367 /// EndPath - Indicates that execution of this method/function should
368 /// terminate the simulation of a path.
369 bool EndPath;
370
Ted Kremeneka7338b42008-03-11 06:39:11 +0000371public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000372 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000373 ArgEffect ReceiverEff, bool endpath = false)
374 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
375 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000376
Ted Kremenek272aa852008-06-25 21:21:56 +0000377 /// getArg - Return the argument effect on the argument specified by
378 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000379 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000380 if (const ArgEffect *AE = Args.lookup(idx))
381 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000382
Ted Kremenekbcaff792008-05-06 15:44:25 +0000383 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000384 }
385
Ted Kremenek2f226732009-05-04 05:31:22 +0000386 /// setDefaultArgEffect - Set the default argument effect.
387 void setDefaultArgEffect(ArgEffect E) {
388 DefaultArgEffect = E;
389 }
390
391 /// setArg - Set the argument effect on the argument specified by idx.
392 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
393 Args = AF.Add(Args, idx, E);
394 }
395
Ted Kremenek272aa852008-06-25 21:21:56 +0000396 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000397 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000398
Ted Kremenek2f226732009-05-04 05:31:22 +0000399 /// setRetEffect - Set the effect of the return value of the call.
400 void setRetEffect(RetEffect E) { Ret = E; }
401
Ted Kremenekf2717b02008-07-18 17:24:20 +0000402 /// isEndPath - Returns true if executing the given method/function should
403 /// terminate the path.
404 bool isEndPath() const { return EndPath; }
405
Ted Kremenek272aa852008-06-25 21:21:56 +0000406 /// getReceiverEffect - Returns the effect on the receiver of the call.
407 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000408 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000409
Ted Kremenek2f226732009-05-04 05:31:22 +0000410 /// setReceiverEffect - Set the effect on the receiver of the call.
411 void setReceiverEffect(ArgEffect E) { Receiver = E; }
412
Ted Kremeneka56ae162009-05-03 05:20:50 +0000413 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000414
Ted Kremeneka56ae162009-05-03 05:20:50 +0000415 ExprIterator begin_args() const { return Args.begin(); }
416 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000417
Ted Kremeneka56ae162009-05-03 05:20:50 +0000418 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000419 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000420 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000421 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000422 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000423 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000424 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000425 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000426 }
427
428 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000429 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000430 }
431};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000432} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000433
Ted Kremenek272aa852008-06-25 21:21:56 +0000434//===----------------------------------------------------------------------===//
435// Data structures for constructing summaries.
436//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000437
Ted Kremenek272aa852008-06-25 21:21:56 +0000438namespace {
439class VISIBILITY_HIDDEN ObjCSummaryKey {
440 IdentifierInfo* II;
441 Selector S;
442public:
443 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
444 : II(ii), S(s) {}
445
Ted Kremenek314b1952009-04-29 23:03:22 +0000446 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000447 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +0000448
449 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
450 : II(d ? d->getIdentifier() : ii), S(s) {}
Ted Kremenek272aa852008-06-25 21:21:56 +0000451
452 ObjCSummaryKey(Selector s)
453 : II(0), S(s) {}
454
455 IdentifierInfo* getIdentifier() const { return II; }
456 Selector getSelector() const { return S; }
457};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000458}
459
460namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000461template <> struct DenseMapInfo<ObjCSummaryKey> {
462 static inline ObjCSummaryKey getEmptyKey() {
463 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
464 DenseMapInfo<Selector>::getEmptyKey());
465 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000466
Ted Kremenek272aa852008-06-25 21:21:56 +0000467 static inline ObjCSummaryKey getTombstoneKey() {
468 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
469 DenseMapInfo<Selector>::getTombstoneKey());
470 }
471
472 static unsigned getHashValue(const ObjCSummaryKey &V) {
473 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
474 & 0x88888888)
475 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
476 & 0x55555555);
477 }
478
479 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
480 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
481 RHS.getIdentifier()) &&
482 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
483 RHS.getSelector());
484 }
485
486 static bool isPod() {
487 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
488 DenseMapInfo<Selector>::isPod();
489 }
490};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000491} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000492
Ted Kremenek84f010c2008-06-23 23:30:29 +0000493namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000494class VISIBILITY_HIDDEN ObjCSummaryCache {
495 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
496 MapTy M;
497public:
498 ObjCSummaryCache() {}
499
500 typedef MapTy::iterator iterator;
501
Ted Kremenek314b1952009-04-29 23:03:22 +0000502 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
503 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000504 // Lookup the method using the decl for the class @interface. If we
505 // have no decl, lookup using the class name.
506 return D ? find(D, S) : find(ClsName, S);
507 }
508
Ted Kremenek314b1952009-04-29 23:03:22 +0000509 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000510 // Do a lookup with the (D,S) pair. If we find a match return
511 // the iterator.
512 ObjCSummaryKey K(D, S);
513 MapTy::iterator I = M.find(K);
514
515 if (I != M.end() || !D)
516 return I;
517
518 // Walk the super chain. If we find a hit with a parent, we'll end
519 // up returning that summary. We actually allow that key (null,S), as
520 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
521 // generate initial summaries without having to worry about NSObject
522 // being declared.
523 // FIXME: We may change this at some point.
524 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
525 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
526 break;
527
528 if (!C)
529 return I;
530 }
531
532 // Cache the summary with original key to make the next lookup faster
533 // and return the iterator.
534 M[K] = I->second;
535 return I;
536 }
537
Ted Kremenek9449ca92008-08-12 20:41:56 +0000538
Ted Kremenek272aa852008-06-25 21:21:56 +0000539 iterator find(Expr* Receiver, Selector S) {
540 return find(getReceiverDecl(Receiver), S);
541 }
542
543 iterator find(IdentifierInfo* II, Selector S) {
544 // FIXME: Class method lookup. Right now we dont' have a good way
545 // of going between IdentifierInfo* and the class hierarchy.
546 iterator I = M.find(ObjCSummaryKey(II, S));
547 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
548 }
549
550 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
551
552 const PointerType* PT = E->getType()->getAsPointerType();
553 if (!PT) return 0;
554
555 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
Ted Kremenek272aa852008-06-25 21:21:56 +0000556
557 return OI ? OI->getDecl() : 0;
558 }
559
560 iterator end() { return M.end(); }
561
562 RetainSummary*& operator[](ObjCMessageExpr* ME) {
563
564 Selector S = ME->getSelector();
565
566 if (Expr* Receiver = ME->getReceiver()) {
567 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
568 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
569 }
570
571 return M[ObjCSummaryKey(ME->getClassName(), S)];
572 }
573
574 RetainSummary*& operator[](ObjCSummaryKey K) {
575 return M[K];
576 }
577
578 RetainSummary*& operator[](Selector S) {
579 return M[ ObjCSummaryKey(S) ];
580 }
581};
582} // end anonymous namespace
583
584//===----------------------------------------------------------------------===//
585// Data structures for managing collections of summaries.
586//===----------------------------------------------------------------------===//
587
588namespace {
589class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000590
591 //==-----------------------------------------------------------------==//
592 // Typedefs.
593 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000594
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000595 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
596 FuncSummariesTy;
597
Ted Kremenek84f010c2008-06-23 23:30:29 +0000598 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000599
600 //==-----------------------------------------------------------------==//
601 // Data.
602 //==-----------------------------------------------------------------==//
603
Ted Kremenek272aa852008-06-25 21:21:56 +0000604 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000605 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000606
Ted Kremenekede40b72008-07-09 18:11:16 +0000607 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
608 /// "CFDictionaryCreate".
609 IdentifierInfo* CFDictionaryCreateII;
610
Ted Kremenek272aa852008-06-25 21:21:56 +0000611 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000612 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000613
Ted Kremenek272aa852008-06-25 21:21:56 +0000614 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000615 FuncSummariesTy FuncSummaries;
616
Ted Kremenek272aa852008-06-25 21:21:56 +0000617 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
618 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000619 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000620
Ted Kremenek272aa852008-06-25 21:21:56 +0000621 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000622 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000623
Ted Kremenek272aa852008-06-25 21:21:56 +0000624 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
625 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000626 llvm::BumpPtrAllocator BPAlloc;
627
Ted Kremeneka56ae162009-05-03 05:20:50 +0000628 /// AF - A factory for ArgEffects objects.
629 ArgEffects::Factory AF;
630
Ted Kremenek272aa852008-06-25 21:21:56 +0000631 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000632 ArgEffects ScratchArgs;
633
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000634 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
635 /// objects.
636 RetEffect ObjCAllocRetE;
Ted Kremenekd27ed0d2009-06-05 23:18:01 +0000637
Ted Kremenek77bec862009-06-11 18:17:24 +0000638 /// ObjCInitRetE - Default return effect for init methods returning Objective-C
Ted Kremenekd27ed0d2009-06-05 23:18:01 +0000639 /// objects.
640 RetEffect ObjCInitRetE;
Ted Kremenek77bec862009-06-11 18:17:24 +0000641
Ted Kremenek286e9852009-05-04 04:57:00 +0000642 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000643 RetainSummary* StopSummary;
644
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000645 //==-----------------------------------------------------------------==//
646 // Methods.
647 //==-----------------------------------------------------------------==//
648
Ted Kremenek272aa852008-06-25 21:21:56 +0000649 /// getArgEffects - Returns a persistent ArgEffects object based on the
650 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000651 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000652
Ted Kremenek562c1302008-05-05 16:51:50 +0000653 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000654
655public:
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000656 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
657
Ted Kremenek2f226732009-05-04 05:31:22 +0000658 RetainSummary *getDefaultSummary() {
659 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
660 return new (Summ) RetainSummary(DefaultSummary);
661 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000662
Ted Kremenek064ef322009-02-23 16:51:39 +0000663 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000664
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000665 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
666 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000667 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000668
Ted Kremeneka56ae162009-05-03 05:20:50 +0000669 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000670 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000671 ArgEffect DefaultEff = MayEscape,
672 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000673
Ted Kremenek266d8b62008-05-06 02:26:56 +0000674 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000675 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000676 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000677 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000678 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000679
Ted Kremeneka821b792009-04-29 05:04:30 +0000680 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000681 if (StopSummary)
682 return StopSummary;
683
684 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
685 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000686
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000687 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000688 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000689
Ted Kremeneka821b792009-04-29 05:04:30 +0000690 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000691
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000692 void InitializeClassMethodSummaries();
693 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000694
Ted Kremenek9b42e062009-05-03 04:42:10 +0000695 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000696 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000697
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000698private:
699
Ted Kremenekf2717b02008-07-18 17:24:20 +0000700 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
701 RetainSummary* Summ) {
702 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
703 }
704
Ted Kremenek272aa852008-06-25 21:21:56 +0000705 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
706 ObjCClassMethodSummaries[S] = Summ;
707 }
708
709 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
710 ObjCMethodSummaries[S] = Summ;
711 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000712
713 void addClassMethSummary(const char* Cls, const char* nullaryName,
714 RetainSummary *Summ) {
715 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
716 Selector S = GetNullarySelector(nullaryName, Ctx);
717 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
718 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000719
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000720 void addInstMethSummary(const char* Cls, const char* nullaryName,
721 RetainSummary *Summ) {
722 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
723 Selector S = GetNullarySelector(nullaryName, Ctx);
724 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
725 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000726
727 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000728 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000729
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000730 while (const char* s = va_arg(argp, const char*))
731 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000732
733 return Ctx.Selectors.getSelector(II.size(), &II[0]);
734 }
735
736 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
737 RetainSummary* Summ, va_list argp) {
738 Selector S = generateSelector(argp);
739 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000740 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000741
742 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
743 va_list argp;
744 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000745 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000746 va_end(argp);
747 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000748
749 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
750 va_list argp;
751 va_start(argp, Summ);
752 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
753 va_end(argp);
754 }
755
756 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
757 va_list argp;
758 va_start(argp, Summ);
759 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
760 va_end(argp);
761 }
762
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000763 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000764 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
765 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000766 DoNothing, DoNothing, true);
767 va_list argp;
768 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000769 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000770 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000771 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000772
Ted Kremeneka7338b42008-03-11 06:39:11 +0000773public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000774
775 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000776 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000777 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000778 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000779 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
780 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek77bec862009-06-11 18:17:24 +0000781 ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned()
782 : RetEffect::MakeOwnedWhenTrackedReceiver()),
Ted Kremenek286e9852009-05-04 04:57:00 +0000783 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
784 RetEffect::MakeNoRet() /* return effect */,
Ted Kremeneka13b0862009-05-11 18:30:24 +0000785 MayEscape, /* default argument effect */
786 DoNothing /* receiver effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000787 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000788
789 InitializeClassMethodSummaries();
790 InitializeMethodSummaries();
791 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000792
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000793 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000794
Ted Kremenekd13c1872008-06-24 03:56:45 +0000795 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000796
Ted Kremenek314b1952009-04-29 23:03:22 +0000797 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
798 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000799 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000800 ID, ME->getMethodDecl(), ME->getType());
801 }
802
Ted Kremenek04e00302009-04-29 17:09:14 +0000803 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000804 const ObjCInterfaceDecl* ID,
805 const ObjCMethodDecl *MD,
806 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000807
808 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000809 const ObjCInterfaceDecl *ID,
810 const ObjCMethodDecl *MD,
811 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000812
813 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
814 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
815 ME->getClassInfo().first,
816 ME->getMethodDecl(), ME->getType());
817 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000818
819 /// getMethodSummary - This version of getMethodSummary is used to query
820 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000821 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
822 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000823 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000824 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000825 IdentifierInfo *ClsName = ID->getIdentifier();
826 QualType ResultTy = MD->getResultType();
827
Ted Kremenek81eb4642009-04-30 05:47:23 +0000828 // Resolve the method decl last.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000829 if (const ObjCMethodDecl *InterfaceMD = ResolveToInterfaceMethodDecl(MD))
Ted Kremenek81eb4642009-04-30 05:47:23 +0000830 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000831
Ted Kremenek91b89a42009-04-29 17:17:48 +0000832 if (MD->isInstanceMethod())
833 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
834 else
835 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
836 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000837
Ted Kremenek314b1952009-04-29 23:03:22 +0000838 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
839 Selector S, QualType RetTy);
840
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000841 void updateSummaryFromAnnotations(RetainSummary &Summ,
842 const ObjCMethodDecl *MD);
843
844 void updateSummaryFromAnnotations(RetainSummary &Summ,
845 const FunctionDecl *FD);
846
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000847 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000848
849 RetainSummary *copySummary(RetainSummary *OldSumm) {
850 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
851 new (Summ) RetainSummary(*OldSumm);
852 return Summ;
853 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000854};
855
856} // end anonymous namespace
857
858//===----------------------------------------------------------------------===//
859// Implementation of checker data structures.
860//===----------------------------------------------------------------------===//
861
Ted Kremeneka56ae162009-05-03 05:20:50 +0000862RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000863
Ted Kremeneka56ae162009-05-03 05:20:50 +0000864ArgEffects RetainSummaryManager::getArgEffects() {
865 ArgEffects AE = ScratchArgs;
866 ScratchArgs = AF.GetEmptyMap();
867 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000868}
869
Ted Kremenek266d8b62008-05-06 02:26:56 +0000870RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000871RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000872 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000873 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000874 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000875 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000876 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000877 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000878 return Summ;
879}
880
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000881//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000882// Predicates.
883//===----------------------------------------------------------------------===//
884
Ted Kremenek9b42e062009-05-03 04:42:10 +0000885bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000886 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000887 return false;
888
Ted Kremenek0d813552009-04-23 22:11:07 +0000889 // We assume that id<..>, id, and "Class" all represent tracked objects.
890 const PointerType *PT = Ty->getAsPointerType();
891 if (PT == 0)
892 return true;
893
894 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000895
896 // We assume that id<..>, id, and "Class" all represent tracked objects.
897 if (!OT)
898 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000899
Ted Kremenek5b44a402009-05-16 01:38:01 +0000900 // Does the interface subclass NSObject?
901 // FIXME: We can memoize here if this gets too expensive.
Ted Kremenek35920ed2009-01-07 00:39:56 +0000902 ObjCInterfaceDecl* ID = OT->getDecl();
903
Ted Kremenek5b44a402009-05-16 01:38:01 +0000904 // Assume that anything declared with a forward declaration and no
905 // @interface subclasses NSObject.
906 if (ID->isForwardDecl())
907 return true;
908
909 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
910
911
Ted Kremenek35920ed2009-01-07 00:39:56 +0000912 for ( ; ID ; ID = ID->getSuperClass())
913 if (ID->getIdentifier() == NSObjectII)
914 return true;
915
916 return false;
917}
918
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000919bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
920 return isRefType(T, "CF") || // Core Foundation.
921 isRefType(T, "CG") || // Core Graphics.
922 isRefType(T, "DADisk") || // Disk Arbitration API.
923 isRefType(T, "DADissenter") ||
924 isRefType(T, "DASessionRef");
925}
926
Ted Kremenek35920ed2009-01-07 00:39:56 +0000927//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000928// Summary creation for functions (largely uses of Core Foundation).
929//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000930
Ted Kremenek17144e82009-01-12 21:45:02 +0000931static bool isRetain(FunctionDecl* FD, const char* FName) {
932 const char* loc = strstr(FName, "Retain");
933 return loc && loc[sizeof("Retain")-1] == '\0';
934}
935
936static bool isRelease(FunctionDecl* FD, const char* FName) {
937 const char* loc = strstr(FName, "Release");
938 return loc && loc[sizeof("Release")-1] == '\0';
939}
940
Ted Kremenekd13c1872008-06-24 03:56:45 +0000941RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000942 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000943 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000944 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000945 return I->second;
946
Ted Kremenek64cddf12009-05-04 15:34:07 +0000947 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000948 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000949
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000950 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000951 // We generate "stop" summaries for implicitly defined functions.
952 if (FD->isImplicit()) {
953 S = getPersistentStopSummary();
954 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000955 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000956
Ted Kremenek064ef322009-02-23 16:51:39 +0000957 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000958 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000959 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000960 const char* FName = FD->getIdentifier()->getName();
961
Ted Kremenek38c6f022009-03-05 22:11:14 +0000962 // Strip away preceding '_'. Doing this here will effect all the checks
963 // down below.
964 while (*FName == '_') ++FName;
965
Ted Kremenek17144e82009-01-12 21:45:02 +0000966 // Inspect the result type.
967 QualType RetTy = FT->getResultType();
968
969 // FIXME: This should all be refactored into a chain of "summary lookup"
970 // filters.
Ted Kremenek648a7702009-06-15 20:36:07 +0000971 assert (ScratchArgs.isEmpty());
972
Ted Kremenek77bec862009-06-11 18:17:24 +0000973 switch (strlen(FName)) {
974 default: break;
Ted Kremenek648a7702009-06-15 20:36:07 +0000975
976
Ted Kremenek77bec862009-06-11 18:17:24 +0000977 case 17:
978 // Handle: id NSMakeCollectable(CFTypeRef)
979 if (!memcmp(FName, "NSMakeCollectable", 17)) {
980 S = (RetTy == Ctx.getObjCIdType())
981 ? getUnarySummary(FT, cfmakecollectable)
982 : getPersistentStopSummary();
983 }
Ted Kremenek648a7702009-06-15 20:36:07 +0000984 else if (!memcmp(FName, "IOBSDNameMatching", 17) ||
985 !memcmp(FName, "IOServiceMatching", 17)) {
986 // Part of <rdar://problem/6961230>. (IOKit)
987 // This should be addressed using a API table.
988 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
989 DoNothing, DoNothing);
990 }
Ted Kremenek77bec862009-06-11 18:17:24 +0000991 break;
Ted Kremenek648a7702009-06-15 20:36:07 +0000992
993 case 21:
994 if (!memcmp(FName, "IOServiceNameMatching", 21)) {
995 // Part of <rdar://problem/6961230>. (IOKit)
996 // This should be addressed using a API table.
997 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
998 DoNothing, DoNothing);
999 }
1000 break;
1001
1002 case 24:
1003 if (!memcmp(FName, "IOServiceAddNotification", 24)) {
1004 // Part of <rdar://problem/6961230>. (IOKit)
1005 // This should be addressed using a API table.
1006 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1007 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1008 }
1009 break;
1010
1011 case 25:
1012 if (!memcmp(FName, "IORegistryEntryIDMatching", 25)) {
1013 // Part of <rdar://problem/6961230>. (IOKit)
1014 // This should be addressed using a API table.
1015 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1016 DoNothing, DoNothing);
1017 }
1018 break;
1019
1020 case 26:
1021 if (!memcmp(FName, "IOOpenFirmwarePathMatching", 26)) {
1022 // Part of <rdar://problem/6961230>. (IOKit)
1023 // This should be addressed using a API table.
1024 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1025 DoNothing, DoNothing);
1026 }
1027 break;
1028
Ted Kremenek77bec862009-06-11 18:17:24 +00001029 case 27:
1030 if (!memcmp(FName, "IOServiceGetMatchingService", 27)) {
1031 // Part of <rdar://problem/6961230>.
1032 // This should be addressed using a API table.
Ted Kremenek77bec862009-06-11 18:17:24 +00001033 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1034 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1035 }
1036 break;
1037
1038 case 28:
1039 if (!memcmp(FName, "IOServiceGetMatchingServices", 28)) {
1040 // FIXES: <rdar://problem/6326900>
1041 // This should be addressed using a API table. This strcmp is also
1042 // a little gross, but there is no need to super optimize here.
Ted Kremenek77bec862009-06-11 18:17:24 +00001043 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1044 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1045 }
1046 break;
Ted Kremenek648a7702009-06-15 20:36:07 +00001047
1048 case 32:
1049 if (!memcmp(FName, "IOServiceAddMatchingNotification", 32)) {
1050 // Part of <rdar://problem/6961230>.
1051 // This should be addressed using a API table.
1052 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1053 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1054 }
1055 break;
Ted Kremenek77bec862009-06-11 18:17:24 +00001056 }
1057
1058 // Did we get a summary?
1059 if (S)
1060 break;
Ted Kremenek7b88c892009-03-17 22:43:44 +00001061
1062 // Enable this code once the semantics of NSDeallocateObject are resolved
1063 // for GC. <rdar://problem/6619988>
1064#if 0
1065 // Handle: NSDeallocateObject(id anObject);
1066 // This method does allow 'nil' (although we don't check it now).
1067 if (strcmp(FName, "NSDeallocateObject") == 0) {
1068 return RetTy == Ctx.VoidTy
1069 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1070 : getPersistentStopSummary();
1071 }
1072#endif
Ted Kremenek17144e82009-01-12 21:45:02 +00001073
1074 if (RetTy->isPointerType()) {
1075 // For CoreFoundation ('CF') types.
1076 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1077 if (isRetain(FD, FName))
1078 S = getUnarySummary(FT, cfretain);
1079 else if (strstr(FName, "MakeCollectable"))
1080 S = getUnarySummary(FT, cfmakecollectable);
1081 else
1082 S = getCFCreateGetRuleSummary(FD, FName);
1083
1084 break;
1085 }
1086
1087 // For CoreGraphics ('CG') types.
1088 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1089 if (isRetain(FD, FName))
1090 S = getUnarySummary(FT, cfretain);
1091 else
1092 S = getCFCreateGetRuleSummary(FD, FName);
1093
1094 break;
1095 }
1096
1097 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1098 if (isRefType(RetTy, "DADisk") ||
1099 isRefType(RetTy, "DADissenter") ||
1100 isRefType(RetTy, "DASessionRef")) {
1101 S = getCFCreateGetRuleSummary(FD, FName);
1102 break;
1103 }
1104
1105 break;
1106 }
1107
1108 // Check for release functions, the only kind of functions that we care
1109 // about that don't return a pointer type.
1110 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001111 // Test for 'CGCF'.
1112 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1113 FName += 4;
1114 else
1115 FName += 2;
1116
1117 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001118 S = getUnarySummary(FT, cfrelease);
1119 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001120 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001121 // Remaining CoreFoundation and CoreGraphics functions.
1122 // We use to assume that they all strictly followed the ownership idiom
1123 // and that ownership cannot be transferred. While this is technically
1124 // correct, many methods allow a tracked object to escape. For example:
1125 //
1126 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1127 // CFDictionaryAddValue(y, key, x);
1128 // CFRelease(x);
1129 // ... it is okay to use 'x' since 'y' has a reference to it
1130 //
1131 // We handle this and similar cases with the follow heuristic. If the
1132 // function name contains "InsertValue", "SetValue" or "AddValue" then
1133 // we assume that arguments may "escape."
1134 //
1135 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1136 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001137 CStrInCStrNoCase(FName, "SetValue") ||
1138 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001139 ? MayEscape : DoNothing;
1140
1141 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001142 }
1143 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001144 }
1145 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001146
1147 if (!S)
1148 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001149
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001150 // Annotations override defaults.
1151 assert(S);
1152 updateSummaryFromAnnotations(*S, FD);
1153
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001154 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001155 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001156}
1157
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001158RetainSummary*
1159RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1160 const char* FName) {
1161
Ted Kremenek562c1302008-05-05 16:51:50 +00001162 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1163 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001164
Ted Kremenek562c1302008-05-05 16:51:50 +00001165 if (strstr(FName, "Get"))
1166 return getCFSummaryGetRule(FD);
1167
Ted Kremenek286e9852009-05-04 04:57:00 +00001168 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001169}
1170
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001171RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001172RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1173 UnaryFuncKind func) {
1174
Ted Kremenek17144e82009-01-12 21:45:02 +00001175 // Sanity check that this is *really* a unary function. This can
1176 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001177 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001178 if (!FTP || FTP->getNumArgs() != 1)
1179 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001180
Ted Kremeneka56ae162009-05-03 05:20:50 +00001181 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001182
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001183 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001184 case cfretain: {
1185 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001186 return getPersistentSummary(RetEffect::MakeAlias(0),
1187 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001188 }
1189
1190 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001191 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001192 return getPersistentSummary(RetEffect::MakeNoRet(),
1193 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001194 }
1195
1196 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001197 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001198 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001199 }
1200
1201 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001202 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001203 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001204 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001205}
1206
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001207RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001208 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001209
1210 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001211 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1212 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001213 }
1214
Ted Kremenek68621b92009-01-28 05:56:51 +00001215 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001216}
1217
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001218RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001219 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001220 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1221 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001222}
1223
Ted Kremeneka7338b42008-03-11 06:39:11 +00001224//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001225// Summary creation for Selectors.
1226//===----------------------------------------------------------------------===//
1227
Ted Kremenekbcaff792008-05-06 15:44:25 +00001228RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001229RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001230 assert(ScratchArgs.isEmpty());
1231 // 'init' methods conceptually return a newly allocated object and claim
1232 // the receiver.
1233 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
Ted Kremenekd27ed0d2009-06-05 23:18:01 +00001234 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001235
1236 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001237}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001238
1239void
1240RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1241 const FunctionDecl *FD) {
1242 if (!FD)
1243 return;
1244
Ted Kremenek77bec862009-06-11 18:17:24 +00001245 QualType RetTy = FD->getResultType();
1246
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001247 // Determine if there is a special return effect for this method.
Ted Kremenek401674a2009-06-05 23:00:33 +00001248 if (isTrackedObjCObjectType(RetTy)) {
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001249 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001250 Summ.setRetEffect(ObjCAllocRetE);
1251 }
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001252 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenek401674a2009-06-05 23:00:33 +00001253 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek77bec862009-06-11 18:17:24 +00001254 }
1255 }
1256 else if (RetTy->getAsPointerType()) {
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001257 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001258 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1259 }
1260 }
1261}
1262
1263void
1264RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1265 const ObjCMethodDecl *MD) {
1266 if (!MD)
1267 return;
1268
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001269 bool isTrackedLoc = false;
1270
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001271 // Determine if there is a special return effect for this method.
1272 if (isTrackedObjCObjectType(MD->getResultType())) {
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001273 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001274 Summ.setRetEffect(ObjCAllocRetE);
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001275 return;
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001276 }
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001277
1278 isTrackedLoc = true;
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001279 }
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001280
1281 if (!isTrackedLoc)
1282 isTrackedLoc = MD->getResultType()->getAsPointerType() != NULL;
1283
1284 if (isTrackedLoc && MD->getAttr<CFReturnsRetainedAttr>())
1285 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001286}
1287
Ted Kremenekbcaff792008-05-06 15:44:25 +00001288RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001289RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1290 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001291
Ted Kremenek578498a2009-04-29 00:42:39 +00001292 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001293 // Scan the method decl for 'void*' arguments. These should be treated
1294 // as 'StopTracking' because they are often used with delegates.
1295 // Delegates are a frequent form of false positives with the retain
1296 // count checker.
1297 unsigned i = 0;
1298 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1299 E = MD->param_end(); I != E; ++I, ++i)
1300 if (ParmVarDecl *PD = *I) {
1301 QualType Ty = Ctx.getCanonicalType(PD->getType());
1302 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001303 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001304 }
1305 }
1306
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001307 // Any special effect for the receiver?
1308 ArgEffect ReceiverEff = DoNothing;
1309
1310 // If one of the arguments in the selector has the keyword 'delegate' we
1311 // should stop tracking the reference count for the receiver. This is
1312 // because the reference count is quite possibly handled by a delegate
1313 // method.
1314 if (S.isKeywordSelector()) {
1315 const std::string &str = S.getAsString();
1316 assert(!str.empty());
1317 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1318 }
1319
Ted Kremenek174a0772009-04-23 23:08:22 +00001320 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001321 if (isTrackedObjCObjectType(RetTy)) {
1322 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1323 // by instance methods.
Ted Kremenek613ef972009-05-15 15:49:00 +00001324 RetEffect E = followsFundamentalRule(S)
1325 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001326
1327 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001328 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001329
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001330 // Look for methods that return an owned core foundation object.
1331 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek613ef972009-05-15 15:49:00 +00001332 RetEffect E = followsFundamentalRule(S)
1333 ? RetEffect::MakeOwned(RetEffect::CF, true)
1334 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001335
1336 return getPersistentSummary(E, ReceiverEff, MayEscape);
1337 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001338
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001339 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001340 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001341
Ted Kremenek2f226732009-05-04 05:31:22 +00001342 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001343}
1344
1345RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001346RetainSummaryManager::getInstanceMethodSummary(Selector S,
1347 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001348 const ObjCInterfaceDecl* ID,
1349 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001350 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001351
Ted Kremeneka821b792009-04-29 05:04:30 +00001352 // Look up a summary in our summary cache.
1353 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001354
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001355 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001356 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001357
Ted Kremeneka56ae162009-05-03 05:20:50 +00001358 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001359 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001360
Ted Kremenek2f226732009-05-04 05:31:22 +00001361 // "initXXX": pass-through for receiver.
Ted Kremenek613ef972009-05-15 15:49:00 +00001362 if (deriveNamingConvention(S) == InitRule)
Ted Kremenek2f226732009-05-04 05:31:22 +00001363 Summ = getInitMethodSummary(RetTy);
1364 else
1365 Summ = getCommonMethodSummary(MD, S, RetTy);
1366
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001367 // Annotations override defaults.
1368 updateSummaryFromAnnotations(*Summ, MD);
1369
Ted Kremenek2f226732009-05-04 05:31:22 +00001370 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001371 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001372 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001373}
1374
Ted Kremeneka7722b72008-05-06 21:26:51 +00001375RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001376RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001377 const ObjCInterfaceDecl *ID,
1378 const ObjCMethodDecl *MD,
1379 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001380
Ted Kremenek578498a2009-04-29 00:42:39 +00001381 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001382 ObjCMethodSummariesTy::iterator I =
1383 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001384
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001385 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001386 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001387
1388 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001389
1390 // Annotations override defaults.
1391 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001392
Ted Kremenek2f226732009-05-04 05:31:22 +00001393 // Memoize the summary.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00001394 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001395 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001396}
1397
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001398void RetainSummaryManager::InitializeClassMethodSummaries() {
1399 assert(ScratchArgs.isEmpty());
1400 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001401
Ted Kremenek272aa852008-06-25 21:21:56 +00001402 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1403 // NSObject and its derivatives.
1404 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1405 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1406 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001407
1408 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001409 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001410 GetNullarySelector("currentHandler", Ctx),
1411 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001412
1413 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001414 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001415 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1416 GetUnarySelector("addObject", Ctx),
1417 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001418 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001419
1420 // Create the summaries for [NSObject performSelector...]. We treat
1421 // these as 'stop tracking' for the arguments because they are often
1422 // used for delegates that can release the object. When we have better
1423 // inter-procedural analysis we can potentially do something better. This
1424 // workaround is to remove false positives.
1425 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1426 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1427 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1428 "afterDelay", NULL);
1429 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1430 "afterDelay", "inModes", NULL);
1431 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1432 "withObject", "waitUntilDone", NULL);
1433 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1434 "withObject", "waitUntilDone", "modes", NULL);
1435 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1436 "withObject", "waitUntilDone", NULL);
1437 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1438 "withObject", "waitUntilDone", "modes", NULL);
1439 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1440 "withObject", NULL);
Ted Kremenekdf100482009-05-14 21:29:16 +00001441
1442 // Specially handle NSData.
1443 RetainSummary *dataWithBytesNoCopySumm =
1444 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1445 DoNothing);
1446 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1447 "dataWithBytesNoCopy", "length", NULL);
1448 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1449 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001450}
1451
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001452void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001453
Ted Kremeneka56ae162009-05-03 05:20:50 +00001454 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001455
Ted Kremeneka7722b72008-05-06 21:26:51 +00001456 // Create the "init" selector. It just acts as a pass-through for the
1457 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001458 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
Ted Kremenek77bec862009-06-11 18:17:24 +00001459 getPersistentSummary(ObjCInitRetE, DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001460
1461 // The next methods are allocators.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001462 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001463
1464 // Create the "copy" selector.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001465 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001466
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001467 // Create the "mutableCopy" selector.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001468 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001469
Ted Kremenek266d8b62008-05-06 02:26:56 +00001470 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001471 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001472 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001473 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001474
1475 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001476 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001477 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001478
1479 // Create the "drain" selector.
1480 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001481 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001482
1483 // Create the -dealloc summary.
1484 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1485 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001486
1487 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001488 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001489 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001490
Ted Kremenekaac82832009-02-23 17:45:03 +00001491 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001492 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001493 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001494 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001495
Ted Kremenek45642a42008-08-12 18:48:50 +00001496 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001497 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1498 // self-own themselves. However, they only do this once they are displayed.
1499 // Thus, we need to track an NSWindow's display status.
1500 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001501 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001502 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1503 StopTracking,
1504 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001505
1506 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1507
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001508#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001509 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001510 "styleMask", "backing", "defer", NULL);
1511
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001512 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001513 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001514#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001515
Ted Kremenek45642a42008-08-12 18:48:50 +00001516 // For NSPanel (which subclasses NSWindow), allocated objects are not
1517 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001518 // FIXME: For now we don't track NSPanels. object for the same reason
1519 // as for NSWindow objects.
1520 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1521
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001522#if 0
1523 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001524 "styleMask", "backing", "defer", NULL);
1525
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001526 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001527 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001528#endif
Ted Kremenek88294222009-05-18 23:14:34 +00001529
1530 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1531 // exit a method.
1532 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek272aa852008-06-25 21:21:56 +00001533
Ted Kremenekf2717b02008-07-18 17:24:20 +00001534 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001535 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1536 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001537
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001538 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1539 "file", "lineNumber", "description", NULL);
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001540
1541 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1542 addInstMethSummary("QCRenderer", AllocSumm,
1543 "createSnapshotImageOfType", NULL);
1544 addInstMethSummary("QCView", AllocSumm,
1545 "createSnapshotImageOfType", NULL);
1546
Ted Kremenek054cd002009-06-15 20:58:58 +00001547 // Create summaries for CIContext, 'createCGImage' and
1548 // 'createCGLayerWithSize'.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001549 addInstMethSummary("CIContext", AllocSumm,
1550 "createCGImage", "fromRect", NULL);
1551 addInstMethSummary("CIContext", AllocSumm,
Ted Kremenek054cd002009-06-15 20:58:58 +00001552 "createCGImage", "fromRect", "format", "colorSpace", NULL);
1553 addInstMethSummary("CIContext", AllocSumm, "createCGLayerWithSize",
1554 "info", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001555}
1556
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001557//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001558// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001559//===----------------------------------------------------------------------===//
1560
Ted Kremeneka7338b42008-03-11 06:39:11 +00001561namespace {
1562
Ted Kremenek7d421f32008-04-09 23:49:11 +00001563class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001564public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001565 enum Kind {
1566 Owned = 0, // Owning reference.
1567 NotOwned, // Reference is not owned by still valid (not freed).
1568 Released, // Object has been released.
1569 ReturnedOwned, // Returned object passes ownership to caller.
1570 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001571 ERROR_START,
1572 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1573 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001574 ErrorUseAfterRelease, // Object used after released.
1575 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001576 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001577 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001578 ErrorLeakReturned, // A memory leak due to the returning method not having
1579 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001580 ErrorGCLeakReturned,
1581 ErrorOverAutorelease,
1582 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001583 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001584
1585private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001586 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001587 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001588 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001589 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001590 QualType T;
1591
Ted Kremenek4d99d342009-05-08 20:01:42 +00001592 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1593 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001594
Ted Kremenek68621b92009-01-28 05:56:51 +00001595 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001596 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001597
1598public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001599 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001600
1601 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001602
Ted Kremenek4d99d342009-05-08 20:01:42 +00001603 unsigned getCount() const { return Cnt; }
1604 unsigned getAutoreleaseCount() const { return ACnt; }
1605 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1606 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001607 void setCount(unsigned i) { Cnt = i; }
1608 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001609
Ted Kremenek272aa852008-06-25 21:21:56 +00001610 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001611
1612 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001613
Ted Kremenek6537a642009-03-17 19:42:23 +00001614 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001615
Ted Kremenek6537a642009-03-17 19:42:23 +00001616 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001617
Ted Kremenekffefc352008-04-11 22:25:11 +00001618 bool isOwned() const {
1619 return getKind() == Owned;
1620 }
1621
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001622 bool isNotOwned() const {
1623 return getKind() == NotOwned;
1624 }
1625
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001626 bool isReturnedOwned() const {
1627 return getKind() == ReturnedOwned;
1628 }
1629
1630 bool isReturnedNotOwned() const {
1631 return getKind() == ReturnedNotOwned;
1632 }
1633
1634 bool isNonLeakError() const {
1635 Kind k = getKind();
1636 return isError(k) && !isLeak(k);
1637 }
1638
Ted Kremenek68621b92009-01-28 05:56:51 +00001639 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1640 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001641 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001642 }
1643
Ted Kremenek68621b92009-01-28 05:56:51 +00001644 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1645 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001646 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001647 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001648
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001649 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001650
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001651 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001652 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001653 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001654
Ted Kremenek272aa852008-06-25 21:21:56 +00001655 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001656 return RefVal(getKind(), getObjKind(), getCount() - i,
1657 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001658 }
1659
1660 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001661 return RefVal(getKind(), getObjKind(), getCount() + i,
1662 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001663 }
1664
1665 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001666 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1667 getType());
1668 }
1669
1670 RefVal autorelease() const {
1671 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1672 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001673 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001674
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001675 void Profile(llvm::FoldingSetNodeID& ID) const {
1676 ID.AddInteger((unsigned) kind);
1677 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001678 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001679 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001680 }
1681
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001682 void print(llvm::raw_ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001683};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001684
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001685void RefVal::print(llvm::raw_ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001686 if (!T.isNull())
1687 Out << "Tracked Type:" << T.getAsString() << '\n';
1688
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001689 switch (getKind()) {
1690 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001691 case Owned: {
1692 Out << "Owned";
1693 unsigned cnt = getCount();
1694 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001695 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001696 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001697
Ted Kremenekc4f81022008-04-10 23:09:18 +00001698 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001699 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001700 unsigned cnt = getCount();
1701 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001702 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001703 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001704
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001705 case ReturnedOwned: {
1706 Out << "ReturnedOwned";
1707 unsigned cnt = getCount();
1708 if (cnt) Out << " (+ " << cnt << ")";
1709 break;
1710 }
1711
1712 case ReturnedNotOwned: {
1713 Out << "ReturnedNotOwned";
1714 unsigned cnt = getCount();
1715 if (cnt) Out << " (+ " << cnt << ")";
1716 break;
1717 }
1718
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001719 case Released:
1720 Out << "Released";
1721 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001722
1723 case ErrorDeallocGC:
1724 Out << "-dealloc (GC)";
1725 break;
1726
1727 case ErrorDeallocNotOwned:
1728 Out << "-dealloc (not-owned)";
1729 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001730
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001731 case ErrorLeak:
1732 Out << "Leaked";
1733 break;
1734
Ted Kremenek311f3d42008-10-22 23:56:21 +00001735 case ErrorLeakReturned:
1736 Out << "Leaked (Bad naming)";
1737 break;
1738
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001739 case ErrorGCLeakReturned:
1740 Out << "Leaked (GC-ed at return)";
1741 break;
1742
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001743 case ErrorUseAfterRelease:
1744 Out << "Use-After-Release [ERROR]";
1745 break;
1746
1747 case ErrorReleaseNotOwned:
1748 Out << "Release of Not-Owned [ERROR]";
1749 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001750
1751 case RefVal::ErrorOverAutorelease:
1752 Out << "Over autoreleased";
1753 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001754
1755 case RefVal::ErrorReturnedNotOwned:
1756 Out << "Non-owned object returned instead of owned";
1757 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001758 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001759
1760 if (ACnt) {
1761 Out << " [ARC +" << ACnt << ']';
1762 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001763}
Ted Kremenek0d721572008-03-11 17:48:22 +00001764
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001765} // end anonymous namespace
1766
1767//===----------------------------------------------------------------------===//
1768// RefBindings - State used to track object reference counts.
1769//===----------------------------------------------------------------------===//
1770
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001771typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001772static int RefBIndex = 0;
1773
1774namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001775 template<>
1776 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1777 static inline void* GDMIndex() { return &RefBIndex; }
1778 };
1779}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001780
1781//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001782// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001783//===----------------------------------------------------------------------===//
1784
Ted Kremenekb6578942009-02-24 19:15:11 +00001785typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1786typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1787typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001788
Ted Kremenekb6578942009-02-24 19:15:11 +00001789static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001790static int AutoRBIndex = 0;
1791
Ted Kremenekb6578942009-02-24 19:15:11 +00001792namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001793namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001794
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001795namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001796template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001797 : public GRStatePartialTrait<ARStack> {
1798 static inline void* GDMIndex() { return &AutoRBIndex; }
1799};
1800
1801template<> struct GRStateTrait<AutoreleasePoolContents>
1802 : public GRStatePartialTrait<ARPoolContents> {
1803 static inline void* GDMIndex() { return &AutoRCIndex; }
1804};
1805} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001806
Ted Kremenek681fb352009-03-20 17:34:15 +00001807static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1808 ARStack stack = state->get<AutoreleaseStack>();
1809 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1810}
1811
Ted Kremenek18a636d2009-06-18 01:23:53 +00001812static const GRState * SendAutorelease(const GRState *state,
1813 ARCounts::Factory &F, SymbolRef sym) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001814
1815 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenek18a636d2009-06-18 01:23:53 +00001816 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek681fb352009-03-20 17:34:15 +00001817 ARCounts newCnts(0);
1818
1819 if (cnts) {
1820 const unsigned *cnt = (*cnts).lookup(sym);
1821 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1822 }
1823 else
1824 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1825
Ted Kremenek18a636d2009-06-18 01:23:53 +00001826 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek681fb352009-03-20 17:34:15 +00001827}
1828
Ted Kremenek7aef4842008-04-16 20:40:59 +00001829//===----------------------------------------------------------------------===//
1830// Transfer functions.
1831//===----------------------------------------------------------------------===//
1832
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001833namespace {
1834
Ted Kremenekd1c53ff2009-06-26 00:05:51 +00001835class VISIBILITY_HIDDEN CFRefCount : public GRTransferFuncs {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001836public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001837 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001838 public:
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001839 virtual void Print(llvm::raw_ostream& Out, const GRState* state,
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001840 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001841 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001842
1843private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001844 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1845 SummaryLogTy;
1846
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001847 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001848 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001849 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001850 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001851
Ted Kremenek708af042009-02-05 06:50:21 +00001852 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001853 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001854 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001855 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001856 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001857 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001858
Ted Kremenek18a636d2009-06-18 01:23:53 +00001859 const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenekb6578942009-02-24 19:15:11 +00001860 RefVal::Kind& hasErr);
1861
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001862 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1863 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001864 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001865 ExplodedNode<GRState>* Pred,
1866 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001867 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001868
Ted Kremenek18a636d2009-06-18 01:23:53 +00001869 const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001870 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1871
Ted Kremenek18a636d2009-06-18 01:23:53 +00001872 ExplodedNode<GRState>* ProcessLeaks(const GRState * state,
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001873 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1874 GenericNodeBuilder &Builder,
1875 GRExprEngine &Eng,
1876 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001877
Ted Kremenekb6578942009-02-24 19:15:11 +00001878public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001879 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001880 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001881 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1882 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001883 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1884 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001885
Ted Kremenek708af042009-02-05 06:50:21 +00001886 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001887
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001888 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001889
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001890 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1891 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001892 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001893
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001894 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001895 const LangOptions& getLangOptions() const { return LOpts; }
1896
Ted Kremenekc26c4692009-02-18 03:48:14 +00001897 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1898 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1899 return I == SummaryLog.end() ? 0 : I->second;
1900 }
1901
Ted Kremeneka7338b42008-03-11 06:39:11 +00001902 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001903
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001904 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001905 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001906 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001907 Expr* Ex,
1908 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001909 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001910 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001911 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001912
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001913 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001914 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001915 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001916 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001917 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001918
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001919
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001920 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001921 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001922 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001923 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001924 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001925
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001926 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001927 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001928 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001929 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001930 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001931
Ted Kremeneka42be302009-02-14 01:43:44 +00001932 // Stores.
1933 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1934
Ted Kremenekffefc352008-04-11 22:25:11 +00001935 // End-of-path.
1936
1937 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001938 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001939
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001940 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001941 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001942 GRStmtNodeBuilder<GRState>& Builder,
1943 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001944 Stmt* S, const GRState* state,
1945 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001946
Ted Kremenek18a636d2009-06-18 01:23:53 +00001947 std::pair<ExplodedNode<GRState>*, const GRState *>
1948 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001949 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1950 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001951 // Return statements.
1952
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001953 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001954 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001955 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001956 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001957 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001958
1959 // Assumptions.
1960
Ted Kremenek70970bf2009-06-18 22:57:13 +00001961 virtual const GRState *EvalAssume(const GRState* state, SVal condition,
1962 bool assumption);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001963};
1964
1965} // end anonymous namespace
1966
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001967static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym,
1968 const GRState *state) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001969 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001970 if (Sym)
1971 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001972 else
1973 Out << "<pool>";
1974 Out << ":{";
1975
1976 // Get the contents of the pool.
1977 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1978 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1979 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1980
1981 Out << '}';
1982}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001983
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001984void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out,
1985 const GRState* state,
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001986 const char* nl, const char* sep) {
1987
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001988 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001989
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001990 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001991 Out << sep << nl;
1992
1993 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1994 Out << (*I).first << " : ";
1995 (*I).second.print(Out);
1996 Out << nl;
1997 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001998
1999 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00002000 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00002001 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00002002
Ted Kremenek681fb352009-03-20 17:34:15 +00002003 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
2004 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
2005 PrintPool(Out, *I, state);
2006
2007 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00002008}
2009
Ted Kremenek47a72422009-04-29 18:50:19 +00002010//===----------------------------------------------------------------------===//
2011// Error reporting.
2012//===----------------------------------------------------------------------===//
2013
2014namespace {
2015
2016 //===-------------===//
2017 // Bug Descriptions. //
2018 //===-------------===//
2019
2020 class VISIBILITY_HIDDEN CFRefBug : public BugType {
2021 protected:
2022 CFRefCount& TF;
2023
2024 CFRefBug(CFRefCount* tf, const char* name)
2025 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
2026 public:
2027
2028 CFRefCount& getTF() { return TF; }
2029 const CFRefCount& getTF() const { return TF; }
2030
2031 // FIXME: Eventually remove.
2032 virtual const char* getDescription() const = 0;
2033
2034 virtual bool isLeak() const { return false; }
2035 };
2036
2037 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2038 public:
2039 UseAfterRelease(CFRefCount* tf)
2040 : CFRefBug(tf, "Use-after-release") {}
2041
2042 const char* getDescription() const {
2043 return "Reference-counted object is used after it is released";
2044 }
2045 };
2046
2047 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2048 public:
2049 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
2050
2051 const char* getDescription() const {
2052 return "Incorrect decrement of the reference count of an "
2053 "object is not owned at this point by the caller";
2054 }
2055 };
2056
2057 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2058 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002059 DeallocGC(CFRefCount *tf)
2060 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002061
2062 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002063 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00002064 }
2065 };
2066
2067 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2068 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002069 DeallocNotOwned(CFRefCount *tf)
2070 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002071
2072 const char *getDescription() const {
2073 return "-dealloc sent to object that may be referenced elsewhere";
2074 }
2075 };
2076
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002077 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
2078 public:
2079 OverAutorelease(CFRefCount *tf) :
2080 CFRefBug(tf, "Object sent -autorelease too many times") {}
2081
2082 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00002083 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002084 }
2085 };
2086
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002087 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
2088 public:
2089 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2090 CFRefBug(tf, "Method should return an owned object") {}
2091
2092 const char *getDescription() const {
2093 return "Object with +0 retain counts returned to caller where a +1 "
2094 "(owning) retain count is expected";
2095 }
2096 };
2097
Ted Kremenek47a72422009-04-29 18:50:19 +00002098 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2099 const bool isReturn;
2100 protected:
2101 Leak(CFRefCount* tf, const char* name, bool isRet)
2102 : CFRefBug(tf, name), isReturn(isRet) {}
2103 public:
2104
2105 const char* getDescription() const { return ""; }
2106
2107 bool isLeak() const { return true; }
2108 };
2109
2110 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2111 public:
2112 LeakAtReturn(CFRefCount* tf, const char* name)
2113 : Leak(tf, name, true) {}
2114 };
2115
2116 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2117 public:
2118 LeakWithinFunction(CFRefCount* tf, const char* name)
2119 : Leak(tf, name, false) {}
2120 };
2121
2122 //===---------===//
2123 // Bug Reports. //
2124 //===---------===//
2125
2126 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2127 protected:
2128 SymbolRef Sym;
2129 const CFRefCount &TF;
2130 public:
2131 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2132 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002133 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2134
2135 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2136 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002137 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002138
2139 virtual ~CFRefReport() {}
2140
2141 CFRefBug& getBugType() {
2142 return (CFRefBug&) RangedBugReport::getBugType();
2143 }
2144 const CFRefBug& getBugType() const {
2145 return (const CFRefBug&) RangedBugReport::getBugType();
2146 }
2147
2148 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2149 const SourceRange*& end) {
2150
2151 if (!getBugType().isLeak())
2152 RangedBugReport::getRanges(BR, beg, end);
2153 else
2154 beg = end = 0;
2155 }
2156
2157 SymbolRef getSymbol() const { return Sym; }
2158
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002159 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002160 const ExplodedNode<GRState>* N);
2161
2162 std::pair<const char**,const char**> getExtraDescriptiveText();
2163
2164 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2165 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002166 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002167 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002168
Ted Kremenek47a72422009-04-29 18:50:19 +00002169 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2170 SourceLocation AllocSite;
2171 const MemRegion* AllocBinding;
2172 public:
2173 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2174 ExplodedNode<GRState> *n, SymbolRef sym,
2175 GRExprEngine& Eng);
2176
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002177 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002178 const ExplodedNode<GRState>* N);
2179
2180 SourceLocation getLocation() const { return AllocSite; }
2181 };
2182} // end anonymous namespace
2183
2184void CFRefCount::RegisterChecks(BugReporter& BR) {
2185 useAfterRelease = new UseAfterRelease(this);
2186 BR.Register(useAfterRelease);
2187
2188 releaseNotOwned = new BadRelease(this);
2189 BR.Register(releaseNotOwned);
2190
2191 deallocGC = new DeallocGC(this);
2192 BR.Register(deallocGC);
2193
2194 deallocNotOwned = new DeallocNotOwned(this);
2195 BR.Register(deallocNotOwned);
2196
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002197 overAutorelease = new OverAutorelease(this);
2198 BR.Register(overAutorelease);
2199
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002200 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2201 BR.Register(returnNotOwnedForOwned);
2202
Ted Kremenek47a72422009-04-29 18:50:19 +00002203 // First register "return" leaks.
2204 const char* name = 0;
2205
2206 if (isGCEnabled())
2207 name = "Leak of returned object when using garbage collection";
2208 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2209 name = "Leak of returned object when not using garbage collection (GC) in "
2210 "dual GC/non-GC code";
2211 else {
2212 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2213 name = "Leak of returned object";
2214 }
2215
2216 leakAtReturn = new LeakAtReturn(this, name);
2217 BR.Register(leakAtReturn);
2218
2219 // Second, register leaks within a function/method.
2220 if (isGCEnabled())
2221 name = "Leak of object when using garbage collection";
2222 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2223 name = "Leak of object when not using garbage collection (GC) in "
2224 "dual GC/non-GC code";
2225 else {
2226 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2227 name = "Leak";
2228 }
2229
2230 leakWithinFunction = new LeakWithinFunction(this, name);
2231 BR.Register(leakWithinFunction);
2232
2233 // Save the reference to the BugReporter.
2234 this->BR = &BR;
2235}
2236
2237static const char* Msgs[] = {
2238 // GC only
2239 "Code is compiled to only use garbage collection",
2240 // No GC.
2241 "Code is compiled to use reference counts",
2242 // Hybrid, with GC.
2243 "Code is compiled to use either garbage collection (GC) or reference counts"
2244 " (non-GC). The bug occurs with GC enabled",
2245 // Hybrid, without GC
2246 "Code is compiled to use either garbage collection (GC) or reference counts"
2247 " (non-GC). The bug occurs in non-GC mode"
2248};
2249
2250std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2251 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2252
2253 switch (TF.getLangOptions().getGCMode()) {
2254 default:
2255 assert(false);
2256
2257 case LangOptions::GCOnly:
2258 assert (TF.isGCEnabled());
2259 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2260
2261 case LangOptions::NonGC:
2262 assert (!TF.isGCEnabled());
2263 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2264
2265 case LangOptions::HybridGC:
2266 if (TF.isGCEnabled())
2267 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2268 else
2269 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2270 }
2271}
2272
2273static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2274 ArgEffect X) {
2275 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2276 I!=E; ++I)
2277 if (*I == X) return true;
2278
2279 return false;
2280}
2281
2282PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2283 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002284 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002285
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002286 if (!isa<PostStmt>(N->getLocation()))
2287 return NULL;
2288
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002289 // Check if the type state has changed.
Ted Kremenek18a636d2009-06-18 01:23:53 +00002290 const GRState *PrevSt = PrevN->getState();
2291 const GRState *CurrSt = N->getState();
Ted Kremenek47a72422009-04-29 18:50:19 +00002292
Ted Kremenek18a636d2009-06-18 01:23:53 +00002293 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002294 if (!CurrT) return NULL;
2295
Ted Kremenek18a636d2009-06-18 01:23:53 +00002296 const RefVal &CurrV = *CurrT;
2297 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002298
2299 // Create a string buffer to constain all the useful things we want
2300 // to tell the user.
2301 std::string sbuf;
2302 llvm::raw_string_ostream os(sbuf);
2303
2304 // This is the allocation site since the previous node had no bindings
2305 // for this symbol.
2306 if (!PrevT) {
2307 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2308
2309 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2310 // Get the name of the callee (if it is available).
Ted Kremenek18a636d2009-06-18 01:23:53 +00002311 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek47a72422009-04-29 18:50:19 +00002312 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2313 os << "Call to function '" << FD->getNameAsString() <<'\'';
2314 else
2315 os << "function call";
2316 }
2317 else {
2318 assert (isa<ObjCMessageExpr>(S));
2319 os << "Method";
2320 }
2321
2322 if (CurrV.getObjKind() == RetEffect::CF) {
2323 os << " returns a Core Foundation object with a ";
2324 }
2325 else {
2326 assert (CurrV.getObjKind() == RetEffect::ObjC);
2327 os << " returns an Objective-C object with a ";
2328 }
2329
2330 if (CurrV.isOwned()) {
2331 os << "+1 retain count (owning reference).";
2332
2333 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2334 assert(CurrV.getObjKind() == RetEffect::CF);
2335 os << " "
2336 "Core Foundation objects are not automatically garbage collected.";
2337 }
2338 }
2339 else {
2340 assert (CurrV.isNotOwned());
2341 os << "+0 retain count (non-owning reference).";
2342 }
2343
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002344 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002345 return new PathDiagnosticEventPiece(Pos, os.str());
2346 }
2347
2348 // Gather up the effects that were performed on the object at this
2349 // program point
2350 llvm::SmallVector<ArgEffect, 2> AEffects;
2351
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002352 if (const RetainSummary *Summ =
2353 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002354 // We only have summaries attached to nodes after evaluating CallExpr and
2355 // ObjCMessageExprs.
2356 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2357
2358 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2359 // Iterate through the parameter expressions and see if the symbol
2360 // was ever passed as an argument.
2361 unsigned i = 0;
2362
2363 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2364 AI!=AE; ++AI, ++i) {
2365
2366 // Retrieve the value of the argument. Is it the symbol
2367 // we are interested in?
Ted Kremenek18a636d2009-06-18 01:23:53 +00002368 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenek47a72422009-04-29 18:50:19 +00002369 continue;
2370
2371 // We have an argument. Get the effect!
2372 AEffects.push_back(Summ->getArg(i));
2373 }
2374 }
2375 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2376 if (Expr *receiver = ME->getReceiver())
Ted Kremenek18a636d2009-06-18 01:23:53 +00002377 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002378 // The symbol we are tracking is the receiver.
2379 AEffects.push_back(Summ->getReceiverEffect());
2380 }
2381 }
2382 }
2383
2384 do {
2385 // Get the previous type state.
2386 RefVal PrevV = *PrevT;
2387
2388 // Specially handle -dealloc.
2389 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2390 // Determine if the object's reference count was pushed to zero.
2391 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2392 // We may not have transitioned to 'release' if we hit an error.
2393 // This case is handled elsewhere.
2394 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002395 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002396 os << "Object released by directly sending the '-dealloc' message";
2397 break;
2398 }
2399 }
2400
2401 // Specially handle CFMakeCollectable and friends.
2402 if (contains(AEffects, MakeCollectable)) {
2403 // Get the name of the function.
2404 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek18a636d2009-06-18 01:23:53 +00002405 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
Ted Kremenek47a72422009-04-29 18:50:19 +00002406 const FunctionDecl* FD = X.getAsFunctionDecl();
2407 const std::string& FName = FD->getNameAsString();
2408
2409 if (TF.isGCEnabled()) {
2410 // Determine if the object's reference count was pushed to zero.
2411 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2412
2413 os << "In GC mode a call to '" << FName
2414 << "' decrements an object's retain count and registers the "
2415 "object with the garbage collector. ";
2416
2417 if (CurrV.getKind() == RefVal::Released) {
2418 assert(CurrV.getCount() == 0);
2419 os << "Since it now has a 0 retain count the object can be "
2420 "automatically collected by the garbage collector.";
2421 }
2422 else
2423 os << "An object must have a 0 retain count to be garbage collected. "
2424 "After this call its retain count is +" << CurrV.getCount()
2425 << '.';
2426 }
2427 else
2428 os << "When GC is not enabled a call to '" << FName
2429 << "' has no effect on its argument.";
2430
2431 // Nothing more to say.
2432 break;
2433 }
2434
2435 // Determine if the typestate has changed.
2436 if (!(PrevV == CurrV))
2437 switch (CurrV.getKind()) {
2438 case RefVal::Owned:
2439 case RefVal::NotOwned:
2440
Ted Kremenek4d99d342009-05-08 20:01:42 +00002441 if (PrevV.getCount() == CurrV.getCount()) {
2442 // Did an autorelease message get sent?
2443 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2444 return 0;
2445
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002446 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002447 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002448 break;
2449 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002450
2451 if (PrevV.getCount() > CurrV.getCount())
2452 os << "Reference count decremented.";
2453 else
2454 os << "Reference count incremented.";
2455
2456 if (unsigned Count = CurrV.getCount())
2457 os << " The object now has a +" << Count << " retain count.";
2458
2459 if (PrevV.getKind() == RefVal::Released) {
2460 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2461 os << " The object is not eligible for garbage collection until the "
2462 "retain count reaches 0 again.";
2463 }
2464
2465 break;
2466
2467 case RefVal::Released:
2468 os << "Object released.";
2469 break;
2470
2471 case RefVal::ReturnedOwned:
2472 os << "Object returned to caller as an owning reference (single retain "
2473 "count transferred to caller).";
2474 break;
2475
2476 case RefVal::ReturnedNotOwned:
2477 os << "Object returned to caller with a +0 (non-owning) retain count.";
2478 break;
2479
2480 default:
2481 return NULL;
2482 }
2483
2484 // Emit any remaining diagnostics for the argument effects (if any).
2485 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2486 E=AEffects.end(); I != E; ++I) {
2487
2488 // A bunch of things have alternate behavior under GC.
2489 if (TF.isGCEnabled())
2490 switch (*I) {
2491 default: break;
2492 case Autorelease:
2493 os << "In GC mode an 'autorelease' has no effect.";
2494 continue;
2495 case IncRefMsg:
2496 os << "In GC mode the 'retain' message has no effect.";
2497 continue;
2498 case DecRefMsg:
2499 os << "In GC mode the 'release' message has no effect.";
2500 continue;
2501 }
2502 }
2503 } while(0);
2504
2505 if (os.str().empty())
2506 return 0; // We have nothing to say!
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002507
2508 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002509 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002510 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2511
2512 // Add the range by scanning the children of the statement for any bindings
2513 // to Sym.
2514 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2515 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek18a636d2009-06-18 01:23:53 +00002516 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002517 P->addRange(Exp->getSourceRange());
2518 break;
2519 }
2520
2521 return P;
2522}
2523
2524namespace {
2525 class VISIBILITY_HIDDEN FindUniqueBinding :
2526 public StoreManager::BindingsHandler {
2527 SymbolRef Sym;
2528 const MemRegion* Binding;
2529 bool First;
2530
2531 public:
2532 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2533
2534 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2535 SVal val) {
2536
2537 SymbolRef SymV = val.getAsSymbol();
2538 if (!SymV || SymV != Sym)
2539 return true;
2540
2541 if (Binding) {
2542 First = false;
2543 return false;
2544 }
2545 else
2546 Binding = R;
2547
2548 return true;
2549 }
2550
2551 operator bool() { return First && Binding; }
2552 const MemRegion* getRegion() { return Binding; }
2553 };
2554}
2555
2556static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2557GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2558 SymbolRef Sym) {
2559
2560 // Find both first node that referred to the tracked symbol and the
2561 // memory location that value was store to.
2562 const ExplodedNode<GRState>* Last = N;
2563 const MemRegion* FirstBinding = 0;
2564
2565 while (N) {
2566 const GRState* St = N->getState();
2567 RefBindings B = St->get<RefBindings>();
2568
2569 if (!B.lookup(Sym))
2570 break;
2571
2572 FindUniqueBinding FB(Sym);
2573 StateMgr.iterBindings(St, FB);
2574 if (FB) FirstBinding = FB.getRegion();
2575
2576 Last = N;
2577 N = N->pred_empty() ? NULL : *(N->pred_begin());
2578 }
2579
2580 return std::make_pair(Last, FirstBinding);
2581}
2582
2583PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002584CFRefReport::getEndPath(BugReporterContext& BRC,
2585 const ExplodedNode<GRState>* EndN) {
2586 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002587 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002588 BRC.addNotableSymbol(Sym);
2589 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002590}
2591
2592PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002593CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2594 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002595
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002596 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002597 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002598 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002599
2600 // We are reporting a leak. Walk up the graph to get to the first node where
2601 // the symbol appeared, and also get the first VarDecl that tracked object
2602 // is stored to.
2603 const ExplodedNode<GRState>* AllocNode = 0;
2604 const MemRegion* FirstBinding = 0;
2605
2606 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002607 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002608
2609 // Get the allocate site.
2610 assert(AllocNode);
2611 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2612
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002613 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002614 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2615
2616 // Compute an actual location for the leak. Sometimes a leak doesn't
2617 // occur at an actual statement (e.g., transition between blocks; end
2618 // of function) so we need to walk the graph and compute a real location.
2619 const ExplodedNode<GRState>* LeakN = EndN;
2620 PathDiagnosticLocation L;
2621
2622 while (LeakN) {
2623 ProgramPoint P = LeakN->getLocation();
2624
2625 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2626 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2627 break;
2628 }
2629 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2630 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2631 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2632 break;
2633 }
2634 }
2635
2636 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2637 }
2638
2639 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002640 const Decl &D = BRC.getCodeDecl();
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002641 L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002642 }
2643
2644 std::string sbuf;
2645 llvm::raw_string_ostream os(sbuf);
2646
2647 os << "Object allocated on line " << AllocLine;
2648
2649 if (FirstBinding)
2650 os << " and stored into '" << FirstBinding->getString() << '\'';
2651
2652 // Get the retain count.
2653 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2654
2655 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2656 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2657 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2658 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002659 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002660 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002661 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002662 << "') does not contain 'copy' or otherwise starts with"
2663 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002664 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002665 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002666 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2667 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2668 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002669 << "' is potentially leaked when using garbage collection. Callers "
2670 "of this method do not expect a returned object with a +1 retain "
2671 "count since they expect the object to be managed by the garbage "
2672 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002673 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002674 else
2675 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002676 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002677
2678 return new PathDiagnosticEventPiece(L, os.str());
2679}
2680
Ted Kremenek47a72422009-04-29 18:50:19 +00002681CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2682 ExplodedNode<GRState> *n,
2683 SymbolRef sym, GRExprEngine& Eng)
2684: CFRefReport(D, tf, n, sym)
2685{
2686
2687 // Most bug reports are cached at the location where they occured.
2688 // With leaks, we want to unique them by the location where they were
2689 // allocated, and only report a single path. To do this, we need to find
2690 // the allocation site of a piece of tracked memory, which we do via a
2691 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2692 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2693 // that all ancestor nodes that represent the allocation site have the
2694 // same SourceLocation.
2695 const ExplodedNode<GRState>* AllocNode = 0;
2696
2697 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002698 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002699
2700 // Get the SourceLocation for the allocation site.
2701 ProgramPoint P = AllocNode->getLocation();
2702 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2703
2704 // Fill in the description of the bug.
2705 Description.clear();
2706 llvm::raw_string_ostream os(Description);
2707 SourceManager& SMgr = Eng.getContext().getSourceManager();
2708 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002709 os << "Potential leak ";
2710 if (tf.isGCEnabled()) {
2711 os << "(when using garbage collection) ";
2712 }
2713 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002714
2715 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2716 if (AllocBinding)
2717 os << " and stored into '" << AllocBinding->getString() << '\'';
2718}
2719
2720//===----------------------------------------------------------------------===//
2721// Main checker logic.
2722//===----------------------------------------------------------------------===//
2723
Ted Kremenek272aa852008-06-25 21:21:56 +00002724/// GetReturnType - Used to get the return type of a message expression or
2725/// function call with the intention of affixing that type to a tracked symbol.
2726/// While the the return type can be queried directly from RetEx, when
2727/// invoking class methods we augment to the return type to be that of
2728/// a pointer to the class (as opposed it just being id).
2729static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2730
2731 QualType RetTy = RetE->getType();
2732
2733 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002734 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002735 if (!PT)
2736 return RetTy;
2737
2738 // If RetEx is not a message expression just return its type.
2739 // If RetEx is a message expression, return its types if it is something
2740 /// more specific than id.
2741
2742 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2743
Steve Naroff17c03822009-02-12 17:52:19 +00002744 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002745 return RetTy;
2746
2747 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2748
2749 // At this point we know the return type of the message expression is id.
2750 // If we have an ObjCInterceDecl, we know this is a call to a class method
2751 // whose type we can resolve. In such cases, promote the return type to
2752 // Class*.
2753 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2754}
2755
2756
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002757void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002758 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002759 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002760 Expr* Ex,
2761 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002762 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002763 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002764 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002765
Ted Kremeneka7338b42008-03-11 06:39:11 +00002766 // Get the state.
Ted Kremenek18a636d2009-06-18 01:23:53 +00002767 const GRState *state = Builder.GetState(Pred);
Ted Kremenek227c5372008-05-06 02:41:27 +00002768
2769 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002770 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002771 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002772 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002773 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002774
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002775 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek18a636d2009-06-18 01:23:53 +00002776 SVal V = state->getSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002777 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002778
Ted Kremenek74556a12009-03-26 03:35:11 +00002779 if (Sym)
Ted Kremenek18a636d2009-06-18 01:23:53 +00002780 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002781 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002782 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002783 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002784 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002785 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002786 }
2787 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002788 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002789
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002790 if (isa<Loc>(V)) {
2791 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002792 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002793 continue;
2794
Ted Kremenekd1c53ff2009-06-26 00:05:51 +00002795 // Invalidate the value of the variable passed by reference.
Ted Kremenekede40b72008-07-09 18:11:16 +00002796
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002797 // FIXME: We can have collisions on the conjured symbol if the
2798 // expression *I also creates conjured symbols. We probably want
2799 // to identify conjured symbols by an expression pair: the enclosing
2800 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002801 // disambiguate conjured symbols.
Zhongxing Xud2d938c2009-06-29 06:43:40 +00002802 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002803 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
Ted Kremenek1cba5772009-05-11 22:55:17 +00002804
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002805 const MemRegion *R = MR->getRegion();
2806 // Are we dealing with an ElementRegion? If the element type is
2807 // a basic integer type (e.g., char, int) and the underying region
2808 // is a variable region then strip off the ElementRegion.
2809 // FIXME: We really need to think about this for the general case
2810 // as sometimes we are reasoning about arrays and other times
2811 // about (char*), etc., is just a form of passing raw bytes.
2812 // e.g., void *p = alloca(); foo((char*)p);
2813 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2814 // Checking for 'integral type' is probably too promiscuous, but
2815 // we'll leave it in for now until we have a systematic way of
2816 // handling all of these cases. Eventually we need to come up
2817 // with an interface to StoreManager so that this logic can be
2818 // approriately delegated to the respective StoreManagers while
2819 // still allowing us to do checker-specific logic (e.g.,
2820 // invalidating reference counts), probably via callbacks.
2821 if (ER->getElementType()->isIntegralType()) {
2822 const MemRegion *superReg = ER->getSuperRegion();
2823 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2824 isa<ObjCIvarRegion>(superReg))
2825 R = cast<TypedRegion>(superReg);
Ted Kremenek73ec7732009-05-06 18:19:24 +00002826 }
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002827 // FIXME: What about layers of ElementRegions?
2828 }
Zhongxing Xud2d938c2009-06-29 06:43:40 +00002829
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002830 // Is the invalidated variable something that we were tracking?
2831 SymbolRef Sym = state->getSValAsScalarOrLoc(R).getAsLocSymbol();
2832
2833 // Remove any existing reference-count binding.
2834 if (Sym)
2835 state = state->remove<RefBindings>(Sym);
2836
2837 state = StoreMgr.InvalidateRegion(state, R, *I, Count);
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002838 }
2839 else {
2840 // Nuke all other arguments passed by reference.
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002841 // FIXME: is this necessary or correct? unbind only removes the binding.
2842 // We should bind it to UnknownVal explicitly. Otherwise default value
2843 // may be loaded.
Ted Kremenek18a636d2009-06-18 01:23:53 +00002844 state = state->unbindLoc(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002845 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002846 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002847 else if (isa<nonloc::LocAsInteger>(V))
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002848 // FIXME: is this necessary or correct? unbind only removes the binding.
2849 // We should bind it to UnknownVal explicitly. Otherwise default value
2850 // may be loaded.
Ted Kremenek18a636d2009-06-18 01:23:53 +00002851 state = state->unbindLoc(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002852 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002853
Ted Kremenek272aa852008-06-25 21:21:56 +00002854 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002855 if (!ErrorExpr && Receiver) {
Ted Kremenek18a636d2009-06-18 01:23:53 +00002856 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002857 if (Sym) {
Ted Kremenek18a636d2009-06-18 01:23:53 +00002858 if (const RefVal* T = state->get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002859 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002860 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002861 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002862 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002863 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002864 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002865 }
2866 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002867
Ted Kremenek272aa852008-06-25 21:21:56 +00002868 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002869 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002870 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002871 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002872 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002873 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002874
Ted Kremenekf2717b02008-07-18 17:24:20 +00002875 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002876 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002877
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002878 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2879 assert(Receiver);
Ted Kremenek18a636d2009-06-18 01:23:53 +00002880 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002881 bool found = false;
2882 if (SymbolRef Sym = V.getAsLocSymbol())
Ted Kremenek18a636d2009-06-18 01:23:53 +00002883 if (state->get<RefBindings>(Sym)) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002884 found = true;
2885 RE = Summaries.getObjAllocRetEffect();
2886 }
2887
2888 if (!found)
2889 RE = RetEffect::MakeNoRet();
2890 }
2891
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002892 switch (RE.getKind()) {
2893 default:
2894 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002895
Ted Kremenekd1c53ff2009-06-26 00:05:51 +00002896 case RetEffect::NoRet: {
Ted Kremenek455dd862008-04-11 20:23:24 +00002897 // Make up a symbol for the return value (not reference counted).
Ted Kremenekd1c53ff2009-06-26 00:05:51 +00002898 // FIXME: Most of this logic is not specific to the retain/release
2899 // checker.
Ted Kremenek455dd862008-04-11 20:23:24 +00002900
Ted Kremenek8f90e712008-10-17 22:23:12 +00002901 // FIXME: We eventually should handle structs and other compound types
2902 // that are returned by value.
2903
2904 QualType T = Ex->getType();
2905
Ted Kremenek79413a52008-11-13 06:10:40 +00002906 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002907 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002908 ValueManager &ValMgr = Eng.getValueManager();
2909 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek18a636d2009-06-18 01:23:53 +00002910 state = state->bindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002911 }
2912
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002913 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002914 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002915
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002916 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002917 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002918 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002919 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek18a636d2009-06-18 01:23:53 +00002920 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
2921 state = state->bindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002922 break;
2923 }
2924
Ted Kremenek227c5372008-05-06 02:41:27 +00002925 case RetEffect::ReceiverAlias: {
2926 assert (Receiver);
Ted Kremenek18a636d2009-06-18 01:23:53 +00002927 SVal V = state->getSValAsScalarOrLoc(Receiver);
2928 state = state->bindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002929 break;
2930 }
2931
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002932 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002933 case RetEffect::OwnedSymbol: {
2934 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002935 ValueManager &ValMgr = Eng.getValueManager();
2936 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2937 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenek18a636d2009-06-18 01:23:53 +00002938 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002939 RetT));
Zhongxing Xue32c7652009-06-23 09:02:15 +00002940 state = state->bindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002941
2942 // FIXME: Add a flag to the checker where allocations are assumed to
2943 // *not fail.
2944#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002945 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2946 bool isFeasible;
2947 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2948 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2949 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002950#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002951
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002952 break;
2953 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002954
2955 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002956 case RetEffect::NotOwnedSymbol: {
2957 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002958 ValueManager &ValMgr = Eng.getValueManager();
2959 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2960 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenek18a636d2009-06-18 01:23:53 +00002961 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002962 RetT));
Zhongxing Xue32c7652009-06-23 09:02:15 +00002963 state = state->bindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002964 break;
2965 }
2966 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002967
Ted Kremenek0dd65012009-02-18 02:00:25 +00002968 // Generate a sink node if we are at the end of a path.
2969 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002970 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2971 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002972
2973 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002974 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002975}
2976
2977
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002978void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002979 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002980 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002981 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002982 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002983 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002984 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002985 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002986
Ted Kremenek286e9852009-05-04 04:57:00 +00002987 assert(Summ);
2988 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002989 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002990}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002991
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002992void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002993 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002994 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002995 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002996 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002997 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002998
Ted Kremenek272aa852008-06-25 21:21:56 +00002999 if (Expr* Receiver = ME->getReceiver()) {
3000 // We need the type-information of the tracked receiver object
3001 // Retrieve it from the state.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00003002 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek272aa852008-06-25 21:21:56 +00003003
3004 // FIXME: Wouldn't it be great if this code could be reduced? It's just
3005 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00003006 // FIXME: Is this really working as expected? There are cases where
3007 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003008 const GRState* St = Builder.GetState(Pred);
Ted Kremenekc0cccca2009-06-18 23:58:37 +00003009 SVal V = St->getSValAsScalarOrLoc(Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00003010
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003011 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00003012 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003013 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00003014 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00003015
3016 if (const PointerType* PT = Ty->getAsPointerType()) {
3017 QualType PointeeTy = PT->getPointeeType();
3018
3019 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
3020 ID = IT->getDecl();
3021 }
3022 }
3023 }
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00003024
3025 // FIXME: this is a hack. This may or may not be the actual method
3026 // that is called.
3027 if (!ID) {
3028 if (const PointerType *PT = Receiver->getType()->getAsPointerType())
3029 if (const ObjCInterfaceType *p =
3030 PT->getPointeeType()->getAsObjCInterfaceType())
3031 ID = p->getDecl();
3032 }
3033
Ted Kremenek04e00302009-04-29 17:09:14 +00003034 // FIXME: The receiver could be a reference to a class, meaning that
3035 // we should use the class method.
3036 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00003037
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003038 // Special-case: are we sending a mesage to "self"?
3039 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00003040 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
3041 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekc0cccca2009-06-18 23:58:37 +00003042 SVal X = St->getSValAsScalarOrLoc(Receiver);
Ted Kremenek2f226732009-05-04 05:31:22 +00003043 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf6f0a872009-06-23 21:37:46 +00003044 if (L->getRegion() == St->getSelfRegion()) {
Ted Kremenek2f226732009-05-04 05:31:22 +00003045 // Update the summary to make the default argument effect
3046 // 'StopTracking'.
3047 Summ = Summaries.copySummary(Summ);
3048 Summ->setDefaultArgEffect(StopTracking);
3049 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003050 }
3051 }
Ted Kremenek272aa852008-06-25 21:21:56 +00003052 }
Ted Kremenek1feab292008-04-16 04:28:53 +00003053 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00003054 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00003055
Ted Kremenek286e9852009-05-04 04:57:00 +00003056 if (!Summ)
3057 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00003058
Ted Kremenek286e9852009-05-04 04:57:00 +00003059 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00003060 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00003061}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003062
3063namespace {
3064class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003065 const GRState *state;
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003066public:
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003067 StopTrackingCallback(const GRState *st) : state(st) {}
3068 const GRState *getState() const { return state; }
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003069
3070 bool VisitSymbol(SymbolRef sym) {
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003071 state = state->remove<RefBindings>(sym);
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003072 return true;
3073 }
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003074};
3075} // end anonymous namespace
3076
3077
Ted Kremeneka42be302009-02-14 01:43:44 +00003078void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00003079 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00003080 bool escapes = false;
3081
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003082 // A value escapes in three possible cases (this may change):
3083 //
3084 // (1) we are binding to something that is not a memory region.
3085 // (2) we are binding to a memregion that does not have stack storage
3086 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003087 // does not understand.
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003088 const GRState *state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003089
Ted Kremeneka42be302009-02-14 01:43:44 +00003090 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003091 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003092 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003093 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
Ted Kremenekdd2ec492009-06-23 18:05:21 +00003094 escapes = !R->hasStackStorage();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003095
3096 if (!escapes) {
3097 // To test (3), generate a new state with the binding removed. If it is
3098 // the same state, then it escapes (since the store cannot represent
3099 // the binding).
Ted Kremenek18a636d2009-06-18 01:23:53 +00003100 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003101 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003102 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003103
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003104 // If our store can represent the binding and we aren't storing to something
3105 // that doesn't have local storage then just return and have the simulation
3106 // state continue as is.
3107 if (!escapes)
3108 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003109
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003110 // Otherwise, find all symbols referenced by 'val' that we are tracking
3111 // and stop tracking them.
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003112 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003113}
3114
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003115 // Return statements.
3116
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003117void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003118 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003119 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003120 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003121 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003122
3123 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003124 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003125 return;
3126
Ted Kremenek18a636d2009-06-18 01:23:53 +00003127 const GRState *state = Builder.GetState(Pred);
3128 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003129
Ted Kremenek74556a12009-03-26 03:35:11 +00003130 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003131 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003132
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003133 // Get the reference count binding (if any).
Ted Kremenek18a636d2009-06-18 01:23:53 +00003134 const RefVal* T = state->get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003135
3136 if (!T)
3137 return;
3138
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003139 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003140 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003141
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003142 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003143 case RefVal::Owned: {
3144 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003145 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003146 X.setCount(cnt - 1);
3147 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003148 break;
3149 }
3150
3151 case RefVal::NotOwned: {
3152 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003153 if (cnt) {
3154 X.setCount(cnt - 1);
3155 X = X ^ RefVal::ReturnedOwned;
3156 }
3157 else {
3158 X = X ^ RefVal::ReturnedNotOwned;
3159 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003160 break;
3161 }
3162
3163 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003164 return;
3165 }
3166
3167 // Update the binding.
Ted Kremenek18a636d2009-06-18 01:23:53 +00003168 state = state->set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003169 Pred = Builder.MakeNode(Dst, S, Pred, state);
3170
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003171 // Did we cache out?
3172 if (!Pred)
3173 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003174
3175 // Update the autorelease counts.
3176 static unsigned autoreleasetag = 0;
3177 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3178 bool stop = false;
3179 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3180 X, stop);
3181
3182 // Did we cache out?
3183 if (!Pred || stop)
3184 return;
3185
3186 // Get the updated binding.
Ted Kremenek18a636d2009-06-18 01:23:53 +00003187 T = state->get<RefBindings>(Sym);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003188 assert(T);
3189 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003190
Ted Kremenek47a72422009-04-29 18:50:19 +00003191 // Any leaks or other errors?
3192 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003193 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003194 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003195 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003196 RetEffect RE = Summ.getRetEffect();
3197 bool hasError = false;
3198
Ted Kremenek5b44a402009-05-16 01:38:01 +00003199 if (RE.getKind() != RetEffect::NoRet) {
3200 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3201 // Things are more complicated with garbage collection. If the
3202 // returned object is suppose to be an Objective-C object, we have
3203 // a leak (as the caller expects a GC'ed object) because no
3204 // method should return ownership unless it returns a CF object.
3205 X = X ^ RefVal::ErrorGCLeakReturned;
3206
3207 // Keep this false until this is properly tested.
3208 hasError = true;
3209 }
3210 else if (!RE.isOwned()) {
3211 // Either we are using GC and the returned object is a CF type
3212 // or we aren't using GC. In either case, we expect that the
3213 // enclosing method is expected to return ownership.
3214 hasError = true;
3215 X = X ^ RefVal::ErrorLeakReturned;
3216 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003217 }
3218
3219 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003220 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003221 static int ReturnOwnLeakTag = 0;
Ted Kremenek18a636d2009-06-18 01:23:53 +00003222 state = state->set<RefBindings>(Sym, X);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003223 ExplodedNode<GRState> *N =
3224 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3225 if (N) {
3226 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003227 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3228 N, Sym, Eng);
3229 BR->EmitReport(report);
3230 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003231 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003232 }
3233 }
3234 else if (X.isReturnedNotOwned()) {
3235 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3236 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3237 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3238 if (Summ.getRetEffect().isOwned()) {
3239 // Trying to return a not owned object to a caller expecting an
3240 // owned object.
3241
3242 static int ReturnNotOwnedForOwnedTag = 0;
Ted Kremenek18a636d2009-06-18 01:23:53 +00003243 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003244 if (ExplodedNode<GRState> *N =
3245 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3246 state, Pred)) {
3247 CFRefReport *report =
3248 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3249 *this, N, Sym);
3250 BR->EmitReport(report);
3251 }
3252 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003253 }
3254 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003255}
3256
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003257// Assumptions.
3258
Ted Kremenek70970bf2009-06-18 22:57:13 +00003259const GRState* CFRefCount::EvalAssume(const GRState *state,
3260 SVal Cond, bool Assumption) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003261
3262 // FIXME: We may add to the interface of EvalAssume the list of symbols
3263 // whose assumptions have changed. For now we just iterate through the
3264 // bindings and check if any of the tracked symbols are NULL. This isn't
3265 // too bad since the number of symbols we will track in practice are
3266 // probably small and EvalAssume is only called at branches and a few
3267 // other places.
Ted Kremenek18a636d2009-06-18 01:23:53 +00003268 RefBindings B = state->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003269
3270 if (B.isEmpty())
Ted Kremenek18a636d2009-06-18 01:23:53 +00003271 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003272
Ted Kremenek18a636d2009-06-18 01:23:53 +00003273 bool changed = false;
3274 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003275
3276 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003277 // Check if the symbol is null (or equal to any constant).
3278 // If this is the case, stop tracking the symbol.
Ted Kremenek70970bf2009-06-18 22:57:13 +00003279 if (state->getSymVal(I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003280 changed = true;
3281 B = RefBFactory.Remove(B, I.getKey());
3282 }
3283 }
3284
Ted Kremenek91781202008-08-17 03:20:02 +00003285 if (changed)
Ted Kremenek18a636d2009-06-18 01:23:53 +00003286 state = state->set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003287
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003288 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003289}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003290
Ted Kremenek18a636d2009-06-18 01:23:53 +00003291const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
Ted Kremenekb6578942009-02-24 19:15:11 +00003292 RefVal V, ArgEffect E,
3293 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003294
3295 // In GC mode [... release] and [... retain] do nothing.
3296 switch (E) {
3297 default: break;
3298 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3299 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003300 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003301 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3302 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003303 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003304
Ted Kremenek6537a642009-03-17 19:42:23 +00003305 // Handle all use-after-releases.
3306 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3307 V = V ^ RefVal::ErrorUseAfterRelease;
3308 hasErr = V.getKind();
Ted Kremenek18a636d2009-06-18 01:23:53 +00003309 return state->set<RefBindings>(sym, V);
Ted Kremenek6537a642009-03-17 19:42:23 +00003310 }
3311
Ted Kremenek0d721572008-03-11 17:48:22 +00003312 switch (E) {
3313 default:
3314 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003315
3316 case Dealloc:
3317 // Any use of -dealloc in GC is *bad*.
3318 if (isGCEnabled()) {
3319 V = V ^ RefVal::ErrorDeallocGC;
3320 hasErr = V.getKind();
3321 break;
3322 }
3323
3324 switch (V.getKind()) {
3325 default:
3326 assert(false && "Invalid case.");
3327 case RefVal::Owned:
3328 // The object immediately transitions to the released state.
3329 V = V ^ RefVal::Released;
3330 V.clearCounts();
Ted Kremenek18a636d2009-06-18 01:23:53 +00003331 return state->set<RefBindings>(sym, V);
Ted Kremenek6537a642009-03-17 19:42:23 +00003332 case RefVal::NotOwned:
3333 V = V ^ RefVal::ErrorDeallocNotOwned;
3334 hasErr = V.getKind();
3335 break;
3336 }
3337 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003338
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003339 case NewAutoreleasePool:
3340 assert(!isGCEnabled());
Ted Kremenek18a636d2009-06-18 01:23:53 +00003341 return state->add<AutoreleaseStack>(sym);
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003342
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003343 case MayEscape:
3344 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003345 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003346 break;
3347 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003348
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003349 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003350
Ted Kremenekede40b72008-07-09 18:11:16 +00003351 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003352 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003353 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003354
Ted Kremenek9b112d22009-01-28 21:44:40 +00003355 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003356 if (isGCEnabled())
3357 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003358
3359 // Update the autorelease counts.
3360 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003361 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003362 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003363
Ted Kremenek227c5372008-05-06 02:41:27 +00003364 case StopTracking:
Ted Kremenek18a636d2009-06-18 01:23:53 +00003365 return state->remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003366
Ted Kremenek0d721572008-03-11 17:48:22 +00003367 case IncRef:
3368 switch (V.getKind()) {
3369 default:
3370 assert(false);
3371
3372 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003373 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003374 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003375 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003376 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003377 // Non-GC cases are handled above.
3378 assert(isGCEnabled());
3379 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003380 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003381 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003382 break;
3383
Ted Kremenek272aa852008-06-25 21:21:56 +00003384 case SelfOwn:
3385 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003386 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003387 case DecRef:
3388 switch (V.getKind()) {
3389 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003390 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003391 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003392
Ted Kremenek272aa852008-06-25 21:21:56 +00003393 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003394 assert(V.getCount() > 0);
3395 if (V.getCount() == 1) V = V ^ RefVal::Released;
3396 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003397 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003398
Ted Kremenek272aa852008-06-25 21:21:56 +00003399 case RefVal::NotOwned:
3400 if (V.getCount() > 0)
3401 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003402 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003403 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003404 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003405 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003406 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003407
Ted Kremenek0d721572008-03-11 17:48:22 +00003408 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003409 // Non-GC cases are handled above.
3410 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003411 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003412 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003413 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003414 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003415 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003416 }
Ted Kremenek18a636d2009-06-18 01:23:53 +00003417 return state->set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003418}
3419
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003420//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003421// Handle dead symbols and end-of-path.
3422//===----------------------------------------------------------------------===//
3423
Ted Kremenek18a636d2009-06-18 01:23:53 +00003424std::pair<ExplodedNode<GRState>*, const GRState *>
3425CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003426 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003427 GRExprEngine &Eng,
3428 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003429
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003430 unsigned ACnt = V.getAutoreleaseCount();
3431 stop = false;
3432
3433 // No autorelease counts? Nothing to be done.
3434 if (!ACnt)
3435 return std::make_pair(Pred, state);
3436
3437 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3438 unsigned Cnt = V.getCount();
3439
Ted Kremenek0603cf52009-05-11 15:26:06 +00003440 // FIXME: Handle sending 'autorelease' to already released object.
3441
3442 if (V.getKind() == RefVal::ReturnedOwned)
3443 ++Cnt;
3444
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003445 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003446 if (ACnt == Cnt) {
3447 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003448 if (V.getKind() == RefVal::ReturnedOwned)
3449 V = V ^ RefVal::ReturnedNotOwned;
3450 else
3451 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003452 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003453 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003454 V.setCount(Cnt - ACnt);
3455 V.setAutoreleaseCount(0);
3456 }
Ted Kremenek18a636d2009-06-18 01:23:53 +00003457 state = state->set<RefBindings>(Sym, V);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003458 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3459 stop = (N == 0);
3460 return std::make_pair(N, state);
3461 }
3462
3463 // Woah! More autorelease counts then retain counts left.
3464 // Emit hard error.
3465 stop = true;
3466 V = V ^ RefVal::ErrorOverAutorelease;
Ted Kremenek18a636d2009-06-18 01:23:53 +00003467 state = state->set<RefBindings>(Sym, V);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003468
3469 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003470 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003471
3472 std::string sbuf;
3473 llvm::raw_string_ostream os(sbuf);
Ted Kremenek2e6ce412009-05-15 06:02:08 +00003474 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekbd271be2009-05-10 05:11:21 +00003475 if (V.getAutoreleaseCount() > 1)
3476 os << V.getAutoreleaseCount() << " times";
3477 os << " but the object has ";
3478 if (V.getCount() == 0)
3479 os << "zero (locally visible)";
3480 else
3481 os << "+" << V.getCount();
3482 os << " retain counts";
3483
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003484 CFRefReport *report =
3485 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003486 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003487 BR->EmitReport(report);
3488 }
3489
3490 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003491}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003492
Ted Kremenek18a636d2009-06-18 01:23:53 +00003493const GRState *
3494CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003495 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3496
3497 bool hasLeak = V.isOwned() ||
3498 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3499
3500 if (!hasLeak)
Ted Kremenek18a636d2009-06-18 01:23:53 +00003501 return state->remove<RefBindings>(sid);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003502
3503 Leaked.push_back(sid);
Ted Kremenek18a636d2009-06-18 01:23:53 +00003504 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003505}
3506
3507ExplodedNode<GRState>*
Ted Kremenek18a636d2009-06-18 01:23:53 +00003508CFRefCount::ProcessLeaks(const GRState * state,
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003509 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3510 GenericNodeBuilder &Builder,
3511 GRExprEngine& Eng,
3512 ExplodedNode<GRState> *Pred) {
3513
3514 if (Leaked.empty())
3515 return Pred;
3516
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003517 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003518 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003519
3520 if (N) {
3521 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3522 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3523
3524 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3525 : leakAtReturn);
3526 assert(BT && "BugType not initialized.");
3527 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3528 BR->EmitReport(report);
3529 }
3530 }
3531
3532 return N;
3533}
3534
Ted Kremenek708af042009-02-05 06:50:21 +00003535void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3536 GREndPathNodeBuilder<GRState>& Builder) {
3537
Ted Kremenek18a636d2009-06-18 01:23:53 +00003538 const GRState *state = Builder.getState();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003539 GenericNodeBuilder Bd(Builder);
Ted Kremenek18a636d2009-06-18 01:23:53 +00003540 RefBindings B = state->get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003541 ExplodedNode<GRState> *Pred = 0;
3542
3543 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003544 bool stop = false;
3545 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3546 (*I).first,
3547 (*I).second, stop);
3548
3549 if (stop)
3550 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003551 }
3552
Ted Kremenek18a636d2009-06-18 01:23:53 +00003553 B = state->get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003554 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003555
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003556 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3557 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3558
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003559 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003560}
3561
3562void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3563 GRExprEngine& Eng,
3564 GRStmtNodeBuilder<GRState>& Builder,
3565 ExplodedNode<GRState>* Pred,
3566 Stmt* S,
Ted Kremenek18a636d2009-06-18 01:23:53 +00003567 const GRState* state,
Ted Kremenek708af042009-02-05 06:50:21 +00003568 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003569
Ted Kremenek18a636d2009-06-18 01:23:53 +00003570 RefBindings B = state->get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003571
3572 // Update counts from autorelease pools
3573 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3574 E = SymReaper.dead_end(); I != E; ++I) {
3575 SymbolRef Sym = *I;
3576 if (const RefVal* T = B.lookup(Sym)){
3577 // Use the symbol as the tag.
3578 // FIXME: This might not be as unique as we would like.
3579 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003580 bool stop = false;
3581 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3582 Sym, *T, stop);
3583 if (stop)
3584 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003585 }
3586 }
3587
Ted Kremenek18a636d2009-06-18 01:23:53 +00003588 B = state->get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003589 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003590
3591 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003592 E = SymReaper.dead_end(); I != E; ++I) {
3593 if (const RefVal* T = B.lookup(*I))
3594 state = HandleSymbolDeath(state, *I, *T, Leaked);
3595 }
Ted Kremenek708af042009-02-05 06:50:21 +00003596
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003597 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003598 {
3599 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3600 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3601 }
Ted Kremenek708af042009-02-05 06:50:21 +00003602
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003603 // Did we cache out?
3604 if (!Pred)
3605 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003606
3607 // Now generate a new node that nukes the old bindings.
Ted Kremenek18a636d2009-06-18 01:23:53 +00003608 RefBindings::Factory& F = state->get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003609
Ted Kremenek876d8df2009-02-19 23:47:02 +00003610 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003611 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3612
Ted Kremenek18a636d2009-06-18 01:23:53 +00003613 state = state->set<RefBindings>(B);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003614 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003615}
3616
3617void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3618 GRStmtNodeBuilder<GRState>& Builder,
3619 Expr* NodeExpr, Expr* ErrorExpr,
3620 ExplodedNode<GRState>* Pred,
3621 const GRState* St,
3622 RefVal::Kind hasErr, SymbolRef Sym) {
3623 Builder.BuildSinks = true;
3624 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3625
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003626 if (!N)
3627 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003628
3629 CFRefBug *BT = 0;
3630
Ted Kremenek6537a642009-03-17 19:42:23 +00003631 switch (hasErr) {
3632 default:
3633 assert(false && "Unhandled error.");
3634 return;
3635 case RefVal::ErrorUseAfterRelease:
3636 BT = static_cast<CFRefBug*>(useAfterRelease);
3637 break;
3638 case RefVal::ErrorReleaseNotOwned:
3639 BT = static_cast<CFRefBug*>(releaseNotOwned);
3640 break;
3641 case RefVal::ErrorDeallocGC:
3642 BT = static_cast<CFRefBug*>(deallocGC);
3643 break;
3644 case RefVal::ErrorDeallocNotOwned:
3645 BT = static_cast<CFRefBug*>(deallocNotOwned);
3646 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003647 }
3648
Ted Kremenekc26c4692009-02-18 03:48:14 +00003649 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003650 report->addRange(ErrorExpr->getSourceRange());
3651 BR->EmitReport(report);
3652}
3653
3654//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003655// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003656//===----------------------------------------------------------------------===//
3657
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003658GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3659 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003660 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003661}