blob: c441e0e2420c3bc161df9cfb3a4844dcd62f5089 [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
Eli Friedmand5a72f02009-08-05 19:21:58 +000047// begins with "alloc" or "new" or contains "copy" (for example, alloc,
Ted Kremenekb6f09542008-10-24 21:18:08 +000048// 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 {
Zhongxing Xu0ace2712009-08-06 12:48:26 +0000170 GRStmtNodeBuilder *SNB;
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000171 Stmt *S;
172 const void *tag;
Zhongxing Xu0ace2712009-08-06 12:48:26 +0000173 GREndPathNodeBuilder *ENB;
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000174public:
Zhongxing Xu0ace2712009-08-06 12:48:26 +0000175 GenericNodeBuilder(GRStmtNodeBuilder &snb, Stmt *s,
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000176 const void *t)
177 : SNB(&snb), S(s), tag(t), ENB(0) {}
Zhongxing Xu0ace2712009-08-06 12:48:26 +0000178
179 GenericNodeBuilder(GREndPathNodeBuilder &enb)
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000180 : SNB(0), S(0), tag(0), ENB(&enb) {}
181
Zhongxing Xu0ace2712009-08-06 12:48:26 +0000182 ExplodedNode *MakeNode(const GRState *state, ExplodedNode *Pred) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000183 if (SNB)
Zhongxing Xu2ac46a52009-08-15 03:17:38 +0000184 return SNB->generateNode(PostStmt(S, Pred->getLocationContext(), tag),
185 state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000186
187 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000188 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000189 }
190};
191} // end anonymous namespace
192
Ted Kremenek7d421f32008-04-09 23:49:11 +0000193//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000194// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000195//===----------------------------------------------------------------------===//
196
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000197static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000198 IdentifierInfo* II = &Ctx.Idents.get(name);
199 return Ctx.Selectors.getSelector(0, &II);
200}
201
Ted Kremenek0e344d42008-05-06 00:30:21 +0000202static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
203 IdentifierInfo* II = &Ctx.Idents.get(name);
204 return Ctx.Selectors.getSelector(1, &II);
205}
206
Ted Kremenek272aa852008-06-25 21:21:56 +0000207//===----------------------------------------------------------------------===//
208// Type querying functions.
209//===----------------------------------------------------------------------===//
210
Ted Kremenek17144e82009-01-12 21:45:02 +0000211static bool hasPrefix(const char* s, const char* prefix) {
212 if (!prefix)
213 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000214
Ted Kremenek17144e82009-01-12 21:45:02 +0000215 char c = *s;
216 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000217
Ted Kremenek17144e82009-01-12 21:45:02 +0000218 while (c != '\0' && cP != '\0') {
219 if (c != cP) break;
220 c = *(++s);
221 cP = *(++prefix);
222 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000223
Ted Kremenek17144e82009-01-12 21:45:02 +0000224 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000225}
226
Ted Kremenek17144e82009-01-12 21:45:02 +0000227static bool hasSuffix(const char* s, const char* suffix) {
228 const char* loc = strstr(s, suffix);
229 return loc && strcmp(suffix, loc) == 0;
230}
231
232static bool isRefType(QualType RetTy, const char* prefix,
233 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000234
Ted Kremenek2f289b62009-05-12 04:53:03 +0000235 // Recursively walk the typedef stack, allowing typedefs of reference types.
236 while (1) {
237 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
238 const char* TDName = TD->getDecl()->getIdentifier()->getName();
239 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
240 return true;
241
242 RetTy = TD->getDecl()->getUnderlyingType();
243 continue;
244 }
245 break;
Ted Kremenek17144e82009-01-12 21:45:02 +0000246 }
247
248 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000249 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000250
251 // Is the type void*?
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000252 const PointerType* PT = RetTy->getAs<PointerType>();
Ted Kremenek17144e82009-01-12 21:45:02 +0000253 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000254 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000255
256 // Does the name start with the prefix?
257 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000258}
259
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000260//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000261// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000262//===----------------------------------------------------------------------===//
263
Ted Kremenek272aa852008-06-25 21:21:56 +0000264/// ArgEffect is used to summarize a function/method call's effect on a
265/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000266enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
267 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
268 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000269
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000271template <> struct FoldingSetTrait<ArgEffect> {
272static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
273 ID.AddInteger((unsigned) X);
274}
Ted Kremenek272aa852008-06-25 21:21:56 +0000275};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000276} // end llvm namespace
277
Ted Kremeneka56ae162009-05-03 05:20:50 +0000278/// ArgEffects summarizes the effects of a function/method call on all of
279/// its arguments.
280typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
281
Ted Kremeneka7338b42008-03-11 06:39:11 +0000282namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000283
284/// RetEffect is used to summarize a function/method call's behavior with
285/// respect to its return value.
286class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000287public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000288 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000289 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
290 OwnedWhenTrackedReceiver };
Ted Kremenek68621b92009-01-28 05:56:51 +0000291
292 enum ObjKind { CF, ObjC, AnyObj };
293
Ted Kremeneka7338b42008-03-11 06:39:11 +0000294private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000295 Kind K;
296 ObjKind O;
297 unsigned index;
298
299 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
300 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000301
Ted Kremeneka7338b42008-03-11 06:39:11 +0000302public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000303 Kind getKind() const { return K; }
304
305 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000306
307 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000308 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000309 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000310 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000311
Ted Kremenek314b1952009-04-29 23:03:22 +0000312 bool isOwned() const {
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000313 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
314 K == OwnedWhenTrackedReceiver;
Ted Kremenek314b1952009-04-29 23:03:22 +0000315 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +0000316
Ted Kremenek0b7f0512009-05-12 20:06:54 +0000317 static RetEffect MakeOwnedWhenTrackedReceiver() {
318 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
319 }
320
Ted Kremenek272aa852008-06-25 21:21:56 +0000321 static RetEffect MakeAlias(unsigned Idx) {
322 return RetEffect(Alias, Idx);
323 }
324 static RetEffect MakeReceiverAlias() {
325 return RetEffect(ReceiverAlias);
326 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000327 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
328 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000329 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000330 static RetEffect MakeNotOwned(ObjKind o) {
331 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000332 }
333 static RetEffect MakeGCNotOwned() {
334 return RetEffect(GCNotOwnedSymbol, ObjC);
335 }
336
Ted Kremenek272aa852008-06-25 21:21:56 +0000337 static RetEffect MakeNoRet() {
338 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000339 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000340
Ted Kremenek272aa852008-06-25 21:21:56 +0000341 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000342 ID.AddInteger((unsigned)K);
343 ID.AddInteger((unsigned)O);
344 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000345 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000346};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000347
Ted Kremenek272aa852008-06-25 21:21:56 +0000348
Ted Kremenek2f226732009-05-04 05:31:22 +0000349class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000350 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
351 /// specifies the argument (starting from 0). This can be sparsely
352 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000354
355 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
356 /// do not have an entry in Args.
357 ArgEffect DefaultArgEffect;
358
Ted Kremenek272aa852008-06-25 21:21:56 +0000359 /// Receiver - If this summary applies to an Objective-C message expression,
360 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000361 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000362
363 /// Ret - The effect on the return value. Used to indicate if the
364 /// function/method call returns a new tracked symbol, returns an
365 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000366 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000367
Ted Kremenekf2717b02008-07-18 17:24:20 +0000368 /// EndPath - Indicates that execution of this method/function should
369 /// terminate the simulation of a path.
370 bool EndPath;
371
Ted Kremeneka7338b42008-03-11 06:39:11 +0000372public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000373 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000374 ArgEffect ReceiverEff, bool endpath = false)
375 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
376 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000377
Ted Kremenek272aa852008-06-25 21:21:56 +0000378 /// getArg - Return the argument effect on the argument specified by
379 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000380 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000381 if (const ArgEffect *AE = Args.lookup(idx))
382 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000383
Ted Kremenekbcaff792008-05-06 15:44:25 +0000384 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000385 }
386
Ted Kremenek2f226732009-05-04 05:31:22 +0000387 /// setDefaultArgEffect - Set the default argument effect.
388 void setDefaultArgEffect(ArgEffect E) {
389 DefaultArgEffect = E;
390 }
391
392 /// setArg - Set the argument effect on the argument specified by idx.
393 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
394 Args = AF.Add(Args, idx, E);
395 }
396
Ted Kremenek272aa852008-06-25 21:21:56 +0000397 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000398 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000399
Ted Kremenek2f226732009-05-04 05:31:22 +0000400 /// setRetEffect - Set the effect of the return value of the call.
401 void setRetEffect(RetEffect E) { Ret = E; }
402
Ted Kremenekf2717b02008-07-18 17:24:20 +0000403 /// isEndPath - Returns true if executing the given method/function should
404 /// terminate the path.
405 bool isEndPath() const { return EndPath; }
406
Ted Kremenek272aa852008-06-25 21:21:56 +0000407 /// getReceiverEffect - Returns the effect on the receiver of the call.
408 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000409 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000410
Ted Kremenek2f226732009-05-04 05:31:22 +0000411 /// setReceiverEffect - Set the effect on the receiver of the call.
412 void setReceiverEffect(ArgEffect E) { Receiver = E; }
413
Ted Kremeneka56ae162009-05-03 05:20:50 +0000414 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000415
Ted Kremeneka56ae162009-05-03 05:20:50 +0000416 ExprIterator begin_args() const { return Args.begin(); }
417 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000418
Ted Kremeneka56ae162009-05-03 05:20:50 +0000419 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000420 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000421 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000422 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000423 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000424 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000425 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000426 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000427 }
428
429 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000430 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000431 }
432};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000433} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000434
Ted Kremenek272aa852008-06-25 21:21:56 +0000435//===----------------------------------------------------------------------===//
436// Data structures for constructing summaries.
437//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000438
Ted Kremenek272aa852008-06-25 21:21:56 +0000439namespace {
440class VISIBILITY_HIDDEN ObjCSummaryKey {
441 IdentifierInfo* II;
442 Selector S;
443public:
444 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
445 : II(ii), S(s) {}
446
Ted Kremenek314b1952009-04-29 23:03:22 +0000447 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000448 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +0000449
450 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
451 : II(d ? d->getIdentifier() : ii), S(s) {}
Ted Kremenek272aa852008-06-25 21:21:56 +0000452
453 ObjCSummaryKey(Selector s)
454 : II(0), S(s) {}
455
456 IdentifierInfo* getIdentifier() const { return II; }
457 Selector getSelector() const { return S; }
458};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000459}
460
461namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000462template <> struct DenseMapInfo<ObjCSummaryKey> {
463 static inline ObjCSummaryKey getEmptyKey() {
464 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
465 DenseMapInfo<Selector>::getEmptyKey());
466 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000467
Ted Kremenek272aa852008-06-25 21:21:56 +0000468 static inline ObjCSummaryKey getTombstoneKey() {
469 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
470 DenseMapInfo<Selector>::getTombstoneKey());
471 }
472
473 static unsigned getHashValue(const ObjCSummaryKey &V) {
474 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
475 & 0x88888888)
476 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
477 & 0x55555555);
478 }
479
480 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
481 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
482 RHS.getIdentifier()) &&
483 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
484 RHS.getSelector());
485 }
486
487 static bool isPod() {
488 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
489 DenseMapInfo<Selector>::isPod();
490 }
491};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000492} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000493
Ted Kremenek84f010c2008-06-23 23:30:29 +0000494namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000495class VISIBILITY_HIDDEN ObjCSummaryCache {
496 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
497 MapTy M;
498public:
499 ObjCSummaryCache() {}
Ted Kremenek497006c2009-07-21 23:27:57 +0000500
501 RetainSummary* find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000502 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000503 // Lookup the method using the decl for the class @interface. If we
504 // have no decl, lookup using the class name.
505 return D ? find(D, S) : find(ClsName, S);
506 }
507
Ted Kremenek497006c2009-07-21 23:27:57 +0000508 RetainSummary* find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000509 // Do a lookup with the (D,S) pair. If we find a match return
510 // the iterator.
511 ObjCSummaryKey K(D, S);
512 MapTy::iterator I = M.find(K);
513
514 if (I != M.end() || !D)
Ted Kremenek497006c2009-07-21 23:27:57 +0000515 return I->second;
Ted Kremenek272aa852008-06-25 21:21:56 +0000516
517 // Walk the super chain. If we find a hit with a parent, we'll end
518 // up returning that summary. We actually allow that key (null,S), as
519 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
520 // generate initial summaries without having to worry about NSObject
521 // being declared.
522 // FIXME: We may change this at some point.
523 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
524 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
525 break;
526
527 if (!C)
Ted Kremenek497006c2009-07-21 23:27:57 +0000528 return NULL;
Ted Kremenek272aa852008-06-25 21:21:56 +0000529 }
530
531 // Cache the summary with original key to make the next lookup faster
532 // and return the iterator.
Ted Kremenek497006c2009-07-21 23:27:57 +0000533 RetainSummary *Summ = I->second;
534 M[K] = Summ;
535 return Summ;
Ted Kremenek272aa852008-06-25 21:21:56 +0000536 }
537
Ted Kremenek9449ca92008-08-12 20:41:56 +0000538
Ted Kremenek497006c2009-07-21 23:27:57 +0000539 RetainSummary* find(Expr* Receiver, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000540 return find(getReceiverDecl(Receiver), S);
541 }
542
Ted Kremenek497006c2009-07-21 23:27:57 +0000543 RetainSummary* find(IdentifierInfo* II, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000544 // FIXME: Class method lookup. Right now we dont' have a good way
545 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek497006c2009-07-21 23:27:57 +0000546 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
547
548 if (I == M.end())
549 I = M.find(ObjCSummaryKey(S));
550
551 return I == M.end() ? NULL : I->second;
Ted Kremenek272aa852008-06-25 21:21:56 +0000552 }
553
Steve Naroff329ec222009-07-10 23:34:53 +0000554 const ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
555 if (const ObjCObjectPointerType* PT =
556 E->getType()->getAsObjCObjectPointerType())
557 return PT->getInterfaceDecl();
558
559 return NULL;
Ted Kremenek272aa852008-06-25 21:21:56 +0000560 }
561
Ted Kremenek272aa852008-06-25 21:21:56 +0000562 RetainSummary*& operator[](ObjCMessageExpr* ME) {
563
564 Selector S = ME->getSelector();
565
566 if (Expr* Receiver = ME->getReceiver()) {
Steve Naroff329ec222009-07-10 23:34:53 +0000567 const ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +0000568 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) {
Steve Naroffad75bd22009-07-16 15:41:00 +0000886 if (!Ty->isObjCObjectPointerType())
Ted Kremenek35920ed2009-01-07 00:39:56 +0000887 return false;
888
Steve Naroff329ec222009-07-10 23:34:53 +0000889 const ObjCObjectPointerType *PT = Ty->getAsObjCObjectPointerType();
890
891 // Can be true for objects with the 'NSObject' attribute.
892 if (!PT)
Ted Kremenek0d813552009-04-23 22:11:07 +0000893 return true;
Steve Naroff329ec222009-07-10 23:34:53 +0000894
895 // We assume that id<..>, id, and "Class" all represent tracked objects.
896 if (PT->isObjCIdType() || PT->isObjCQualifiedIdType() ||
897 PT->isObjCClassType())
898 return true;
Ted Kremenek35920ed2009-01-07 00:39:56 +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.
Steve Naroff329ec222009-07-10 23:34:53 +0000902 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000903
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
Ted Kremenek35920ed2009-01-07 00:39:56 +0000911 for ( ; ID ; ID = ID->getSuperClass())
912 if (ID->getIdentifier() == NSObjectII)
913 return true;
914
915 return false;
916}
917
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000918bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
919 return isRefType(T, "CF") || // Core Foundation.
920 isRefType(T, "CG") || // Core Graphics.
921 isRefType(T, "DADisk") || // Disk Arbitration API.
922 isRefType(T, "DADissenter") ||
923 isRefType(T, "DASessionRef");
924}
925
Ted Kremenek35920ed2009-01-07 00:39:56 +0000926//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000927// Summary creation for functions (largely uses of Core Foundation).
928//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000929
Ted Kremenek17144e82009-01-12 21:45:02 +0000930static bool isRetain(FunctionDecl* FD, const char* FName) {
931 const char* loc = strstr(FName, "Retain");
932 return loc && loc[sizeof("Retain")-1] == '\0';
933}
934
935static bool isRelease(FunctionDecl* FD, const char* FName) {
936 const char* loc = strstr(FName, "Release");
937 return loc && loc[sizeof("Release")-1] == '\0';
938}
939
Ted Kremenekd13c1872008-06-24 03:56:45 +0000940RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000941 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000942 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000943 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000944 return I->second;
945
Ted Kremenek64cddf12009-05-04 15:34:07 +0000946 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000947 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000948
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000949 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000950 // We generate "stop" summaries for implicitly defined functions.
951 if (FD->isImplicit()) {
952 S = getPersistentStopSummary();
953 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000954 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000955
Ted Kremenek064ef322009-02-23 16:51:39 +0000956 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000957 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000958 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000959 const char* FName = FD->getIdentifier()->getName();
960
Ted Kremenek38c6f022009-03-05 22:11:14 +0000961 // Strip away preceding '_'. Doing this here will effect all the checks
962 // down below.
963 while (*FName == '_') ++FName;
964
Ted Kremenek17144e82009-01-12 21:45:02 +0000965 // Inspect the result type.
966 QualType RetTy = FT->getResultType();
967
968 // FIXME: This should all be refactored into a chain of "summary lookup"
969 // filters.
Ted Kremenek648a7702009-06-15 20:36:07 +0000970 assert (ScratchArgs.isEmpty());
971
Ted Kremenek77bec862009-06-11 18:17:24 +0000972 switch (strlen(FName)) {
973 default: break;
Ted Kremenek648a7702009-06-15 20:36:07 +0000974
975
Ted Kremenek77bec862009-06-11 18:17:24 +0000976 case 17:
977 // Handle: id NSMakeCollectable(CFTypeRef)
978 if (!memcmp(FName, "NSMakeCollectable", 17)) {
Steve Naroff329ec222009-07-10 23:34:53 +0000979 S = (RetTy->isObjCIdType())
Ted Kremenek77bec862009-06-11 18:17:24 +0000980 ? getUnarySummary(FT, cfmakecollectable)
981 : getPersistentStopSummary();
982 }
Ted Kremenek648a7702009-06-15 20:36:07 +0000983 else if (!memcmp(FName, "IOBSDNameMatching", 17) ||
984 !memcmp(FName, "IOServiceMatching", 17)) {
985 // Part of <rdar://problem/6961230>. (IOKit)
986 // This should be addressed using a API table.
987 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
988 DoNothing, DoNothing);
989 }
Ted Kremenek77bec862009-06-11 18:17:24 +0000990 break;
Ted Kremenek648a7702009-06-15 20:36:07 +0000991
992 case 21:
993 if (!memcmp(FName, "IOServiceNameMatching", 21)) {
994 // Part of <rdar://problem/6961230>. (IOKit)
995 // This should be addressed using a API table.
996 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
997 DoNothing, DoNothing);
998 }
999 break;
1000
1001 case 24:
1002 if (!memcmp(FName, "IOServiceAddNotification", 24)) {
1003 // Part of <rdar://problem/6961230>. (IOKit)
1004 // This should be addressed using a API table.
1005 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1006 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1007 }
1008 break;
1009
1010 case 25:
1011 if (!memcmp(FName, "IORegistryEntryIDMatching", 25)) {
1012 // Part of <rdar://problem/6961230>. (IOKit)
1013 // This should be addressed using a API table.
1014 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1015 DoNothing, DoNothing);
1016 }
1017 break;
1018
1019 case 26:
1020 if (!memcmp(FName, "IOOpenFirmwarePathMatching", 26)) {
1021 // Part of <rdar://problem/6961230>. (IOKit)
1022 // This should be addressed using a API table.
1023 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1024 DoNothing, DoNothing);
1025 }
1026 break;
1027
Ted Kremenek77bec862009-06-11 18:17:24 +00001028 case 27:
1029 if (!memcmp(FName, "IOServiceGetMatchingService", 27)) {
1030 // Part of <rdar://problem/6961230>.
1031 // This should be addressed using a API table.
Ted Kremenek77bec862009-06-11 18:17:24 +00001032 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1033 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1034 }
1035 break;
1036
1037 case 28:
1038 if (!memcmp(FName, "IOServiceGetMatchingServices", 28)) {
1039 // FIXES: <rdar://problem/6326900>
1040 // This should be addressed using a API table. This strcmp is also
1041 // a little gross, but there is no need to super optimize here.
Ted Kremenek77bec862009-06-11 18:17:24 +00001042 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
1043 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1044 }
1045 break;
Ted Kremenek648a7702009-06-15 20:36:07 +00001046
1047 case 32:
1048 if (!memcmp(FName, "IOServiceAddMatchingNotification", 32)) {
1049 // Part of <rdar://problem/6961230>.
1050 // This should be addressed using a API table.
1051 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1052 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1053 }
1054 break;
Ted Kremenek77bec862009-06-11 18:17:24 +00001055 }
1056
1057 // Did we get a summary?
1058 if (S)
1059 break;
Ted Kremenek7b88c892009-03-17 22:43:44 +00001060
1061 // Enable this code once the semantics of NSDeallocateObject are resolved
1062 // for GC. <rdar://problem/6619988>
1063#if 0
1064 // Handle: NSDeallocateObject(id anObject);
1065 // This method does allow 'nil' (although we don't check it now).
1066 if (strcmp(FName, "NSDeallocateObject") == 0) {
1067 return RetTy == Ctx.VoidTy
1068 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1069 : getPersistentStopSummary();
1070 }
1071#endif
Ted Kremenek17144e82009-01-12 21:45:02 +00001072
1073 if (RetTy->isPointerType()) {
1074 // For CoreFoundation ('CF') types.
1075 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1076 if (isRetain(FD, FName))
1077 S = getUnarySummary(FT, cfretain);
1078 else if (strstr(FName, "MakeCollectable"))
1079 S = getUnarySummary(FT, cfmakecollectable);
1080 else
1081 S = getCFCreateGetRuleSummary(FD, FName);
1082
1083 break;
1084 }
1085
1086 // For CoreGraphics ('CG') types.
1087 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1088 if (isRetain(FD, FName))
1089 S = getUnarySummary(FT, cfretain);
1090 else
1091 S = getCFCreateGetRuleSummary(FD, FName);
1092
1093 break;
1094 }
1095
1096 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1097 if (isRefType(RetTy, "DADisk") ||
1098 isRefType(RetTy, "DADissenter") ||
1099 isRefType(RetTy, "DASessionRef")) {
1100 S = getCFCreateGetRuleSummary(FD, FName);
1101 break;
1102 }
1103
1104 break;
1105 }
1106
1107 // Check for release functions, the only kind of functions that we care
1108 // about that don't return a pointer type.
1109 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001110 // Test for 'CGCF'.
1111 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1112 FName += 4;
1113 else
1114 FName += 2;
1115
1116 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001117 S = getUnarySummary(FT, cfrelease);
1118 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001119 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001120 // Remaining CoreFoundation and CoreGraphics functions.
1121 // We use to assume that they all strictly followed the ownership idiom
1122 // and that ownership cannot be transferred. While this is technically
1123 // correct, many methods allow a tracked object to escape. For example:
1124 //
1125 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1126 // CFDictionaryAddValue(y, key, x);
1127 // CFRelease(x);
1128 // ... it is okay to use 'x' since 'y' has a reference to it
1129 //
1130 // We handle this and similar cases with the follow heuristic. If the
1131 // function name contains "InsertValue", "SetValue" or "AddValue" then
1132 // we assume that arguments may "escape."
1133 //
1134 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1135 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001136 CStrInCStrNoCase(FName, "SetValue") ||
1137 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001138 ? MayEscape : DoNothing;
1139
1140 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001141 }
1142 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001143 }
1144 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001145
1146 if (!S)
1147 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001148
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001149 // Annotations override defaults.
1150 assert(S);
1151 updateSummaryFromAnnotations(*S, FD);
1152
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001153 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001154 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001155}
1156
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001157RetainSummary*
1158RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1159 const char* FName) {
1160
Ted Kremenek562c1302008-05-05 16:51:50 +00001161 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1162 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001163
Ted Kremenek562c1302008-05-05 16:51:50 +00001164 if (strstr(FName, "Get"))
1165 return getCFSummaryGetRule(FD);
1166
Ted Kremenek286e9852009-05-04 04:57:00 +00001167 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001168}
1169
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001170RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001171RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1172 UnaryFuncKind func) {
1173
Ted Kremenek17144e82009-01-12 21:45:02 +00001174 // Sanity check that this is *really* a unary function. This can
1175 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001176 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001177 if (!FTP || FTP->getNumArgs() != 1)
1178 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001179
Ted Kremeneka56ae162009-05-03 05:20:50 +00001180 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001181
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001182 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001183 case cfretain: {
1184 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001185 return getPersistentSummary(RetEffect::MakeAlias(0),
1186 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001187 }
1188
1189 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001190 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001191 return getPersistentSummary(RetEffect::MakeNoRet(),
1192 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001193 }
1194
1195 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001196 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001197 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001198 }
1199
1200 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001201 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001202 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001203 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001204}
1205
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001206RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001207 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001208
1209 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001210 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1211 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001212 }
1213
Ted Kremenek68621b92009-01-28 05:56:51 +00001214 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001215}
1216
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001217RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001218 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001219 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1220 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001221}
1222
Ted Kremeneka7338b42008-03-11 06:39:11 +00001223//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001224// Summary creation for Selectors.
1225//===----------------------------------------------------------------------===//
1226
Ted Kremenekbcaff792008-05-06 15:44:25 +00001227RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001228RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001229 assert(ScratchArgs.isEmpty());
1230 // 'init' methods conceptually return a newly allocated object and claim
1231 // the receiver.
1232 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
Ted Kremenekd27ed0d2009-06-05 23:18:01 +00001233 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001234
1235 return getDefaultSummary();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001236}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001237
1238void
1239RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1240 const FunctionDecl *FD) {
1241 if (!FD)
1242 return;
1243
Ted Kremenek77bec862009-06-11 18:17:24 +00001244 QualType RetTy = FD->getResultType();
1245
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001246 // Determine if there is a special return effect for this method.
Ted Kremenek401674a2009-06-05 23:00:33 +00001247 if (isTrackedObjCObjectType(RetTy)) {
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001248 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001249 Summ.setRetEffect(ObjCAllocRetE);
1250 }
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001251 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenek401674a2009-06-05 23:00:33 +00001252 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek77bec862009-06-11 18:17:24 +00001253 }
1254 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001255 else if (RetTy->getAs<PointerType>()) {
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001256 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001257 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1258 }
1259 }
1260}
1261
1262void
1263RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1264 const ObjCMethodDecl *MD) {
1265 if (!MD)
1266 return;
1267
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001268 bool isTrackedLoc = false;
1269
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001270 // Determine if there is a special return effect for this method.
1271 if (isTrackedObjCObjectType(MD->getResultType())) {
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001272 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001273 Summ.setRetEffect(ObjCAllocRetE);
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001274 return;
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001275 }
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001276
1277 isTrackedLoc = true;
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001278 }
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001279
1280 if (!isTrackedLoc)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001281 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Ted Kremenekd37e8c32009-07-06 18:30:43 +00001282
1283 if (isTrackedLoc && MD->getAttr<CFReturnsRetainedAttr>())
1284 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001285}
1286
Ted Kremenekbcaff792008-05-06 15:44:25 +00001287RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001288RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1289 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001290
Ted Kremenek578498a2009-04-29 00:42:39 +00001291 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001292 // Scan the method decl for 'void*' arguments. These should be treated
1293 // as 'StopTracking' because they are often used with delegates.
1294 // Delegates are a frequent form of false positives with the retain
1295 // count checker.
1296 unsigned i = 0;
1297 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1298 E = MD->param_end(); I != E; ++I, ++i)
1299 if (ParmVarDecl *PD = *I) {
1300 QualType Ty = Ctx.getCanonicalType(PD->getType());
1301 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001302 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001303 }
1304 }
1305
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001306 // Any special effect for the receiver?
1307 ArgEffect ReceiverEff = DoNothing;
1308
1309 // If one of the arguments in the selector has the keyword 'delegate' we
1310 // should stop tracking the reference count for the receiver. This is
1311 // because the reference count is quite possibly handled by a delegate
1312 // method.
1313 if (S.isKeywordSelector()) {
1314 const std::string &str = S.getAsString();
1315 assert(!str.empty());
1316 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1317 }
1318
Ted Kremenek174a0772009-04-23 23:08:22 +00001319 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001320 if (isTrackedObjCObjectType(RetTy)) {
1321 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1322 // by instance methods.
Ted Kremenek613ef972009-05-15 15:49:00 +00001323 RetEffect E = followsFundamentalRule(S)
1324 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001325
1326 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001327 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001328
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001329 // Look for methods that return an owned core foundation object.
1330 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek613ef972009-05-15 15:49:00 +00001331 RetEffect E = followsFundamentalRule(S)
1332 ? RetEffect::MakeOwned(RetEffect::CF, true)
1333 : RetEffect::MakeNotOwned(RetEffect::CF);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001334
1335 return getPersistentSummary(E, ReceiverEff, MayEscape);
1336 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001337
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001338 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001339 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001340
Ted Kremenek2f226732009-05-04 05:31:22 +00001341 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001342}
1343
1344RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001345RetainSummaryManager::getInstanceMethodSummary(Selector S,
1346 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001347 const ObjCInterfaceDecl* ID,
1348 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001349 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001350
Ted Kremeneka821b792009-04-29 05:04:30 +00001351 // Look up a summary in our summary cache.
Ted Kremenek497006c2009-07-21 23:27:57 +00001352 RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001353
Ted Kremenek497006c2009-07-21 23:27:57 +00001354 if (!Summ) {
1355 assert(ScratchArgs.isEmpty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001356
Ted Kremenek497006c2009-07-21 23:27:57 +00001357 // "initXXX": pass-through for receiver.
1358 if (deriveNamingConvention(S) == InitRule)
1359 Summ = getInitMethodSummary(RetTy);
1360 else
1361 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek2f226732009-05-04 05:31:22 +00001362
Ted Kremenek497006c2009-07-21 23:27:57 +00001363 // Annotations override defaults.
1364 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001365
Ted Kremenek497006c2009-07-21 23:27:57 +00001366 // Memoize the summary.
1367 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1368 }
1369
Ted Kremeneke4158502009-04-23 19:11:35 +00001370 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001371}
1372
Ted Kremeneka7722b72008-05-06 21:26:51 +00001373RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001374RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001375 const ObjCInterfaceDecl *ID,
1376 const ObjCMethodDecl *MD,
1377 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001378
Ted Kremenek578498a2009-04-29 00:42:39 +00001379 assert(ClsName && "Class name must be specified.");
Ted Kremenek497006c2009-07-21 23:27:57 +00001380 RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001381
Ted Kremenek497006c2009-07-21 23:27:57 +00001382 if (!Summ) {
1383 Summ = getCommonMethodSummary(MD, S, RetTy);
1384 // Annotations override defaults.
1385 updateSummaryFromAnnotations(*Summ, MD);
1386 // Memoize the summary.
1387 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1388 }
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001389
Ted Kremeneke4158502009-04-23 19:11:35 +00001390 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001391}
1392
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001393void RetainSummaryManager::InitializeClassMethodSummaries() {
1394 assert(ScratchArgs.isEmpty());
1395 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001396
Ted Kremenek272aa852008-06-25 21:21:56 +00001397 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1398 // NSObject and its derivatives.
1399 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1400 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1401 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001402
1403 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001404 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001405 GetNullarySelector("currentHandler", Ctx),
1406 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001407
1408 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001409 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001410 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1411 GetUnarySelector("addObject", Ctx),
1412 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001413 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001414
1415 // Create the summaries for [NSObject performSelector...]. We treat
1416 // these as 'stop tracking' for the arguments because they are often
1417 // used for delegates that can release the object. When we have better
1418 // inter-procedural analysis we can potentially do something better. This
1419 // workaround is to remove false positives.
1420 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1421 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1422 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1423 "afterDelay", NULL);
1424 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1425 "afterDelay", "inModes", NULL);
1426 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1427 "withObject", "waitUntilDone", NULL);
1428 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1429 "withObject", "waitUntilDone", "modes", NULL);
1430 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1431 "withObject", "waitUntilDone", NULL);
1432 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1433 "withObject", "waitUntilDone", "modes", NULL);
1434 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1435 "withObject", NULL);
Ted Kremenekdf100482009-05-14 21:29:16 +00001436
1437 // Specially handle NSData.
1438 RetainSummary *dataWithBytesNoCopySumm =
1439 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1440 DoNothing);
1441 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1442 "dataWithBytesNoCopy", "length", NULL);
1443 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1444 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001445}
1446
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001447void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001448
Ted Kremeneka56ae162009-05-03 05:20:50 +00001449 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001450
Ted Kremeneka7722b72008-05-06 21:26:51 +00001451 // Create the "init" selector. It just acts as a pass-through for the
1452 // receiver.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001453 addNSObjectMethSummary(GetNullarySelector("init", Ctx),
Ted Kremenek77bec862009-06-11 18:17:24 +00001454 getPersistentSummary(ObjCInitRetE, DecRefMsg));
Ted Kremeneka7722b72008-05-06 21:26:51 +00001455
1456 // The next methods are allocators.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001457 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001458
1459 // Create the "copy" selector.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001460 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001461
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001462 // Create the "mutableCopy" selector.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001463 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001464
Ted Kremenek266d8b62008-05-06 02:26:56 +00001465 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001466 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001467 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001468 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001469
1470 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001471 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001472 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001473
1474 // Create the "drain" selector.
1475 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001476 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001477
1478 // Create the -dealloc summary.
1479 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1480 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001481
1482 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001483 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001484 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001485
Ted Kremenekaac82832009-02-23 17:45:03 +00001486 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001487 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001488 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001489 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001490
Ted Kremenek45642a42008-08-12 18:48:50 +00001491 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001492 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1493 // self-own themselves. However, they only do this once they are displayed.
1494 // Thus, we need to track an NSWindow's display status.
1495 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001496 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001497 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1498 StopTracking,
1499 StopTracking);
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001500
1501 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1502
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001503#if 0
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001504 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001505 "styleMask", "backing", "defer", NULL);
1506
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001507 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001508 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001509#endif
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001510
Ted Kremenek45642a42008-08-12 18:48:50 +00001511 // For NSPanel (which subclasses NSWindow), allocated objects are not
1512 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001513 // FIXME: For now we don't track NSPanels. object for the same reason
1514 // as for NSWindow objects.
1515 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1516
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001517#if 0
1518 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001519 "styleMask", "backing", "defer", NULL);
1520
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001521 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek45642a42008-08-12 18:48:50 +00001522 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00001523#endif
Ted Kremenek88294222009-05-18 23:14:34 +00001524
1525 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1526 // exit a method.
1527 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek272aa852008-06-25 21:21:56 +00001528
Ted Kremenekf2717b02008-07-18 17:24:20 +00001529 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001530 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1531 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001532
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001533 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1534 "file", "lineNumber", "description", NULL);
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001535
1536 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1537 addInstMethSummary("QCRenderer", AllocSumm,
1538 "createSnapshotImageOfType", NULL);
1539 addInstMethSummary("QCView", AllocSumm,
1540 "createSnapshotImageOfType", NULL);
1541
Ted Kremenek054cd002009-06-15 20:58:58 +00001542 // Create summaries for CIContext, 'createCGImage' and
1543 // 'createCGLayerWithSize'.
Ted Kremenek3dc67bd2009-05-20 22:39:57 +00001544 addInstMethSummary("CIContext", AllocSumm,
1545 "createCGImage", "fromRect", NULL);
1546 addInstMethSummary("CIContext", AllocSumm,
Ted Kremenek054cd002009-06-15 20:58:58 +00001547 "createCGImage", "fromRect", "format", "colorSpace", NULL);
1548 addInstMethSummary("CIContext", AllocSumm, "createCGLayerWithSize",
1549 "info", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001550}
1551
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001552//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001553// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001554//===----------------------------------------------------------------------===//
1555
Ted Kremeneka7338b42008-03-11 06:39:11 +00001556namespace {
1557
Ted Kremenek7d421f32008-04-09 23:49:11 +00001558class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001559public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001560 enum Kind {
1561 Owned = 0, // Owning reference.
1562 NotOwned, // Reference is not owned by still valid (not freed).
1563 Released, // Object has been released.
1564 ReturnedOwned, // Returned object passes ownership to caller.
1565 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001566 ERROR_START,
1567 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1568 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001569 ErrorUseAfterRelease, // Object used after released.
1570 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001571 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001572 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001573 ErrorLeakReturned, // A memory leak due to the returning method not having
1574 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001575 ErrorGCLeakReturned,
1576 ErrorOverAutorelease,
1577 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001578 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001579
1580private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001581 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001582 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001583 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001584 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001585 QualType T;
1586
Ted Kremenek4d99d342009-05-08 20:01:42 +00001587 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1588 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001589
Ted Kremenek68621b92009-01-28 05:56:51 +00001590 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001591 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001592
1593public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001594 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001595
1596 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001597
Ted Kremenek4d99d342009-05-08 20:01:42 +00001598 unsigned getCount() const { return Cnt; }
1599 unsigned getAutoreleaseCount() const { return ACnt; }
1600 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1601 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001602 void setCount(unsigned i) { Cnt = i; }
1603 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001604
Ted Kremenek272aa852008-06-25 21:21:56 +00001605 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001606
1607 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001608
Ted Kremenek6537a642009-03-17 19:42:23 +00001609 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001610
Ted Kremenek6537a642009-03-17 19:42:23 +00001611 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001612
Ted Kremenekffefc352008-04-11 22:25:11 +00001613 bool isOwned() const {
1614 return getKind() == Owned;
1615 }
1616
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001617 bool isNotOwned() const {
1618 return getKind() == NotOwned;
1619 }
1620
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001621 bool isReturnedOwned() const {
1622 return getKind() == ReturnedOwned;
1623 }
1624
1625 bool isReturnedNotOwned() const {
1626 return getKind() == ReturnedNotOwned;
1627 }
1628
1629 bool isNonLeakError() const {
1630 Kind k = getKind();
1631 return isError(k) && !isLeak(k);
1632 }
1633
Ted Kremenek68621b92009-01-28 05:56:51 +00001634 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1635 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001636 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001637 }
1638
Ted Kremenek68621b92009-01-28 05:56:51 +00001639 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1640 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001641 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001642 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001643
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001644 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001645
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001646 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001647 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001648 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001649
Ted Kremenek272aa852008-06-25 21:21:56 +00001650 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001651 return RefVal(getKind(), getObjKind(), getCount() - i,
1652 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001653 }
1654
1655 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^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001661 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1662 getType());
1663 }
1664
1665 RefVal autorelease() const {
1666 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1667 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001668 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001669
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001670 void Profile(llvm::FoldingSetNodeID& ID) const {
1671 ID.AddInteger((unsigned) kind);
1672 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001673 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001674 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001675 }
1676
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001677 void print(llvm::raw_ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001678};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001679
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001680void RefVal::print(llvm::raw_ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001681 if (!T.isNull())
1682 Out << "Tracked Type:" << T.getAsString() << '\n';
1683
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001684 switch (getKind()) {
1685 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001686 case Owned: {
1687 Out << "Owned";
1688 unsigned cnt = getCount();
1689 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001690 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001691 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001692
Ted Kremenekc4f81022008-04-10 23:09:18 +00001693 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001694 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001695 unsigned cnt = getCount();
1696 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001697 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001698 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001699
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001700 case ReturnedOwned: {
1701 Out << "ReturnedOwned";
1702 unsigned cnt = getCount();
1703 if (cnt) Out << " (+ " << cnt << ")";
1704 break;
1705 }
1706
1707 case ReturnedNotOwned: {
1708 Out << "ReturnedNotOwned";
1709 unsigned cnt = getCount();
1710 if (cnt) Out << " (+ " << cnt << ")";
1711 break;
1712 }
1713
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001714 case Released:
1715 Out << "Released";
1716 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001717
1718 case ErrorDeallocGC:
1719 Out << "-dealloc (GC)";
1720 break;
1721
1722 case ErrorDeallocNotOwned:
1723 Out << "-dealloc (not-owned)";
1724 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001725
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001726 case ErrorLeak:
1727 Out << "Leaked";
1728 break;
1729
Ted Kremenek311f3d42008-10-22 23:56:21 +00001730 case ErrorLeakReturned:
1731 Out << "Leaked (Bad naming)";
1732 break;
1733
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001734 case ErrorGCLeakReturned:
1735 Out << "Leaked (GC-ed at return)";
1736 break;
1737
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001738 case ErrorUseAfterRelease:
1739 Out << "Use-After-Release [ERROR]";
1740 break;
1741
1742 case ErrorReleaseNotOwned:
1743 Out << "Release of Not-Owned [ERROR]";
1744 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001745
1746 case RefVal::ErrorOverAutorelease:
1747 Out << "Over autoreleased";
1748 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001749
1750 case RefVal::ErrorReturnedNotOwned:
1751 Out << "Non-owned object returned instead of owned";
1752 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001753 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001754
1755 if (ACnt) {
1756 Out << " [ARC +" << ACnt << ']';
1757 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001758}
Ted Kremenek0d721572008-03-11 17:48:22 +00001759
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001760} // end anonymous namespace
1761
1762//===----------------------------------------------------------------------===//
1763// RefBindings - State used to track object reference counts.
1764//===----------------------------------------------------------------------===//
1765
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001766typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001767static int RefBIndex = 0;
1768
1769namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001770 template<>
1771 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1772 static inline void* GDMIndex() { return &RefBIndex; }
1773 };
1774}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001775
1776//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001777// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001778//===----------------------------------------------------------------------===//
1779
Ted Kremenekb6578942009-02-24 19:15:11 +00001780typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1781typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1782typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001783
Ted Kremenekb6578942009-02-24 19:15:11 +00001784static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001785static int AutoRBIndex = 0;
1786
Ted Kremenekb6578942009-02-24 19:15:11 +00001787namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001788namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001789
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001790namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001791template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001792 : public GRStatePartialTrait<ARStack> {
1793 static inline void* GDMIndex() { return &AutoRBIndex; }
1794};
1795
1796template<> struct GRStateTrait<AutoreleasePoolContents>
1797 : public GRStatePartialTrait<ARPoolContents> {
1798 static inline void* GDMIndex() { return &AutoRCIndex; }
1799};
1800} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001801
Ted Kremenek681fb352009-03-20 17:34:15 +00001802static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1803 ARStack stack = state->get<AutoreleaseStack>();
1804 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1805}
1806
Ted Kremenek18a636d2009-06-18 01:23:53 +00001807static const GRState * SendAutorelease(const GRState *state,
1808 ARCounts::Factory &F, SymbolRef sym) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001809
1810 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenek18a636d2009-06-18 01:23:53 +00001811 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek681fb352009-03-20 17:34:15 +00001812 ARCounts newCnts(0);
1813
1814 if (cnts) {
1815 const unsigned *cnt = (*cnts).lookup(sym);
1816 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1817 }
1818 else
1819 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1820
Ted Kremenek18a636d2009-06-18 01:23:53 +00001821 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek681fb352009-03-20 17:34:15 +00001822}
1823
Ted Kremenek7aef4842008-04-16 20:40:59 +00001824//===----------------------------------------------------------------------===//
1825// Transfer functions.
1826//===----------------------------------------------------------------------===//
1827
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001828namespace {
1829
Ted Kremenekd1c53ff2009-06-26 00:05:51 +00001830class VISIBILITY_HIDDEN CFRefCount : public GRTransferFuncs {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001831public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001832 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001833 public:
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001834 virtual void Print(llvm::raw_ostream& Out, const GRState* state,
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001835 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001836 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001837
1838private:
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001839 typedef llvm::DenseMap<const ExplodedNode*, const RetainSummary*>
1840 SummaryLogTy;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001841
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001842 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001843 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001844 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001845 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001846
Ted Kremenek708af042009-02-05 06:50:21 +00001847 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001848 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001849 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001850 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001851 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001852 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001853
Ted Kremenek18a636d2009-06-18 01:23:53 +00001854 const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenekb6578942009-02-24 19:15:11 +00001855 RefVal::Kind& hasErr);
1856
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001857 void ProcessNonLeakError(ExplodedNodeSet& Dst,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001858 GRStmtNodeBuilder& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001859 Expr* NodeExpr, Expr* ErrorExpr,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001860 ExplodedNode* Pred,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001861 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001862 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001863
Ted Kremenek18a636d2009-06-18 01:23:53 +00001864 const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001865 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1866
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001867 ExplodedNode* ProcessLeaks(const GRState * state,
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001868 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1869 GenericNodeBuilder &Builder,
1870 GRExprEngine &Eng,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001871 ExplodedNode *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001872
Ted Kremenekb6578942009-02-24 19:15:11 +00001873public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001874 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001875 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001876 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1877 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001878 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1879 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001880
Ted Kremenek708af042009-02-05 06:50:21 +00001881 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001882
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001883 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001884
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001885 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1886 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001887 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001888
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001889 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001890 const LangOptions& getLangOptions() const { return LOpts; }
1891
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001892 const RetainSummary *getSummaryOfNode(const ExplodedNode *N) const {
Ted Kremenekc26c4692009-02-18 03:48:14 +00001893 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1894 return I == SummaryLog.end() ? 0 : I->second;
1895 }
1896
Ted Kremeneka7338b42008-03-11 06:39:11 +00001897 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001898
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001899 void EvalSummary(ExplodedNodeSet& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001900 GRExprEngine& Eng,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001901 GRStmtNodeBuilder& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001902 Expr* Ex,
1903 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001904 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001905 ExprIterator arg_beg, ExprIterator arg_end,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001906 ExplodedNode* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001907
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001908 virtual void EvalCall(ExplodedNodeSet& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001909 GRExprEngine& Eng,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001910 GRStmtNodeBuilder& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001911 CallExpr* CE, SVal L,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001912 ExplodedNode* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001913
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001914
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001915 virtual void EvalObjCMessageExpr(ExplodedNodeSet& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001916 GRExprEngine& Engine,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001917 GRStmtNodeBuilder& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001918 ObjCMessageExpr* ME,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001919 ExplodedNode* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001920
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001921 bool EvalObjCMessageExprAux(ExplodedNodeSet& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001922 GRExprEngine& Engine,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001923 GRStmtNodeBuilder& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001924 ObjCMessageExpr* ME,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001925 ExplodedNode* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001926
Ted Kremeneka42be302009-02-14 01:43:44 +00001927 // Stores.
1928 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1929
Ted Kremenekffefc352008-04-11 22:25:11 +00001930 // End-of-path.
1931
1932 virtual void EvalEndPath(GRExprEngine& Engine,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001933 GREndPathNodeBuilder& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001934
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001935 virtual void EvalDeadSymbols(ExplodedNodeSet& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001936 GRExprEngine& Engine,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001937 GRStmtNodeBuilder& Builder,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001938 ExplodedNode* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001939 Stmt* S, const GRState* state,
1940 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001941
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001942 std::pair<ExplodedNode*, const GRState *>
Ted Kremenek18a636d2009-06-18 01:23:53 +00001943 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001944 ExplodedNode* Pred, GRExprEngine &Eng,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001945 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001946 // Return statements.
1947
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001948 virtual void EvalReturn(ExplodedNodeSet& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001949 GRExprEngine& Engine,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00001950 GRStmtNodeBuilder& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001951 ReturnStmt* S,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00001952 ExplodedNode* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001953
1954 // Assumptions.
1955
Ted Kremenek70970bf2009-06-18 22:57:13 +00001956 virtual const GRState *EvalAssume(const GRState* state, SVal condition,
1957 bool assumption);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001958};
1959
1960} // end anonymous namespace
1961
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001962static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym,
1963 const GRState *state) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001964 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001965 if (Sym)
1966 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001967 else
1968 Out << "<pool>";
1969 Out << ":{";
1970
1971 // Get the contents of the pool.
1972 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1973 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1974 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1975
1976 Out << '}';
1977}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001978
Ted Kremenekdd04ed62009-06-24 23:06:47 +00001979void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out,
1980 const GRState* state,
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001981 const char* nl, const char* sep) {
1982
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001983 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001984
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001985 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001986 Out << sep << nl;
1987
1988 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1989 Out << (*I).first << " : ";
1990 (*I).second.print(Out);
1991 Out << nl;
1992 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001993
1994 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001995 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001996 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001997
Ted Kremenek681fb352009-03-20 17:34:15 +00001998 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1999 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
2000 PrintPool(Out, *I, state);
2001
2002 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00002003}
2004
Ted Kremenek47a72422009-04-29 18:50:19 +00002005//===----------------------------------------------------------------------===//
2006// Error reporting.
2007//===----------------------------------------------------------------------===//
2008
2009namespace {
2010
2011 //===-------------===//
2012 // Bug Descriptions. //
2013 //===-------------===//
2014
2015 class VISIBILITY_HIDDEN CFRefBug : public BugType {
2016 protected:
2017 CFRefCount& TF;
2018
2019 CFRefBug(CFRefCount* tf, const char* name)
2020 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
2021 public:
2022
2023 CFRefCount& getTF() { return TF; }
2024 const CFRefCount& getTF() const { return TF; }
2025
2026 // FIXME: Eventually remove.
2027 virtual const char* getDescription() const = 0;
2028
2029 virtual bool isLeak() const { return false; }
2030 };
2031
2032 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2033 public:
2034 UseAfterRelease(CFRefCount* tf)
2035 : CFRefBug(tf, "Use-after-release") {}
2036
2037 const char* getDescription() const {
2038 return "Reference-counted object is used after it is released";
2039 }
2040 };
2041
2042 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2043 public:
2044 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
2045
2046 const char* getDescription() const {
2047 return "Incorrect decrement of the reference count of an "
2048 "object is not owned at this point by the caller";
2049 }
2050 };
2051
2052 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2053 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002054 DeallocGC(CFRefCount *tf)
2055 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002056
2057 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002058 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00002059 }
2060 };
2061
2062 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2063 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002064 DeallocNotOwned(CFRefCount *tf)
2065 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002066
2067 const char *getDescription() const {
2068 return "-dealloc sent to object that may be referenced elsewhere";
2069 }
2070 };
2071
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002072 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
2073 public:
2074 OverAutorelease(CFRefCount *tf) :
2075 CFRefBug(tf, "Object sent -autorelease too many times") {}
2076
2077 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00002078 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002079 }
2080 };
2081
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002082 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
2083 public:
2084 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2085 CFRefBug(tf, "Method should return an owned object") {}
2086
2087 const char *getDescription() const {
2088 return "Object with +0 retain counts returned to caller where a +1 "
2089 "(owning) retain count is expected";
2090 }
2091 };
2092
Ted Kremenek47a72422009-04-29 18:50:19 +00002093 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2094 const bool isReturn;
2095 protected:
2096 Leak(CFRefCount* tf, const char* name, bool isRet)
2097 : CFRefBug(tf, name), isReturn(isRet) {}
2098 public:
2099
2100 const char* getDescription() const { return ""; }
2101
2102 bool isLeak() const { return true; }
2103 };
2104
2105 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2106 public:
2107 LeakAtReturn(CFRefCount* tf, const char* name)
2108 : Leak(tf, name, true) {}
2109 };
2110
2111 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2112 public:
2113 LeakWithinFunction(CFRefCount* tf, const char* name)
2114 : Leak(tf, name, false) {}
2115 };
2116
2117 //===---------===//
2118 // Bug Reports. //
2119 //===---------===//
2120
2121 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2122 protected:
2123 SymbolRef Sym;
2124 const CFRefCount &TF;
2125 public:
2126 CFRefReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002127 ExplodedNode *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00002128 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2129
2130 CFRefReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002131 ExplodedNode *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002132 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00002133
2134 virtual ~CFRefReport() {}
2135
2136 CFRefBug& getBugType() {
2137 return (CFRefBug&) RangedBugReport::getBugType();
2138 }
2139 const CFRefBug& getBugType() const {
2140 return (const CFRefBug&) RangedBugReport::getBugType();
2141 }
2142
Zhongxing Xu8e691432009-08-18 08:58:41 +00002143 virtual void getRanges(const SourceRange*& beg, const SourceRange*& end) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002144 if (!getBugType().isLeak())
Zhongxing Xu8e691432009-08-18 08:58:41 +00002145 RangedBugReport::getRanges(beg, end);
Ted Kremenek47a72422009-04-29 18:50:19 +00002146 else
2147 beg = end = 0;
2148 }
2149
2150 SymbolRef getSymbol() const { return Sym; }
2151
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002152 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002153 const ExplodedNode* N);
Ted Kremenek47a72422009-04-29 18:50:19 +00002154
2155 std::pair<const char**,const char**> getExtraDescriptiveText();
2156
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002157 PathDiagnosticPiece* VisitNode(const ExplodedNode* N,
2158 const ExplodedNode* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002159 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002160 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002161
Ted Kremenek47a72422009-04-29 18:50:19 +00002162 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2163 SourceLocation AllocSite;
2164 const MemRegion* AllocBinding;
2165 public:
2166 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002167 ExplodedNode *n, SymbolRef sym,
Ted Kremenek47a72422009-04-29 18:50:19 +00002168 GRExprEngine& Eng);
2169
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002170 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002171 const ExplodedNode* N);
Ted Kremenek47a72422009-04-29 18:50:19 +00002172
2173 SourceLocation getLocation() const { return AllocSite; }
2174 };
2175} // end anonymous namespace
2176
2177void CFRefCount::RegisterChecks(BugReporter& BR) {
2178 useAfterRelease = new UseAfterRelease(this);
2179 BR.Register(useAfterRelease);
2180
2181 releaseNotOwned = new BadRelease(this);
2182 BR.Register(releaseNotOwned);
2183
2184 deallocGC = new DeallocGC(this);
2185 BR.Register(deallocGC);
2186
2187 deallocNotOwned = new DeallocNotOwned(this);
2188 BR.Register(deallocNotOwned);
2189
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002190 overAutorelease = new OverAutorelease(this);
2191 BR.Register(overAutorelease);
2192
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002193 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2194 BR.Register(returnNotOwnedForOwned);
2195
Ted Kremenek47a72422009-04-29 18:50:19 +00002196 // First register "return" leaks.
2197 const char* name = 0;
2198
2199 if (isGCEnabled())
2200 name = "Leak of returned object when using garbage collection";
2201 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2202 name = "Leak of returned object when not using garbage collection (GC) in "
2203 "dual GC/non-GC code";
2204 else {
2205 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2206 name = "Leak of returned object";
2207 }
2208
2209 leakAtReturn = new LeakAtReturn(this, name);
2210 BR.Register(leakAtReturn);
2211
2212 // Second, register leaks within a function/method.
2213 if (isGCEnabled())
2214 name = "Leak of object when using garbage collection";
2215 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2216 name = "Leak of object when not using garbage collection (GC) in "
2217 "dual GC/non-GC code";
2218 else {
2219 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2220 name = "Leak";
2221 }
2222
2223 leakWithinFunction = new LeakWithinFunction(this, name);
2224 BR.Register(leakWithinFunction);
2225
2226 // Save the reference to the BugReporter.
2227 this->BR = &BR;
2228}
2229
2230static const char* Msgs[] = {
2231 // GC only
2232 "Code is compiled to only use garbage collection",
2233 // No GC.
2234 "Code is compiled to use reference counts",
2235 // Hybrid, with GC.
2236 "Code is compiled to use either garbage collection (GC) or reference counts"
2237 " (non-GC). The bug occurs with GC enabled",
2238 // Hybrid, without GC
2239 "Code is compiled to use either garbage collection (GC) or reference counts"
2240 " (non-GC). The bug occurs in non-GC mode"
2241};
2242
2243std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2244 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2245
2246 switch (TF.getLangOptions().getGCMode()) {
2247 default:
2248 assert(false);
2249
2250 case LangOptions::GCOnly:
2251 assert (TF.isGCEnabled());
2252 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2253
2254 case LangOptions::NonGC:
2255 assert (!TF.isGCEnabled());
2256 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2257
2258 case LangOptions::HybridGC:
2259 if (TF.isGCEnabled())
2260 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2261 else
2262 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2263 }
2264}
2265
2266static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2267 ArgEffect X) {
2268 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2269 I!=E; ++I)
2270 if (*I == X) return true;
2271
2272 return false;
2273}
2274
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002275PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N,
2276 const ExplodedNode* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002277 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002278
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002279 if (!isa<PostStmt>(N->getLocation()))
2280 return NULL;
2281
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002282 // Check if the type state has changed.
Ted Kremenek18a636d2009-06-18 01:23:53 +00002283 const GRState *PrevSt = PrevN->getState();
2284 const GRState *CurrSt = N->getState();
Ted Kremenek47a72422009-04-29 18:50:19 +00002285
Ted Kremenek18a636d2009-06-18 01:23:53 +00002286 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002287 if (!CurrT) return NULL;
2288
Ted Kremenek18a636d2009-06-18 01:23:53 +00002289 const RefVal &CurrV = *CurrT;
2290 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002291
2292 // Create a string buffer to constain all the useful things we want
2293 // to tell the user.
2294 std::string sbuf;
2295 llvm::raw_string_ostream os(sbuf);
2296
2297 // This is the allocation site since the previous node had no bindings
2298 // for this symbol.
2299 if (!PrevT) {
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002300 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek47a72422009-04-29 18:50:19 +00002301
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002302 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002303 // Get the name of the callee (if it is available).
Ted Kremenek18a636d2009-06-18 01:23:53 +00002304 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek47a72422009-04-29 18:50:19 +00002305 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2306 os << "Call to function '" << FD->getNameAsString() <<'\'';
2307 else
2308 os << "function call";
2309 }
2310 else {
2311 assert (isa<ObjCMessageExpr>(S));
2312 os << "Method";
2313 }
2314
2315 if (CurrV.getObjKind() == RetEffect::CF) {
2316 os << " returns a Core Foundation object with a ";
2317 }
2318 else {
2319 assert (CurrV.getObjKind() == RetEffect::ObjC);
2320 os << " returns an Objective-C object with a ";
2321 }
2322
2323 if (CurrV.isOwned()) {
2324 os << "+1 retain count (owning reference).";
2325
2326 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2327 assert(CurrV.getObjKind() == RetEffect::CF);
2328 os << " "
2329 "Core Foundation objects are not automatically garbage collected.";
2330 }
2331 }
2332 else {
2333 assert (CurrV.isNotOwned());
2334 os << "+0 retain count (non-owning reference).";
2335 }
2336
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002337 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002338 return new PathDiagnosticEventPiece(Pos, os.str());
2339 }
2340
2341 // Gather up the effects that were performed on the object at this
2342 // program point
2343 llvm::SmallVector<ArgEffect, 2> AEffects;
2344
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002345 if (const RetainSummary *Summ =
2346 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002347 // We only have summaries attached to nodes after evaluating CallExpr and
2348 // ObjCMessageExprs.
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002349 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek47a72422009-04-29 18:50:19 +00002350
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002351 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002352 // Iterate through the parameter expressions and see if the symbol
2353 // was ever passed as an argument.
2354 unsigned i = 0;
2355
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002356 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek47a72422009-04-29 18:50:19 +00002357 AI!=AE; ++AI, ++i) {
2358
2359 // Retrieve the value of the argument. Is it the symbol
2360 // we are interested in?
Ted Kremenek18a636d2009-06-18 01:23:53 +00002361 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenek47a72422009-04-29 18:50:19 +00002362 continue;
2363
2364 // We have an argument. Get the effect!
2365 AEffects.push_back(Summ->getArg(i));
2366 }
2367 }
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002368 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2369 if (const Expr *receiver = ME->getReceiver())
Ted Kremenek18a636d2009-06-18 01:23:53 +00002370 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002371 // The symbol we are tracking is the receiver.
2372 AEffects.push_back(Summ->getReceiverEffect());
2373 }
2374 }
2375 }
2376
2377 do {
2378 // Get the previous type state.
2379 RefVal PrevV = *PrevT;
2380
2381 // Specially handle -dealloc.
2382 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2383 // Determine if the object's reference count was pushed to zero.
2384 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2385 // We may not have transitioned to 'release' if we hit an error.
2386 // This case is handled elsewhere.
2387 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002388 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002389 os << "Object released by directly sending the '-dealloc' message";
2390 break;
2391 }
2392 }
2393
2394 // Specially handle CFMakeCollectable and friends.
2395 if (contains(AEffects, MakeCollectable)) {
2396 // Get the name of the function.
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002397 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek18a636d2009-06-18 01:23:53 +00002398 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
Ted Kremenek47a72422009-04-29 18:50:19 +00002399 const FunctionDecl* FD = X.getAsFunctionDecl();
2400 const std::string& FName = FD->getNameAsString();
2401
2402 if (TF.isGCEnabled()) {
2403 // Determine if the object's reference count was pushed to zero.
2404 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2405
2406 os << "In GC mode a call to '" << FName
2407 << "' decrements an object's retain count and registers the "
2408 "object with the garbage collector. ";
2409
2410 if (CurrV.getKind() == RefVal::Released) {
2411 assert(CurrV.getCount() == 0);
2412 os << "Since it now has a 0 retain count the object can be "
2413 "automatically collected by the garbage collector.";
2414 }
2415 else
2416 os << "An object must have a 0 retain count to be garbage collected. "
2417 "After this call its retain count is +" << CurrV.getCount()
2418 << '.';
2419 }
2420 else
2421 os << "When GC is not enabled a call to '" << FName
2422 << "' has no effect on its argument.";
2423
2424 // Nothing more to say.
2425 break;
2426 }
2427
2428 // Determine if the typestate has changed.
2429 if (!(PrevV == CurrV))
2430 switch (CurrV.getKind()) {
2431 case RefVal::Owned:
2432 case RefVal::NotOwned:
2433
Ted Kremenek4d99d342009-05-08 20:01:42 +00002434 if (PrevV.getCount() == CurrV.getCount()) {
2435 // Did an autorelease message get sent?
2436 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2437 return 0;
2438
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002439 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002440 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002441 break;
2442 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002443
2444 if (PrevV.getCount() > CurrV.getCount())
2445 os << "Reference count decremented.";
2446 else
2447 os << "Reference count incremented.";
2448
2449 if (unsigned Count = CurrV.getCount())
2450 os << " The object now has a +" << Count << " retain count.";
2451
2452 if (PrevV.getKind() == RefVal::Released) {
2453 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2454 os << " The object is not eligible for garbage collection until the "
2455 "retain count reaches 0 again.";
2456 }
2457
2458 break;
2459
2460 case RefVal::Released:
2461 os << "Object released.";
2462 break;
2463
2464 case RefVal::ReturnedOwned:
2465 os << "Object returned to caller as an owning reference (single retain "
2466 "count transferred to caller).";
2467 break;
2468
2469 case RefVal::ReturnedNotOwned:
2470 os << "Object returned to caller with a +0 (non-owning) retain count.";
2471 break;
2472
2473 default:
2474 return NULL;
2475 }
2476
2477 // Emit any remaining diagnostics for the argument effects (if any).
2478 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2479 E=AEffects.end(); I != E; ++I) {
2480
2481 // A bunch of things have alternate behavior under GC.
2482 if (TF.isGCEnabled())
2483 switch (*I) {
2484 default: break;
2485 case Autorelease:
2486 os << "In GC mode an 'autorelease' has no effect.";
2487 continue;
2488 case IncRefMsg:
2489 os << "In GC mode the 'retain' message has no effect.";
2490 continue;
2491 case DecRefMsg:
2492 os << "In GC mode the 'release' message has no effect.";
2493 continue;
2494 }
2495 }
2496 } while(0);
2497
2498 if (os.str().empty())
2499 return 0; // We have nothing to say!
Ted Kremenek4054ccc2009-05-13 07:12:33 +00002500
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002501 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002502 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002503 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2504
2505 // Add the range by scanning the children of the statement for any bindings
2506 // to Sym.
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002507 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2508 I!=E; ++I)
2509 if (const Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek18a636d2009-06-18 01:23:53 +00002510 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002511 P->addRange(Exp->getSourceRange());
2512 break;
2513 }
2514
2515 return P;
2516}
2517
2518namespace {
2519 class VISIBILITY_HIDDEN FindUniqueBinding :
2520 public StoreManager::BindingsHandler {
2521 SymbolRef Sym;
2522 const MemRegion* Binding;
2523 bool First;
2524
2525 public:
2526 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2527
2528 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2529 SVal val) {
2530
2531 SymbolRef SymV = val.getAsSymbol();
2532 if (!SymV || SymV != Sym)
2533 return true;
2534
2535 if (Binding) {
2536 First = false;
2537 return false;
2538 }
2539 else
2540 Binding = R;
2541
2542 return true;
2543 }
2544
2545 operator bool() { return First && Binding; }
2546 const MemRegion* getRegion() { return Binding; }
2547 };
2548}
2549
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002550static std::pair<const ExplodedNode*,const MemRegion*>
2551GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode* N,
Ted Kremenek47a72422009-04-29 18:50:19 +00002552 SymbolRef Sym) {
2553
2554 // Find both first node that referred to the tracked symbol and the
2555 // memory location that value was store to.
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002556 const ExplodedNode* Last = N;
Ted Kremenek47a72422009-04-29 18:50:19 +00002557 const MemRegion* FirstBinding = 0;
2558
2559 while (N) {
2560 const GRState* St = N->getState();
2561 RefBindings B = St->get<RefBindings>();
2562
2563 if (!B.lookup(Sym))
2564 break;
2565
2566 FindUniqueBinding FB(Sym);
2567 StateMgr.iterBindings(St, FB);
2568 if (FB) FirstBinding = FB.getRegion();
2569
2570 Last = N;
2571 N = N->pred_empty() ? NULL : *(N->pred_begin());
2572 }
2573
2574 return std::make_pair(Last, FirstBinding);
2575}
2576
2577PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002578CFRefReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002579 const ExplodedNode* EndN) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002580 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002581 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002582 BRC.addNotableSymbol(Sym);
2583 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002584}
2585
2586PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002587CFRefLeakReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002588 const ExplodedNode* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002589
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002590 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002591 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002592 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002593
2594 // We are reporting a leak. Walk up the graph to get to the first node where
2595 // the symbol appeared, and also get the first VarDecl that tracked object
2596 // is stored to.
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002597 const ExplodedNode* AllocNode = 0;
Ted Kremenek47a72422009-04-29 18:50:19 +00002598 const MemRegion* FirstBinding = 0;
2599
2600 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002601 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002602
2603 // Get the allocate site.
2604 assert(AllocNode);
Ted Kremenekc08c21e2009-07-22 22:35:28 +00002605 const Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenek47a72422009-04-29 18:50:19 +00002606
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002607 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002608 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2609
2610 // Compute an actual location for the leak. Sometimes a leak doesn't
2611 // occur at an actual statement (e.g., transition between blocks; end
2612 // of function) so we need to walk the graph and compute a real location.
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002613 const ExplodedNode* LeakN = EndN;
Ted Kremenek47a72422009-04-29 18:50:19 +00002614 PathDiagnosticLocation L;
2615
2616 while (LeakN) {
2617 ProgramPoint P = LeakN->getLocation();
2618
2619 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2620 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2621 break;
2622 }
2623 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2624 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2625 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2626 break;
2627 }
2628 }
2629
2630 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2631 }
2632
2633 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002634 const Decl &D = BRC.getCodeDecl();
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002635 L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002636 }
2637
2638 std::string sbuf;
2639 llvm::raw_string_ostream os(sbuf);
2640
2641 os << "Object allocated on line " << AllocLine;
2642
2643 if (FirstBinding)
2644 os << " and stored into '" << FirstBinding->getString() << '\'';
2645
2646 // Get the retain count.
2647 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2648
2649 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2650 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2651 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2652 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002653 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002654 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002655 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002656 << "') does not contain 'copy' or otherwise starts with"
2657 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002658 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002659 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002660 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2661 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2662 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002663 << "' is potentially leaked when using garbage collection. Callers "
2664 "of this method do not expect a returned object with a +1 retain "
2665 "count since they expect the object to be managed by the garbage "
2666 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002667 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002668 else
2669 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002670 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002671
2672 return new PathDiagnosticEventPiece(L, os.str());
2673}
2674
Ted Kremenek47a72422009-04-29 18:50:19 +00002675CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002676 ExplodedNode *n,
Ted Kremenek47a72422009-04-29 18:50:19 +00002677 SymbolRef sym, GRExprEngine& Eng)
2678: CFRefReport(D, tf, n, sym)
2679{
2680
2681 // Most bug reports are cached at the location where they occured.
2682 // With leaks, we want to unique them by the location where they were
2683 // allocated, and only report a single path. To do this, we need to find
2684 // the allocation site of a piece of tracked memory, which we do via a
2685 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2686 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2687 // that all ancestor nodes that represent the allocation site have the
2688 // same SourceLocation.
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002689 const ExplodedNode* AllocNode = 0;
Ted Kremenek47a72422009-04-29 18:50:19 +00002690
2691 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002692 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002693
2694 // Get the SourceLocation for the allocation site.
2695 ProgramPoint P = AllocNode->getLocation();
2696 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2697
2698 // Fill in the description of the bug.
2699 Description.clear();
2700 llvm::raw_string_ostream os(Description);
2701 SourceManager& SMgr = Eng.getContext().getSourceManager();
2702 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002703 os << "Potential leak ";
2704 if (tf.isGCEnabled()) {
2705 os << "(when using garbage collection) ";
2706 }
2707 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002708
2709 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2710 if (AllocBinding)
2711 os << " and stored into '" << AllocBinding->getString() << '\'';
2712}
2713
2714//===----------------------------------------------------------------------===//
2715// Main checker logic.
2716//===----------------------------------------------------------------------===//
2717
Ted Kremenek272aa852008-06-25 21:21:56 +00002718/// GetReturnType - Used to get the return type of a message expression or
2719/// function call with the intention of affixing that type to a tracked symbol.
2720/// While the the return type can be queried directly from RetEx, when
2721/// invoking class methods we augment to the return type to be that of
2722/// a pointer to the class (as opposed it just being id).
Steve Naroff329ec222009-07-10 23:34:53 +00002723static QualType GetReturnType(const Expr* RetE, ASTContext& Ctx) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002724 QualType RetTy = RetE->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002725 // If RetE is not a message expression just return its type.
2726 // If RetE is a message expression, return its types if it is something
Ted Kremenek272aa852008-06-25 21:21:56 +00002727 /// more specific than id.
Steve Naroff329ec222009-07-10 23:34:53 +00002728 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2729 if (const ObjCObjectPointerType *PT = RetTy->getAsObjCObjectPointerType())
2730 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2731 PT->isObjCClassType()) {
2732 // At this point we know the return type of the message expression is
2733 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2734 // is a call to a class method whose type we can resolve. In such
2735 // cases, promote the return type to XXX* (where XXX is the class).
2736 const ObjCInterfaceDecl *D = ME->getClassInfo().first;
2737 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2738 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002739
Steve Naroff329ec222009-07-10 23:34:53 +00002740 return RetTy;
Ted Kremenek272aa852008-06-25 21:21:56 +00002741}
2742
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002743void CFRefCount::EvalSummary(ExplodedNodeSet& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002744 GRExprEngine& Eng,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00002745 GRStmtNodeBuilder& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002746 Expr* Ex,
2747 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002748 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002749 ExprIterator arg_beg, ExprIterator arg_end,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002750 ExplodedNode* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002751
Ted Kremeneka7338b42008-03-11 06:39:11 +00002752 // Get the state.
Ted Kremenek18a636d2009-06-18 01:23:53 +00002753 const GRState *state = Builder.GetState(Pred);
Ted Kremenek227c5372008-05-06 02:41:27 +00002754
2755 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002756 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002757 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002758 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002759 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002760
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002761 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek18a636d2009-06-18 01:23:53 +00002762 SVal V = state->getSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002763 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002764
Ted Kremenek74556a12009-03-26 03:35:11 +00002765 if (Sym)
Ted Kremenek18a636d2009-06-18 01:23:53 +00002766 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002767 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002768 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002769 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002770 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002771 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002772 }
2773 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002774 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002775
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002776 if (isa<Loc>(V)) {
2777 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002778 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002779 continue;
2780
Ted Kremenekd1c53ff2009-06-26 00:05:51 +00002781 // Invalidate the value of the variable passed by reference.
Ted Kremenekede40b72008-07-09 18:11:16 +00002782
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002783 // FIXME: We can have collisions on the conjured symbol if the
2784 // expression *I also creates conjured symbols. We probably want
2785 // to identify conjured symbols by an expression pair: the enclosing
2786 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002787 // disambiguate conjured symbols.
Zhongxing Xud2d938c2009-06-29 06:43:40 +00002788 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002789 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
Ted Kremenek1cba5772009-05-11 22:55:17 +00002790
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002791 const MemRegion *R = MR->getRegion();
2792 // Are we dealing with an ElementRegion? If the element type is
2793 // a basic integer type (e.g., char, int) and the underying region
2794 // is a variable region then strip off the ElementRegion.
2795 // FIXME: We really need to think about this for the general case
2796 // as sometimes we are reasoning about arrays and other times
2797 // about (char*), etc., is just a form of passing raw bytes.
2798 // e.g., void *p = alloca(); foo((char*)p);
2799 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2800 // Checking for 'integral type' is probably too promiscuous, but
2801 // we'll leave it in for now until we have a systematic way of
2802 // handling all of these cases. Eventually we need to come up
2803 // with an interface to StoreManager so that this logic can be
2804 // approriately delegated to the respective StoreManagers while
2805 // still allowing us to do checker-specific logic (e.g.,
2806 // invalidating reference counts), probably via callbacks.
2807 if (ER->getElementType()->isIntegralType()) {
2808 const MemRegion *superReg = ER->getSuperRegion();
2809 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2810 isa<ObjCIvarRegion>(superReg))
2811 R = cast<TypedRegion>(superReg);
Ted Kremenek73ec7732009-05-06 18:19:24 +00002812 }
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002813 // FIXME: What about layers of ElementRegions?
2814 }
Zhongxing Xud2d938c2009-06-29 06:43:40 +00002815
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002816 // Is the invalidated variable something that we were tracking?
2817 SymbolRef Sym = state->getSValAsScalarOrLoc(R).getAsLocSymbol();
2818
2819 // Remove any existing reference-count binding.
2820 if (Sym)
2821 state = state->remove<RefBindings>(Sym);
2822
2823 state = StoreMgr.InvalidateRegion(state, R, *I, Count);
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002824 }
2825 else {
2826 // Nuke all other arguments passed by reference.
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002827 // FIXME: is this necessary or correct? unbind only removes the binding.
2828 // We should bind it to UnknownVal explicitly. Otherwise default value
2829 // may be loaded.
Ted Kremenek18a636d2009-06-18 01:23:53 +00002830 state = state->unbindLoc(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002831 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002832 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002833 else if (isa<nonloc::LocAsInteger>(V))
Zhongxing Xu3f2b3782009-07-06 06:01:24 +00002834 // FIXME: is this necessary or correct? unbind only removes the binding.
2835 // We should bind it to UnknownVal explicitly. Otherwise default value
2836 // may be loaded.
Ted Kremenek18a636d2009-06-18 01:23:53 +00002837 state = state->unbindLoc(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002838 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002839
Ted Kremenek272aa852008-06-25 21:21:56 +00002840 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002841 if (!ErrorExpr && Receiver) {
Ted Kremenek18a636d2009-06-18 01:23:53 +00002842 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002843 if (Sym) {
Ted Kremenek18a636d2009-06-18 01:23:53 +00002844 if (const RefVal* T = state->get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002845 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002846 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002847 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002848 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002849 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002850 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002851 }
2852 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002853
Ted Kremenek272aa852008-06-25 21:21:56 +00002854 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002855 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002856 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002857 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002858 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002859 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002860
Ted Kremenekf2717b02008-07-18 17:24:20 +00002861 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002862 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002863
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002864 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2865 assert(Receiver);
Ted Kremenek18a636d2009-06-18 01:23:53 +00002866 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002867 bool found = false;
2868 if (SymbolRef Sym = V.getAsLocSymbol())
Ted Kremenek18a636d2009-06-18 01:23:53 +00002869 if (state->get<RefBindings>(Sym)) {
Ted Kremenek0b7f0512009-05-12 20:06:54 +00002870 found = true;
2871 RE = Summaries.getObjAllocRetEffect();
2872 }
2873
2874 if (!found)
2875 RE = RetEffect::MakeNoRet();
2876 }
2877
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002878 switch (RE.getKind()) {
2879 default:
2880 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002881
Ted Kremenekd1c53ff2009-06-26 00:05:51 +00002882 case RetEffect::NoRet: {
Ted Kremenek455dd862008-04-11 20:23:24 +00002883 // Make up a symbol for the return value (not reference counted).
Ted Kremenekd1c53ff2009-06-26 00:05:51 +00002884 // FIXME: Most of this logic is not specific to the retain/release
2885 // checker.
Ted Kremenek455dd862008-04-11 20:23:24 +00002886
Ted Kremenek8f90e712008-10-17 22:23:12 +00002887 // FIXME: We eventually should handle structs and other compound types
2888 // that are returned by value.
2889
2890 QualType T = Ex->getType();
2891
Ted Kremenek79413a52008-11-13 06:10:40 +00002892 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002893 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002894 ValueManager &ValMgr = Eng.getValueManager();
2895 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek18a636d2009-06-18 01:23:53 +00002896 state = state->bindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002897 }
2898
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002899 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002900 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002901
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002902 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002903 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002904 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002905 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek18a636d2009-06-18 01:23:53 +00002906 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
2907 state = state->bindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002908 break;
2909 }
2910
Ted Kremenek227c5372008-05-06 02:41:27 +00002911 case RetEffect::ReceiverAlias: {
2912 assert (Receiver);
Ted Kremenek18a636d2009-06-18 01:23:53 +00002913 SVal V = state->getSValAsScalarOrLoc(Receiver);
2914 state = state->bindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002915 break;
2916 }
2917
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002918 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002919 case RetEffect::OwnedSymbol: {
2920 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002921 ValueManager &ValMgr = Eng.getValueManager();
2922 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2923 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenek18a636d2009-06-18 01:23:53 +00002924 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002925 RetT));
Zhongxing Xue32c7652009-06-23 09:02:15 +00002926 state = state->bindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002927
2928 // FIXME: Add a flag to the checker where allocations are assumed to
2929 // *not fail.
2930#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002931 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2932 bool isFeasible;
2933 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2934 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2935 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002936#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002937
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002938 break;
2939 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002940
2941 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002942 case RetEffect::NotOwnedSymbol: {
2943 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002944 ValueManager &ValMgr = Eng.getValueManager();
2945 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2946 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenek18a636d2009-06-18 01:23:53 +00002947 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002948 RetT));
Zhongxing Xue32c7652009-06-23 09:02:15 +00002949 state = state->bindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002950 break;
2951 }
2952 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002953
Ted Kremenek0dd65012009-02-18 02:00:25 +00002954 // Generate a sink node if we are at the end of a path.
Zhongxing Xu0ace2712009-08-06 12:48:26 +00002955 ExplodedNode *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002956 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2957 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002958
2959 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002960 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002961}
2962
2963
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002964void CFRefCount::EvalCall(ExplodedNodeSet& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002965 GRExprEngine& Eng,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00002966 GRStmtNodeBuilder& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002967 CallExpr* CE, SVal L,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002968 ExplodedNode* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002969 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002970 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002971 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002972
Ted Kremenek286e9852009-05-04 04:57:00 +00002973 assert(Summ);
2974 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002975 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002976}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002977
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002978void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002979 GRExprEngine& Eng,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00002980 GRStmtNodeBuilder& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002981 ObjCMessageExpr* ME,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00002982 ExplodedNode* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002983 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002984
Ted Kremenek272aa852008-06-25 21:21:56 +00002985 if (Expr* Receiver = ME->getReceiver()) {
2986 // We need the type-information of the tracked receiver object
2987 // Retrieve it from the state.
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00002988 const ObjCInterfaceDecl* ID = 0;
Ted Kremenek272aa852008-06-25 21:21:56 +00002989
2990 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2991 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002992 // FIXME: Is this really working as expected? There are cases where
2993 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002994 const GRState* St = Builder.GetState(Pred);
Ted Kremenekc0cccca2009-06-18 23:58:37 +00002995 SVal V = St->getSValAsScalarOrLoc(Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002996
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002997 SymbolRef Sym = V.getAsLocSymbol();
Steve Naroff329ec222009-07-10 23:34:53 +00002998
Ted Kremenek74556a12009-03-26 03:35:11 +00002999 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003000 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003001 if (const ObjCObjectPointerType* PT =
3002 T->getType()->getAsObjCObjectPointerType())
3003 ID = PT->getInterfaceDecl();
Ted Kremenek272aa852008-06-25 21:21:56 +00003004 }
3005 }
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00003006
3007 // FIXME: this is a hack. This may or may not be the actual method
3008 // that is called.
3009 if (!ID) {
Steve Naroff329ec222009-07-10 23:34:53 +00003010 if (const ObjCObjectPointerType *PT =
3011 Receiver->getType()->getAsObjCObjectPointerType())
3012 ID = PT->getInterfaceDecl();
Ted Kremenekd2c6b6e2009-05-13 18:16:01 +00003013 }
3014
Ted Kremenek04e00302009-04-29 17:09:14 +00003015 // FIXME: The receiver could be a reference to a class, meaning that
3016 // we should use the class method.
3017 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00003018
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003019 // Special-case: are we sending a mesage to "self"?
3020 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00003021 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
3022 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekc0cccca2009-06-18 23:58:37 +00003023 SVal X = St->getSValAsScalarOrLoc(Receiver);
Ted Kremenek2f226732009-05-04 05:31:22 +00003024 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekb86c11c2009-07-29 18:17:40 +00003025 if (L->getBaseRegion() == St->getSelfRegion()) {
Ted Kremenek2f226732009-05-04 05:31:22 +00003026 // Update the summary to make the default argument effect
3027 // 'StopTracking'.
3028 Summ = Summaries.copySummary(Summ);
3029 Summ->setDefaultArgEffect(StopTracking);
3030 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00003031 }
3032 }
Ted Kremenek272aa852008-06-25 21:21:56 +00003033 }
Ted Kremenek1feab292008-04-16 04:28:53 +00003034 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00003035 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00003036
Ted Kremenek286e9852009-05-04 04:57:00 +00003037 if (!Summ)
3038 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00003039
Ted Kremenek286e9852009-05-04 04:57:00 +00003040 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00003041 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00003042}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003043
3044namespace {
3045class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003046 const GRState *state;
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003047public:
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003048 StopTrackingCallback(const GRState *st) : state(st) {}
3049 const GRState *getState() const { return state; }
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003050
3051 bool VisitSymbol(SymbolRef sym) {
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003052 state = state->remove<RefBindings>(sym);
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003053 return true;
3054 }
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003055};
3056} // end anonymous namespace
3057
3058
Ted Kremeneka42be302009-02-14 01:43:44 +00003059void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00003060 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00003061 bool escapes = false;
3062
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003063 // A value escapes in three possible cases (this may change):
3064 //
3065 // (1) we are binding to something that is not a memory region.
3066 // (2) we are binding to a memregion that does not have stack storage
3067 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00003068 // does not understand.
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003069 const GRState *state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003070
Ted Kremeneka42be302009-02-14 01:43:44 +00003071 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00003072 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00003073 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00003074 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
Ted Kremenekdd2ec492009-06-23 18:05:21 +00003075 escapes = !R->hasStackStorage();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003076
3077 if (!escapes) {
3078 // To test (3), generate a new state with the binding removed. If it is
3079 // the same state, then it escapes (since the store cannot represent
3080 // the binding).
Ted Kremenek18a636d2009-06-18 01:23:53 +00003081 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003082 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00003083 }
Ted Kremeneka42be302009-02-14 01:43:44 +00003084
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003085 // If our store can represent the binding and we aren't storing to something
3086 // that doesn't have local storage then just return and have the simulation
3087 // state continue as is.
3088 if (!escapes)
3089 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003090
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003091 // Otherwise, find all symbols referenced by 'val' that we are tracking
3092 // and stop tracking them.
Ted Kremenekd2d7e182009-06-18 00:49:02 +00003093 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003094}
3095
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003096 // Return statements.
3097
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003098void CFRefCount::EvalReturn(ExplodedNodeSet& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003099 GRExprEngine& Eng,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00003100 GRStmtNodeBuilder& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003101 ReturnStmt* S,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003102 ExplodedNode* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003103
3104 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003105 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003106 return;
3107
Ted Kremenek18a636d2009-06-18 01:23:53 +00003108 const GRState *state = Builder.GetState(Pred);
3109 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003110
Ted Kremenek74556a12009-03-26 03:35:11 +00003111 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003112 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003113
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003114 // Get the reference count binding (if any).
Ted Kremenek18a636d2009-06-18 01:23:53 +00003115 const RefVal* T = state->get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003116
3117 if (!T)
3118 return;
3119
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003120 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003121 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003122
Ted Kremenek0b7f0512009-05-12 20:06:54 +00003123 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003124 case RefVal::Owned: {
3125 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003126 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003127 X.setCount(cnt - 1);
3128 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003129 break;
3130 }
3131
3132 case RefVal::NotOwned: {
3133 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003134 if (cnt) {
3135 X.setCount(cnt - 1);
3136 X = X ^ RefVal::ReturnedOwned;
3137 }
3138 else {
3139 X = X ^ RefVal::ReturnedNotOwned;
3140 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003141 break;
3142 }
3143
3144 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003145 return;
3146 }
3147
3148 // Update the binding.
Ted Kremenek18a636d2009-06-18 01:23:53 +00003149 state = state->set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003150 Pred = Builder.MakeNode(Dst, S, Pred, state);
3151
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003152 // Did we cache out?
3153 if (!Pred)
3154 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003155
3156 // Update the autorelease counts.
3157 static unsigned autoreleasetag = 0;
3158 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3159 bool stop = false;
3160 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3161 X, stop);
3162
3163 // Did we cache out?
3164 if (!Pred || stop)
3165 return;
3166
3167 // Get the updated binding.
Ted Kremenek18a636d2009-06-18 01:23:53 +00003168 T = state->get<RefBindings>(Sym);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003169 assert(T);
3170 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003171
Ted Kremenek47a72422009-04-29 18:50:19 +00003172 // Any leaks or other errors?
3173 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003174 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003175 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003176 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003177 RetEffect RE = Summ.getRetEffect();
3178 bool hasError = false;
3179
Ted Kremenek5b44a402009-05-16 01:38:01 +00003180 if (RE.getKind() != RetEffect::NoRet) {
3181 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3182 // Things are more complicated with garbage collection. If the
3183 // returned object is suppose to be an Objective-C object, we have
3184 // a leak (as the caller expects a GC'ed object) because no
3185 // method should return ownership unless it returns a CF object.
3186 X = X ^ RefVal::ErrorGCLeakReturned;
3187
3188 // Keep this false until this is properly tested.
3189 hasError = true;
3190 }
3191 else if (!RE.isOwned()) {
3192 // Either we are using GC and the returned object is a CF type
3193 // or we aren't using GC. In either case, we expect that the
3194 // enclosing method is expected to return ownership.
3195 hasError = true;
3196 X = X ^ RefVal::ErrorLeakReturned;
3197 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003198 }
3199
3200 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003201 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003202 static int ReturnOwnLeakTag = 0;
Ted Kremenek18a636d2009-06-18 01:23:53 +00003203 state = state->set<RefBindings>(Sym, X);
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003204 ExplodedNode *N =
Zhongxing Xu2ac46a52009-08-15 03:17:38 +00003205 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
3206 &ReturnOwnLeakTag), state, Pred);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003207 if (N) {
3208 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003209 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3210 N, Sym, Eng);
3211 BR->EmitReport(report);
3212 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003213 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003214 }
3215 }
3216 else if (X.isReturnedNotOwned()) {
3217 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3218 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3219 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3220 if (Summ.getRetEffect().isOwned()) {
3221 // Trying to return a not owned object to a caller expecting an
3222 // owned object.
3223
3224 static int ReturnNotOwnedForOwnedTag = 0;
Ted Kremenek18a636d2009-06-18 01:23:53 +00003225 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003226 if (ExplodedNode *N =
Zhongxing Xu2ac46a52009-08-15 03:17:38 +00003227 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
3228 &ReturnNotOwnedForOwnedTag),
3229 state, Pred)) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003230 CFRefReport *report =
3231 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3232 *this, N, Sym);
3233 BR->EmitReport(report);
3234 }
3235 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003236 }
3237 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003238}
3239
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003240// Assumptions.
3241
Ted Kremenek70970bf2009-06-18 22:57:13 +00003242const GRState* CFRefCount::EvalAssume(const GRState *state,
3243 SVal Cond, bool Assumption) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003244
3245 // FIXME: We may add to the interface of EvalAssume the list of symbols
3246 // whose assumptions have changed. For now we just iterate through the
3247 // bindings and check if any of the tracked symbols are NULL. This isn't
3248 // too bad since the number of symbols we will track in practice are
3249 // probably small and EvalAssume is only called at branches and a few
3250 // other places.
Ted Kremenek18a636d2009-06-18 01:23:53 +00003251 RefBindings B = state->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003252
3253 if (B.isEmpty())
Ted Kremenek18a636d2009-06-18 01:23:53 +00003254 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003255
Ted Kremenek18a636d2009-06-18 01:23:53 +00003256 bool changed = false;
3257 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003258
3259 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003260 // Check if the symbol is null (or equal to any constant).
3261 // If this is the case, stop tracking the symbol.
Ted Kremenek70970bf2009-06-18 22:57:13 +00003262 if (state->getSymVal(I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003263 changed = true;
3264 B = RefBFactory.Remove(B, I.getKey());
3265 }
3266 }
3267
Ted Kremenek91781202008-08-17 03:20:02 +00003268 if (changed)
Ted Kremenek18a636d2009-06-18 01:23:53 +00003269 state = state->set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003270
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003271 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003272}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003273
Ted Kremenek18a636d2009-06-18 01:23:53 +00003274const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
Ted Kremenekb6578942009-02-24 19:15:11 +00003275 RefVal V, ArgEffect E,
3276 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003277
3278 // In GC mode [... release] and [... retain] do nothing.
3279 switch (E) {
3280 default: break;
3281 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3282 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003283 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003284 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3285 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003286 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003287
Ted Kremenek6537a642009-03-17 19:42:23 +00003288 // Handle all use-after-releases.
3289 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3290 V = V ^ RefVal::ErrorUseAfterRelease;
3291 hasErr = V.getKind();
Ted Kremenek18a636d2009-06-18 01:23:53 +00003292 return state->set<RefBindings>(sym, V);
Ted Kremenek6537a642009-03-17 19:42:23 +00003293 }
3294
Ted Kremenek0d721572008-03-11 17:48:22 +00003295 switch (E) {
3296 default:
3297 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003298
3299 case Dealloc:
3300 // Any use of -dealloc in GC is *bad*.
3301 if (isGCEnabled()) {
3302 V = V ^ RefVal::ErrorDeallocGC;
3303 hasErr = V.getKind();
3304 break;
3305 }
3306
3307 switch (V.getKind()) {
3308 default:
3309 assert(false && "Invalid case.");
3310 case RefVal::Owned:
3311 // The object immediately transitions to the released state.
3312 V = V ^ RefVal::Released;
3313 V.clearCounts();
Ted Kremenek18a636d2009-06-18 01:23:53 +00003314 return state->set<RefBindings>(sym, V);
Ted Kremenek6537a642009-03-17 19:42:23 +00003315 case RefVal::NotOwned:
3316 V = V ^ RefVal::ErrorDeallocNotOwned;
3317 hasErr = V.getKind();
3318 break;
3319 }
3320 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003321
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003322 case NewAutoreleasePool:
3323 assert(!isGCEnabled());
Ted Kremenek18a636d2009-06-18 01:23:53 +00003324 return state->add<AutoreleaseStack>(sym);
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003325
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003326 case MayEscape:
3327 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003328 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003329 break;
3330 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003331
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003332 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003333
Ted Kremenekede40b72008-07-09 18:11:16 +00003334 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003335 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003336 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003337
Ted Kremenek9b112d22009-01-28 21:44:40 +00003338 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003339 if (isGCEnabled())
3340 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003341
3342 // Update the autorelease counts.
3343 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003344 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003345 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003346
Ted Kremenek227c5372008-05-06 02:41:27 +00003347 case StopTracking:
Ted Kremenek18a636d2009-06-18 01:23:53 +00003348 return state->remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003349
Ted Kremenek0d721572008-03-11 17:48:22 +00003350 case IncRef:
3351 switch (V.getKind()) {
3352 default:
3353 assert(false);
3354
3355 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003356 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003357 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003358 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003359 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003360 // Non-GC cases are handled above.
3361 assert(isGCEnabled());
3362 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003363 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003364 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003365 break;
3366
Ted Kremenek272aa852008-06-25 21:21:56 +00003367 case SelfOwn:
3368 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003369 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003370 case DecRef:
3371 switch (V.getKind()) {
3372 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003373 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003374 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003375
Ted Kremenek272aa852008-06-25 21:21:56 +00003376 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003377 assert(V.getCount() > 0);
3378 if (V.getCount() == 1) V = V ^ RefVal::Released;
3379 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003380 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003381
Ted Kremenek272aa852008-06-25 21:21:56 +00003382 case RefVal::NotOwned:
3383 if (V.getCount() > 0)
3384 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003385 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003386 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003387 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003388 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003389 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003390
Ted Kremenek0d721572008-03-11 17:48:22 +00003391 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003392 // Non-GC cases are handled above.
3393 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003394 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003395 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003396 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003397 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003398 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003399 }
Ted Kremenek18a636d2009-06-18 01:23:53 +00003400 return state->set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003401}
3402
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003403//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003404// Handle dead symbols and end-of-path.
3405//===----------------------------------------------------------------------===//
3406
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003407std::pair<ExplodedNode*, const GRState *>
Ted Kremenek18a636d2009-06-18 01:23:53 +00003408CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003409 ExplodedNode* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003410 GRExprEngine &Eng,
3411 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003412
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003413 unsigned ACnt = V.getAutoreleaseCount();
3414 stop = false;
3415
3416 // No autorelease counts? Nothing to be done.
3417 if (!ACnt)
3418 return std::make_pair(Pred, state);
3419
3420 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3421 unsigned Cnt = V.getCount();
3422
Ted Kremenek0603cf52009-05-11 15:26:06 +00003423 // FIXME: Handle sending 'autorelease' to already released object.
3424
3425 if (V.getKind() == RefVal::ReturnedOwned)
3426 ++Cnt;
3427
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003428 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003429 if (ACnt == Cnt) {
3430 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003431 if (V.getKind() == RefVal::ReturnedOwned)
3432 V = V ^ RefVal::ReturnedNotOwned;
3433 else
3434 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003435 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003436 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003437 V.setCount(Cnt - ACnt);
3438 V.setAutoreleaseCount(0);
3439 }
Ted Kremenek18a636d2009-06-18 01:23:53 +00003440 state = state->set<RefBindings>(Sym, V);
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003441 ExplodedNode *N = Bd.MakeNode(state, Pred);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003442 stop = (N == 0);
3443 return std::make_pair(N, state);
3444 }
3445
3446 // Woah! More autorelease counts then retain counts left.
3447 // Emit hard error.
3448 stop = true;
3449 V = V ^ RefVal::ErrorOverAutorelease;
Ted Kremenek18a636d2009-06-18 01:23:53 +00003450 state = state->set<RefBindings>(Sym, V);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003451
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003452 if (ExplodedNode *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003453 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003454
3455 std::string sbuf;
3456 llvm::raw_string_ostream os(sbuf);
Ted Kremenek2e6ce412009-05-15 06:02:08 +00003457 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenekbd271be2009-05-10 05:11:21 +00003458 if (V.getAutoreleaseCount() > 1)
3459 os << V.getAutoreleaseCount() << " times";
3460 os << " but the object has ";
3461 if (V.getCount() == 0)
3462 os << "zero (locally visible)";
3463 else
3464 os << "+" << V.getCount();
3465 os << " retain counts";
3466
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003467 CFRefReport *report =
3468 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003469 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003470 BR->EmitReport(report);
3471 }
3472
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003473 return std::make_pair((ExplodedNode*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003474}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003475
Ted Kremenek18a636d2009-06-18 01:23:53 +00003476const GRState *
3477CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003478 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3479
3480 bool hasLeak = V.isOwned() ||
3481 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3482
3483 if (!hasLeak)
Ted Kremenek18a636d2009-06-18 01:23:53 +00003484 return state->remove<RefBindings>(sid);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003485
3486 Leaked.push_back(sid);
Ted Kremenek18a636d2009-06-18 01:23:53 +00003487 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003488}
3489
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003490ExplodedNode*
Ted Kremenek18a636d2009-06-18 01:23:53 +00003491CFRefCount::ProcessLeaks(const GRState * state,
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003492 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3493 GenericNodeBuilder &Builder,
3494 GRExprEngine& Eng,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003495 ExplodedNode *Pred) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003496
3497 if (Leaked.empty())
3498 return Pred;
3499
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003500 // Generate an intermediate node representing the leak point.
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003501 ExplodedNode *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003502
3503 if (N) {
3504 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3505 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3506
3507 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3508 : leakAtReturn);
3509 assert(BT && "BugType not initialized.");
3510 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3511 BR->EmitReport(report);
3512 }
3513 }
3514
3515 return N;
3516}
3517
Ted Kremenek708af042009-02-05 06:50:21 +00003518void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00003519 GREndPathNodeBuilder& Builder) {
Ted Kremenek708af042009-02-05 06:50:21 +00003520
Ted Kremenek18a636d2009-06-18 01:23:53 +00003521 const GRState *state = Builder.getState();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003522 GenericNodeBuilder Bd(Builder);
Ted Kremenek18a636d2009-06-18 01:23:53 +00003523 RefBindings B = state->get<RefBindings>();
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003524 ExplodedNode *Pred = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003525
3526 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003527 bool stop = false;
3528 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3529 (*I).first,
3530 (*I).second, stop);
3531
3532 if (stop)
3533 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003534 }
3535
Ted Kremenek18a636d2009-06-18 01:23:53 +00003536 B = state->get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003537 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003538
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003539 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3540 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3541
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003542 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003543}
3544
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003545void CFRefCount::EvalDeadSymbols(ExplodedNodeSet& Dst,
Ted Kremenek708af042009-02-05 06:50:21 +00003546 GRExprEngine& Eng,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00003547 GRStmtNodeBuilder& Builder,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003548 ExplodedNode* Pred,
Ted Kremenek708af042009-02-05 06:50:21 +00003549 Stmt* S,
Ted Kremenek18a636d2009-06-18 01:23:53 +00003550 const GRState* state,
Ted Kremenek708af042009-02-05 06:50:21 +00003551 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003552
Ted Kremenek18a636d2009-06-18 01:23:53 +00003553 RefBindings B = state->get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003554
3555 // Update counts from autorelease pools
3556 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3557 E = SymReaper.dead_end(); I != E; ++I) {
3558 SymbolRef Sym = *I;
3559 if (const RefVal* T = B.lookup(Sym)){
3560 // Use the symbol as the tag.
3561 // FIXME: This might not be as unique as we would like.
3562 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003563 bool stop = false;
3564 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3565 Sym, *T, stop);
3566 if (stop)
3567 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003568 }
3569 }
3570
Ted Kremenek18a636d2009-06-18 01:23:53 +00003571 B = state->get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003572 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003573
3574 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003575 E = SymReaper.dead_end(); I != E; ++I) {
3576 if (const RefVal* T = B.lookup(*I))
3577 state = HandleSymbolDeath(state, *I, *T, Leaked);
3578 }
Ted Kremenek708af042009-02-05 06:50:21 +00003579
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003580 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003581 {
3582 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3583 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3584 }
Ted Kremenek708af042009-02-05 06:50:21 +00003585
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003586 // Did we cache out?
3587 if (!Pred)
3588 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003589
3590 // Now generate a new node that nukes the old bindings.
Ted Kremenek18a636d2009-06-18 01:23:53 +00003591 RefBindings::Factory& F = state->get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003592
Ted Kremenek876d8df2009-02-19 23:47:02 +00003593 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003594 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3595
Ted Kremenek18a636d2009-06-18 01:23:53 +00003596 state = state->set<RefBindings>(B);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003597 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003598}
3599
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003600void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst,
Zhongxing Xu0ace2712009-08-06 12:48:26 +00003601 GRStmtNodeBuilder& Builder,
Zhongxing Xuff71ed02009-08-06 01:32:16 +00003602 Expr* NodeExpr, Expr* ErrorExpr,
3603 ExplodedNode* Pred,
Ted Kremenek708af042009-02-05 06:50:21 +00003604 const GRState* St,
3605 RefVal::Kind hasErr, SymbolRef Sym) {
3606 Builder.BuildSinks = true;
Zhongxing Xu0ace2712009-08-06 12:48:26 +00003607 ExplodedNode *N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
Ted Kremenek708af042009-02-05 06:50:21 +00003608
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003609 if (!N)
3610 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003611
3612 CFRefBug *BT = 0;
3613
Ted Kremenek6537a642009-03-17 19:42:23 +00003614 switch (hasErr) {
3615 default:
3616 assert(false && "Unhandled error.");
3617 return;
3618 case RefVal::ErrorUseAfterRelease:
3619 BT = static_cast<CFRefBug*>(useAfterRelease);
3620 break;
3621 case RefVal::ErrorReleaseNotOwned:
3622 BT = static_cast<CFRefBug*>(releaseNotOwned);
3623 break;
3624 case RefVal::ErrorDeallocGC:
3625 BT = static_cast<CFRefBug*>(deallocGC);
3626 break;
3627 case RefVal::ErrorDeallocNotOwned:
3628 BT = static_cast<CFRefBug*>(deallocNotOwned);
3629 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003630 }
3631
Ted Kremenekc26c4692009-02-18 03:48:14 +00003632 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003633 report->addRange(ErrorExpr->getSourceRange());
3634 BR->EmitReport(report);
3635}
3636
3637//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003638// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003639//===----------------------------------------------------------------------===//
3640
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003641GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3642 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003643 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003644}