blob: 29ad73f0f90a5ead67c74631c8e6a8cffaf72c13 [file] [log] [blame]
Chris Lattnerbda0b622008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek2fff37e2008-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 Greif843e9342008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek2fff37e2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenek072192b2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekc9fa2f72008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek41573eb2009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenekb9d17f92008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenek4dc41cc2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek5216ad72009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek900a2d72008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenekf3948042008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek98530452008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenek5c74d502008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenek5c74d502008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenekb80976c2009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenek39868cd2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenekb80976c2009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek39868cd2009-02-21 18:26:02 +0000122 if ((AtBeginning && StringsEqualNoCase("alloc", s, len)) ||
Ted Kremenek61d2e4a2009-02-22 07:32:24 +0000123 (C == NoConvention && StringsEqualNoCase("copy", s, len)))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000124 C = CreateRule;
125 else // Methods starting with 'init' follow the init rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000126 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000127 C = InitRule;
128 break;
129 }
130
131 // If we aren't in the prefix and have a derived convention then just
132 // return it now.
133 if (!InPossiblePrefix && C != NoConvention)
134 return C;
135
136 AtBeginning = false;
137 s = wordEnd;
138 }
139
140 // We will get here if there wasn't more than one word
141 // after the prefix.
142 return C;
143}
144
Ted Kremenek5c74d502008-10-24 21:18:08 +0000145static bool followsFundamentalRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000146 return deriveNamingConvention(s) == CreateRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000147}
148
149static bool followsReturnRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000150 NamingConvention C = deriveNamingConvention(s);
151 return C == CreateRule || C == InitRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000152}
Ted Kremenek5c74d502008-10-24 21:18:08 +0000153
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000154//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000155// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000156//===----------------------------------------------------------------------===//
157
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000158static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000159 IdentifierInfo* II = &Ctx.Idents.get(name);
160 return Ctx.Selectors.getSelector(0, &II);
161}
162
Ted Kremenek9c32d082008-05-06 00:30:21 +0000163static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
164 IdentifierInfo* II = &Ctx.Idents.get(name);
165 return Ctx.Selectors.getSelector(1, &II);
166}
167
Ted Kremenek553cf182008-06-25 21:21:56 +0000168//===----------------------------------------------------------------------===//
169// Type querying functions.
170//===----------------------------------------------------------------------===//
171
Ted Kremenek12619382009-01-12 21:45:02 +0000172static bool hasPrefix(const char* s, const char* prefix) {
173 if (!prefix)
174 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000175
Ted Kremenek12619382009-01-12 21:45:02 +0000176 char c = *s;
177 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000178
Ted Kremenek12619382009-01-12 21:45:02 +0000179 while (c != '\0' && cP != '\0') {
180 if (c != cP) break;
181 c = *(++s);
182 cP = *(++prefix);
183 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000184
Ted Kremenek12619382009-01-12 21:45:02 +0000185 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000186}
187
Ted Kremenek12619382009-01-12 21:45:02 +0000188static bool hasSuffix(const char* s, const char* suffix) {
189 const char* loc = strstr(s, suffix);
190 return loc && strcmp(suffix, loc) == 0;
191}
192
193static bool isRefType(QualType RetTy, const char* prefix,
194 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek37d785b2008-07-15 16:50:12 +0000195
Ted Kremenek12619382009-01-12 21:45:02 +0000196 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
197 const char* TDName = TD->getDecl()->getIdentifier()->getName();
198 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
199 }
200
201 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000202 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000203
204 // Is the type void*?
205 const PointerType* PT = RetTy->getAsPointerType();
206 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000207 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000208
209 // Does the name start with the prefix?
210 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000211}
212
Ted Kremenek4fd88972008-04-17 18:12:53 +0000213//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000214// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000215//===----------------------------------------------------------------------===//
216
Ted Kremenek553cf182008-06-25 21:21:56 +0000217namespace {
218/// ArgEffect is used to summarize a function/method call's effect on a
219/// particular argument.
Ted Kremenek1c512f52009-02-18 18:54:33 +0000220enum ArgEffect { IncRefMsg, IncRef,
221 DecRefMsg, DecRef,
Ted Kremenek27019002009-02-18 21:57:45 +0000222 MakeCollectable,
Ted Kremenek1c512f52009-02-18 18:54:33 +0000223 DoNothing, DoNothingByRef,
Ted Kremenek070a8252008-07-09 18:11:16 +0000224 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek553cf182008-06-25 21:21:56 +0000225
226/// ArgEffects summarizes the effects of a function/method call on all of
227/// its arguments.
228typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000229}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000230
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000231namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000232template <> struct FoldingSetTrait<ArgEffects> {
233 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
234 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
235 ID.AddInteger(I->first);
236 ID.AddInteger((unsigned) I->second);
237 }
238 }
239};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000240} // end llvm namespace
241
242namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000243
244/// RetEffect is used to summarize a function/method call's behavior with
245/// respect to its return value.
246class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000247public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000248 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
249 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000250
251 enum ObjKind { CF, ObjC, AnyObj };
252
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000253private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000254 Kind K;
255 ObjKind O;
256 unsigned index;
257
258 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
259 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000260
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000261public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000262 Kind getKind() const { return K; }
263
264 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000265
266 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000267 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000268 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000269 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000270
Ted Kremenek553cf182008-06-25 21:21:56 +0000271 static RetEffect MakeAlias(unsigned Idx) {
272 return RetEffect(Alias, Idx);
273 }
274 static RetEffect MakeReceiverAlias() {
275 return RetEffect(ReceiverAlias);
276 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000277 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
278 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000279 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000280 static RetEffect MakeNotOwned(ObjKind o) {
281 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000282 }
283 static RetEffect MakeNoRet() {
284 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000285 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000286
Ted Kremenek553cf182008-06-25 21:21:56 +0000287 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000288 ID.AddInteger((unsigned)K);
289 ID.AddInteger((unsigned)O);
290 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000291 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000292};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000293
Ted Kremenek553cf182008-06-25 21:21:56 +0000294
295class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000296 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
297 /// specifies the argument (starting from 0). This can be sparsely
298 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000299 ArgEffects* Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000300
301 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
302 /// do not have an entry in Args.
303 ArgEffect DefaultArgEffect;
304
Ted Kremenek553cf182008-06-25 21:21:56 +0000305 /// Receiver - If this summary applies to an Objective-C message expression,
306 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000307 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000308
309 /// Ret - The effect on the return value. Used to indicate if the
310 /// function/method call returns a new tracked symbol, returns an
311 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000312 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000313
Ted Kremenek70a733e2008-07-18 17:24:20 +0000314 /// EndPath - Indicates that execution of this method/function should
315 /// terminate the simulation of a path.
316 bool EndPath;
317
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000318public:
319
Ted Kremenek1bffd742008-05-06 15:44:25 +0000320 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000321 ArgEffect ReceiverEff, bool endpath = false)
322 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
323 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000324
Ted Kremenek553cf182008-06-25 21:21:56 +0000325 /// getArg - Return the argument effect on the argument specified by
326 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000327 ArgEffect getArg(unsigned idx) const {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000328
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000329 if (!Args)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000330 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000331
332 // If Args is present, it is likely to contain only 1 element.
333 // Just do a linear search. Do it from the back because functions with
334 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek553cf182008-06-25 21:21:56 +0000335 // argument they actually modify with respect to the reference count.
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000336 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
337 I!=E; ++I) {
338
339 if (idx > I->first)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000340 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000341
342 if (idx == I->first)
343 return I->second;
344 }
345
Ted Kremenek1bffd742008-05-06 15:44:25 +0000346 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000347 }
348
Ted Kremenek553cf182008-06-25 21:21:56 +0000349 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000350 RetEffect getRetEffect() const {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000351 return Ret;
352 }
353
Ted Kremenek70a733e2008-07-18 17:24:20 +0000354 /// isEndPath - Returns true if executing the given method/function should
355 /// terminate the path.
356 bool isEndPath() const { return EndPath; }
357
Ted Kremenek553cf182008-06-25 21:21:56 +0000358 /// getReceiverEffect - Returns the effect on the receiver of the call.
359 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000360 ArgEffect getReceiverEffect() const {
361 return Receiver;
362 }
363
Ted Kremenek55499762008-06-17 02:43:46 +0000364 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000365
Ted Kremenek55499762008-06-17 02:43:46 +0000366 ExprIterator begin_args() const { return Args->begin(); }
367 ExprIterator end_args() const { return Args->end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000368
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000369 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000370 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000371 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000372 ID.AddPointer(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000373 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000374 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000375 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000376 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000377 }
378
379 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000380 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000381 }
382};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000383} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000384
Ted Kremenek553cf182008-06-25 21:21:56 +0000385//===----------------------------------------------------------------------===//
386// Data structures for constructing summaries.
387//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000388
Ted Kremenek553cf182008-06-25 21:21:56 +0000389namespace {
390class VISIBILITY_HIDDEN ObjCSummaryKey {
391 IdentifierInfo* II;
392 Selector S;
393public:
394 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
395 : II(ii), S(s) {}
396
397 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
398 : II(d ? d->getIdentifier() : 0), S(s) {}
399
400 ObjCSummaryKey(Selector s)
401 : II(0), S(s) {}
402
403 IdentifierInfo* getIdentifier() const { return II; }
404 Selector getSelector() const { return S; }
405};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000406}
407
408namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000409template <> struct DenseMapInfo<ObjCSummaryKey> {
410 static inline ObjCSummaryKey getEmptyKey() {
411 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
412 DenseMapInfo<Selector>::getEmptyKey());
413 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000414
Ted Kremenek553cf182008-06-25 21:21:56 +0000415 static inline ObjCSummaryKey getTombstoneKey() {
416 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
417 DenseMapInfo<Selector>::getTombstoneKey());
418 }
419
420 static unsigned getHashValue(const ObjCSummaryKey &V) {
421 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
422 & 0x88888888)
423 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
424 & 0x55555555);
425 }
426
427 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
428 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
429 RHS.getIdentifier()) &&
430 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
431 RHS.getSelector());
432 }
433
434 static bool isPod() {
435 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
436 DenseMapInfo<Selector>::isPod();
437 }
438};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000439} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000440
Ted Kremenek4f22a782008-06-23 23:30:29 +0000441namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000442class VISIBILITY_HIDDEN ObjCSummaryCache {
443 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
444 MapTy M;
445public:
446 ObjCSummaryCache() {}
447
448 typedef MapTy::iterator iterator;
449
450 iterator find(ObjCInterfaceDecl* D, Selector S) {
451
452 // Do a lookup with the (D,S) pair. If we find a match return
453 // the iterator.
454 ObjCSummaryKey K(D, S);
455 MapTy::iterator I = M.find(K);
456
457 if (I != M.end() || !D)
458 return I;
459
460 // Walk the super chain. If we find a hit with a parent, we'll end
461 // up returning that summary. We actually allow that key (null,S), as
462 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
463 // generate initial summaries without having to worry about NSObject
464 // being declared.
465 // FIXME: We may change this at some point.
466 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
467 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
468 break;
469
470 if (!C)
471 return I;
472 }
473
474 // Cache the summary with original key to make the next lookup faster
475 // and return the iterator.
476 M[K] = I->second;
477 return I;
478 }
479
Ted Kremenek98530452008-08-12 20:41:56 +0000480
Ted Kremenek553cf182008-06-25 21:21:56 +0000481 iterator find(Expr* Receiver, Selector S) {
482 return find(getReceiverDecl(Receiver), S);
483 }
484
485 iterator find(IdentifierInfo* II, Selector S) {
486 // FIXME: Class method lookup. Right now we dont' have a good way
487 // of going between IdentifierInfo* and the class hierarchy.
488 iterator I = M.find(ObjCSummaryKey(II, S));
489 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
490 }
491
492 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
493
494 const PointerType* PT = E->getType()->getAsPointerType();
495 if (!PT) return 0;
496
497 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
498 if (!OI) return 0;
499
500 return OI ? OI->getDecl() : 0;
501 }
502
503 iterator end() { return M.end(); }
504
505 RetainSummary*& operator[](ObjCMessageExpr* ME) {
506
507 Selector S = ME->getSelector();
508
509 if (Expr* Receiver = ME->getReceiver()) {
510 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
511 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
512 }
513
514 return M[ObjCSummaryKey(ME->getClassName(), S)];
515 }
516
517 RetainSummary*& operator[](ObjCSummaryKey K) {
518 return M[K];
519 }
520
521 RetainSummary*& operator[](Selector S) {
522 return M[ ObjCSummaryKey(S) ];
523 }
524};
525} // end anonymous namespace
526
527//===----------------------------------------------------------------------===//
528// Data structures for managing collections of summaries.
529//===----------------------------------------------------------------------===//
530
531namespace {
532class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000533
534 //==-----------------------------------------------------------------==//
535 // Typedefs.
536 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000537
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000538 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
539 ArgEffectsSetTy;
540
541 typedef llvm::FoldingSet<RetainSummary>
542 SummarySetTy;
543
544 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
545 FuncSummariesTy;
546
Ted Kremenek4f22a782008-06-23 23:30:29 +0000547 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000548
549 //==-----------------------------------------------------------------==//
550 // Data.
551 //==-----------------------------------------------------------------==//
552
Ted Kremenek553cf182008-06-25 21:21:56 +0000553 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000554 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000555
Ted Kremenek070a8252008-07-09 18:11:16 +0000556 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
557 /// "CFDictionaryCreate".
558 IdentifierInfo* CFDictionaryCreateII;
559
Ted Kremenek553cf182008-06-25 21:21:56 +0000560 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000561 const bool GCEnabled;
562
Ted Kremenek553cf182008-06-25 21:21:56 +0000563 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +0000564 SummarySetTy SummarySet;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000565
Ted Kremenek553cf182008-06-25 21:21:56 +0000566 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000567 FuncSummariesTy FuncSummaries;
568
Ted Kremenek553cf182008-06-25 21:21:56 +0000569 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
570 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000571 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000572
Ted Kremenek553cf182008-06-25 21:21:56 +0000573 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000574 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000575
Ted Kremenek553cf182008-06-25 21:21:56 +0000576 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000577 ArgEffectsSetTy ArgEffectsSet;
578
Ted Kremenek553cf182008-06-25 21:21:56 +0000579 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
580 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000581 llvm::BumpPtrAllocator BPAlloc;
582
Ted Kremenek553cf182008-06-25 21:21:56 +0000583 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000584 ArgEffects ScratchArgs;
585
Ted Kremenek432af592008-05-06 18:11:36 +0000586 RetainSummary* StopSummary;
587
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000588 //==-----------------------------------------------------------------==//
589 // Methods.
590 //==-----------------------------------------------------------------==//
591
Ted Kremenek553cf182008-06-25 21:21:56 +0000592 /// getArgEffects - Returns a persistent ArgEffects object based on the
593 /// data in ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000594 ArgEffects* getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000595
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000596 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000597
598public:
Ted Kremenek12619382009-01-12 21:45:02 +0000599 RetainSummary* getUnarySummary(FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000600
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000601 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
602 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000603 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000604
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000605 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000606 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000607 ArgEffect DefaultEff = MayEscape,
608 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000609
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000610 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000611 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000612 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000613 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000614 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000615
Ted Kremenek1bffd742008-05-06 15:44:25 +0000616 RetainSummary* getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000617 if (StopSummary)
618 return StopSummary;
619
620 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
621 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000622
Ted Kremenek432af592008-05-06 18:11:36 +0000623 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000624 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000625
Ted Kremenek553cf182008-06-25 21:21:56 +0000626 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000627
Ted Kremenek1f180c32008-06-23 22:21:20 +0000628 void InitializeClassMethodSummaries();
629 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000630
Ted Kremenek234a4c22009-01-07 00:39:56 +0000631 bool isTrackedObjectType(QualType T);
632
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000633private:
634
Ted Kremenek70a733e2008-07-18 17:24:20 +0000635 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
636 RetainSummary* Summ) {
637 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
638 }
639
Ted Kremenek553cf182008-06-25 21:21:56 +0000640 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
641 ObjCClassMethodSummaries[S] = Summ;
642 }
643
644 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
645 ObjCMethodSummaries[S] = Summ;
646 }
647
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000648 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenek70a733e2008-07-18 17:24:20 +0000649
Ted Kremenek9e476de2008-08-12 18:30:56 +0000650 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
651 llvm::SmallVector<IdentifierInfo*, 10> II;
652
653 while (const char* s = va_arg(argp, const char*))
654 II.push_back(&Ctx.Idents.get(s));
655
656 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek70a733e2008-07-18 17:24:20 +0000657 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
658 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000659
660 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
661 va_list argp;
662 va_start(argp, Summ);
663 addInstMethSummary(Cls, Summ, argp);
664 va_end(argp);
665 }
Ted Kremenek9e476de2008-08-12 18:30:56 +0000666
667 void addPanicSummary(const char* Cls, ...) {
668 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
669 DoNothing, DoNothing, true);
670 va_list argp;
671 va_start (argp, Cls);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000672 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000673 va_end(argp);
674 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000675
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000676public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000677
678 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000679 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000680 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek553cf182008-06-25 21:21:56 +0000681 GCEnabled(gcenabled), StopSummary(0) {
682
683 InitializeClassMethodSummaries();
684 InitializeMethodSummaries();
685 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000686
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000687 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000688
Ted Kremenekab592272008-06-24 03:56:45 +0000689 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek553cf182008-06-25 21:21:56 +0000690 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek1f180c32008-06-23 22:21:20 +0000691 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenekb3095252008-05-06 04:20:12 +0000692
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000693 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000694};
695
696} // end anonymous namespace
697
698//===----------------------------------------------------------------------===//
699// Implementation of checker data structures.
700//===----------------------------------------------------------------------===//
701
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000702RetainSummaryManager::~RetainSummaryManager() {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000703
704 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
705 // mitigating the need to do explicit cleanup of the
706 // Argument-Effect summaries.
707
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000708 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
709 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000710 I->getValue().~ArgEffects();
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000711}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000712
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000713ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000714
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000715 if (ScratchArgs.empty())
716 return NULL;
717
718 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000719 llvm::FoldingSetNodeID profile;
720 profile.Add(ScratchArgs);
721 void* InsertPos;
722
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000723 // Look up the uniqued copy, or create a new one.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000724 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000725 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000726
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000727 if (E) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000728 ScratchArgs.clear();
729 return &E->getValue();
730 }
731
732 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek553cf182008-06-25 21:21:56 +0000733 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000734
735 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000736 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000737
738 ScratchArgs.clear();
739 return &E->getValue();
740}
741
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000742RetainSummary*
743RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000744 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000745 ArgEffect DefaultEff,
746 bool isEndPath) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000747
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000748 // Generate a profile for the summary.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000749 llvm::FoldingSetNodeID profile;
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000750 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
751 isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000752
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000753 // Look up the uniqued summary, or create one if it doesn't exist.
754 void* InsertPos;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000755 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000756
757 if (Summ)
758 return Summ;
759
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000760 // Create the summary and return it.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000761 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000762 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000763 SummarySet.InsertNode(Summ, InsertPos);
764
765 return Summ;
766}
767
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000768//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000769// Predicates.
770//===----------------------------------------------------------------------===//
771
772bool RetainSummaryManager::isTrackedObjectType(QualType T) {
773 if (!Ctx.isObjCObjectPointerType(T))
774 return false;
775
776 // Does it subclass NSObject?
777 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
778
779 // We assume that id<..>, id, and "Class" all represent tracked objects.
780 if (!OT)
781 return true;
782
783 // Does the object type subclass NSObject?
784 // FIXME: We can memoize here if this gets too expensive.
785 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
786 ObjCInterfaceDecl* ID = OT->getDecl();
787
788 for ( ; ID ; ID = ID->getSuperClass())
789 if (ID->getIdentifier() == NSObjectII)
790 return true;
791
792 return false;
793}
794
795//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000796// Summary creation for functions (largely uses of Core Foundation).
797//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000798
Ted Kremenek12619382009-01-12 21:45:02 +0000799static bool isRetain(FunctionDecl* FD, const char* FName) {
800 const char* loc = strstr(FName, "Retain");
801 return loc && loc[sizeof("Retain")-1] == '\0';
802}
803
804static bool isRelease(FunctionDecl* FD, const char* FName) {
805 const char* loc = strstr(FName, "Release");
806 return loc && loc[sizeof("Release")-1] == '\0';
807}
808
Ted Kremenekab592272008-06-24 03:56:45 +0000809RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000810
811 SourceLocation Loc = FD->getLocation();
812
813 if (!Loc.isFileID())
814 return NULL;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000815
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000816 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000817 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000818
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000819 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000820 return I->second;
821
822 // No summary. Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000823 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000824
Ted Kremenek37d785b2008-07-15 16:50:12 +0000825 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000826 // We generate "stop" summaries for implicitly defined functions.
827 if (FD->isImplicit()) {
828 S = getPersistentStopSummary();
829 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000830 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000831
Ted Kremenek99890652009-01-16 18:40:33 +0000832 // [PR 3337] Use 'getDesugaredType' to strip away any typedefs on the
833 // function's type.
834 FunctionType* FT = cast<FunctionType>(FD->getType()->getDesugaredType());
Ted Kremenek12619382009-01-12 21:45:02 +0000835 const char* FName = FD->getIdentifier()->getName();
836
837 // Inspect the result type.
838 QualType RetTy = FT->getResultType();
839
840 // FIXME: This should all be refactored into a chain of "summary lookup"
841 // filters.
842 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
843 // FIXES: <rdar://problem/6326900>
844 // This should be addressed using a API table. This strcmp is also
845 // a little gross, but there is no need to super optimize here.
846 assert (ScratchArgs.empty());
847 ScratchArgs.push_back(std::make_pair(1, DecRef));
848 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
849 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000850 }
Ted Kremenek12619382009-01-12 21:45:02 +0000851
852 // Handle: id NSMakeCollectable(CFTypeRef)
853 if (strcmp(FName, "NSMakeCollectable") == 0) {
854 S = (RetTy == Ctx.getObjCIdType())
855 ? getUnarySummary(FT, cfmakecollectable)
856 : getPersistentStopSummary();
857
858 break;
859 }
860
861 if (RetTy->isPointerType()) {
862 // For CoreFoundation ('CF') types.
863 if (isRefType(RetTy, "CF", &Ctx, FName)) {
864 if (isRetain(FD, FName))
865 S = getUnarySummary(FT, cfretain);
866 else if (strstr(FName, "MakeCollectable"))
867 S = getUnarySummary(FT, cfmakecollectable);
868 else
869 S = getCFCreateGetRuleSummary(FD, FName);
870
871 break;
872 }
873
874 // For CoreGraphics ('CG') types.
875 if (isRefType(RetTy, "CG", &Ctx, FName)) {
876 if (isRetain(FD, FName))
877 S = getUnarySummary(FT, cfretain);
878 else
879 S = getCFCreateGetRuleSummary(FD, FName);
880
881 break;
882 }
883
884 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
885 if (isRefType(RetTy, "DADisk") ||
886 isRefType(RetTy, "DADissenter") ||
887 isRefType(RetTy, "DASessionRef")) {
888 S = getCFCreateGetRuleSummary(FD, FName);
889 break;
890 }
891
892 break;
893 }
894
895 // Check for release functions, the only kind of functions that we care
896 // about that don't return a pointer type.
897 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
898 if (isRelease(FD, FName+2))
899 S = getUnarySummary(FT, cfrelease);
900 else {
Ted Kremenek68189282009-01-29 22:45:13 +0000901 assert (ScratchArgs.empty());
902 // Remaining CoreFoundation and CoreGraphics functions.
903 // We use to assume that they all strictly followed the ownership idiom
904 // and that ownership cannot be transferred. While this is technically
905 // correct, many methods allow a tracked object to escape. For example:
906 //
907 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
908 // CFDictionaryAddValue(y, key, x);
909 // CFRelease(x);
910 // ... it is okay to use 'x' since 'y' has a reference to it
911 //
912 // We handle this and similar cases with the follow heuristic. If the
913 // function name contains "InsertValue", "SetValue" or "AddValue" then
914 // we assume that arguments may "escape."
915 //
916 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
917 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +0000918 CStrInCStrNoCase(FName, "SetValue") ||
919 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +0000920 ? MayEscape : DoNothing;
921
922 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +0000923 }
924 }
Ted Kremenek37d785b2008-07-15 16:50:12 +0000925 }
926 while (0);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000927
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000928 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000929 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000930}
931
Ted Kremenek37d785b2008-07-15 16:50:12 +0000932RetainSummary*
933RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
934 const char* FName) {
935
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000936 if (strstr(FName, "Create") || strstr(FName, "Copy"))
937 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000938
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000939 if (strstr(FName, "Get"))
940 return getCFSummaryGetRule(FD);
941
942 return 0;
943}
944
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000945RetainSummary*
Ted Kremenek12619382009-01-12 21:45:02 +0000946RetainSummaryManager::getUnarySummary(FunctionType* FT, UnaryFuncKind func) {
947 // Sanity check that this is *really* a unary function. This can
948 // happen if people do weird things.
949 FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FT);
950 if (!FTP || FTP->getNumArgs() != 1)
951 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000952
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000953 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000954
Ted Kremenek377e2302008-04-29 05:33:51 +0000955 switch (func) {
Ted Kremenek12619382009-01-12 21:45:02 +0000956 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000957 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000958 return getPersistentSummary(RetEffect::MakeAlias(0),
959 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000960 }
961
962 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000963 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000964 return getPersistentSummary(RetEffect::MakeNoRet(),
965 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000966 }
967
968 case cfmakecollectable: {
Ted Kremenek27019002009-02-18 21:57:45 +0000969 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
970 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000971 }
972
973 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000974 assert (false && "Not a supported unary function.");
Ted Kremenek98530452008-08-12 20:41:56 +0000975 return 0;
Ted Kremenek940b1d82008-04-10 23:44:06 +0000976 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000977}
978
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000979RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000980 assert (ScratchArgs.empty());
Ted Kremenek070a8252008-07-09 18:11:16 +0000981
982 if (FD->getIdentifier() == CFDictionaryCreateII) {
983 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
984 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
985 }
986
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000987 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000988}
989
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000990RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000991 assert (ScratchArgs.empty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000992 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
993 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000994}
995
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000996//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000997// Summary creation for Selectors.
998//===----------------------------------------------------------------------===//
999
Ted Kremenek1bffd742008-05-06 15:44:25 +00001000RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001001RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001002 assert(ScratchArgs.empty());
1003
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001004 // 'init' methods only return an alias if the return type is a location type.
1005 QualType T = ME->getType();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001006 RetainSummary* Summ =
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001007 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1008 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001009
Ted Kremenek553cf182008-06-25 21:21:56 +00001010 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001011 return Summ;
1012}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001013
Ted Kremenek553cf182008-06-25 21:21:56 +00001014
Ted Kremenek1bffd742008-05-06 15:44:25 +00001015RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001016RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1017 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001018
1019 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001020
Ted Kremenek553cf182008-06-25 21:21:56 +00001021 // Look up a summary in our summary cache.
1022 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001023
Ted Kremenek1f180c32008-06-23 22:21:20 +00001024 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001025 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001026
Ted Kremenek234a4c22009-01-07 00:39:56 +00001027 // "initXXX": pass-through for receiver.
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001028 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001029 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +00001030
Ted Kremenekb80976c2009-02-21 05:13:43 +00001031 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek234a4c22009-01-07 00:39:56 +00001032 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +00001033
Ted Kremenek234a4c22009-01-07 00:39:56 +00001034 // Look for methods that return an owned object.
1035 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek84060db2008-05-07 04:25:59 +00001036 return 0;
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001037
Ted Kremenek234a4c22009-01-07 00:39:56 +00001038 if (followsFundamentalRule(s)) {
1039 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001040 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001041 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek553cf182008-06-25 21:21:56 +00001042 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek1bffd742008-05-06 15:44:25 +00001043 return Summ;
1044 }
Ted Kremenek1bffd742008-05-06 15:44:25 +00001045
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001046 return 0;
1047}
1048
Ted Kremenekc8395602008-05-06 21:26:51 +00001049RetainSummary*
Ted Kremenek1f180c32008-06-23 22:21:20 +00001050RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1051 Selector S) {
Ted Kremenekc8395602008-05-06 21:26:51 +00001052
Ted Kremenek553cf182008-06-25 21:21:56 +00001053 // FIXME: Eventually we should properly do class method summaries, but
1054 // it requires us being able to walk the type hierarchy. Unfortunately,
1055 // we cannot do this with just an IdentifierInfo* for the class name.
1056
Ted Kremenekc8395602008-05-06 21:26:51 +00001057 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +00001058 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001059
Ted Kremenek1f180c32008-06-23 22:21:20 +00001060 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001061 return I->second;
1062
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00001063 return 0;
Ted Kremenekc8395602008-05-06 21:26:51 +00001064}
1065
Ted Kremenek1f180c32008-06-23 22:21:20 +00001066void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +00001067
1068 assert (ScratchArgs.empty());
1069
Ted Kremeneka7344702008-06-23 18:02:52 +00001070 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001071 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001072
Ted Kremenek9c32d082008-05-06 00:30:21 +00001073 RetainSummary* Summ = getPersistentSummary(E);
1074
Ted Kremenek553cf182008-06-25 21:21:56 +00001075 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1076 // NSObject and its derivatives.
1077 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1078 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1079 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001080
1081 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001082 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001083 GetNullarySelector("currentHandler", Ctx),
1084 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001085
1086 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekabf43972009-01-28 21:44:40 +00001087 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1088 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1089 GetUnarySelector("addObject", Ctx),
1090 getPersistentSummary(RetEffect::MakeNoRet(),
1091 DoNothing, DoNothing));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001092}
1093
Ted Kremenek1f180c32008-06-23 22:21:20 +00001094void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001095
1096 assert (ScratchArgs.empty());
1097
Ted Kremenekc8395602008-05-06 21:26:51 +00001098 // Create the "init" selector. It just acts as a pass-through for the
1099 // receiver.
Ted Kremenek179064e2008-07-01 17:21:27 +00001100 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
1101 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001102
1103 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +00001104 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001105 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001106
Ted Kremenek179064e2008-07-01 17:21:27 +00001107 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +00001108
1109 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001110 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1111
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001112 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001113 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001114
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001115 // Create the "retain" selector.
1116 E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001117 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001118 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001119
1120 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001121 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001122 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001123
1124 // Create the "drain" selector.
1125 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001126 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001127
1128 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001129 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001130 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001131
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001132 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek179064e2008-07-01 17:21:27 +00001133 RetainSummary *NSWindowSumm =
1134 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001135
1136 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1137 "styleMask", "backing", "defer", NULL);
1138
1139 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1140 "styleMask", "backing", "defer", "screen", NULL);
1141
1142 // For NSPanel (which subclasses NSWindow), allocated objects are not
1143 // self-owned.
1144 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1145 "styleMask", "backing", "defer", NULL);
1146
1147 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1148 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001149
Ted Kremenek70a733e2008-07-18 17:24:20 +00001150 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001151 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1152 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001153
Ted Kremenek9e476de2008-08-12 18:30:56 +00001154 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1155 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001156}
1157
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001158//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001159// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001160//===----------------------------------------------------------------------===//
1161
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001162namespace {
1163
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001164class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001165public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001166 enum Kind {
1167 Owned = 0, // Owning reference.
1168 NotOwned, // Reference is not owned by still valid (not freed).
1169 Released, // Object has been released.
1170 ReturnedOwned, // Returned object passes ownership to caller.
1171 ReturnedNotOwned, // Return object does not pass ownership to caller.
1172 ErrorUseAfterRelease, // Object used after released.
1173 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001174 ErrorLeak, // A memory leak due to excessive reference counts.
1175 ErrorLeakReturned // A memory leak due to the returning method not having
1176 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001177 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001178
1179private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001180 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001181 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001182 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001183 QualType T;
1184
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001185 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1186 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001187
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001188 RefVal(Kind k, unsigned cnt = 0)
1189 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1190
1191public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001192 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001193
1194 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001195
Ted Kremenek553cf182008-06-25 21:21:56 +00001196 unsigned getCount() const { return Cnt; }
1197 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001198
1199 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001200
Ted Kremenek73c750b2008-03-11 18:14:09 +00001201 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1202
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001203 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001204
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001205 bool isOwned() const {
1206 return getKind() == Owned;
1207 }
1208
Ted Kremenekdb863712008-04-16 22:32:20 +00001209 bool isNotOwned() const {
1210 return getKind() == NotOwned;
1211 }
1212
Ted Kremenek4fd88972008-04-17 18:12:53 +00001213 bool isReturnedOwned() const {
1214 return getKind() == ReturnedOwned;
1215 }
1216
1217 bool isReturnedNotOwned() const {
1218 return getKind() == ReturnedNotOwned;
1219 }
1220
1221 bool isNonLeakError() const {
1222 Kind k = getKind();
1223 return isError(k) && !isLeak(k);
1224 }
1225
1226 // State creation: normal state.
1227
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001228 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1229 unsigned Count = 1) {
1230 return RefVal(Owned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001231 }
1232
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001233 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1234 unsigned Count = 0) {
1235 return RefVal(NotOwned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001236 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001237
1238 static RefVal makeReturnedOwned(unsigned Count) {
1239 return RefVal(ReturnedOwned, Count);
1240 }
1241
1242 static RefVal makeReturnedNotOwned() {
1243 return RefVal(ReturnedNotOwned);
1244 }
1245
Ted Kremenek4fd88972008-04-17 18:12:53 +00001246 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001247
Ted Kremenek4fd88972008-04-17 18:12:53 +00001248 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001249 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001250 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001251
Ted Kremenek553cf182008-06-25 21:21:56 +00001252 RefVal operator-(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001253 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001254 }
1255
1256 RefVal operator+(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001257 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001258 }
1259
1260 RefVal operator^(Kind k) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001261 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001262 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001263
Ted Kremenek4fd88972008-04-17 18:12:53 +00001264 void Profile(llvm::FoldingSetNodeID& ID) const {
1265 ID.AddInteger((unsigned) kind);
1266 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001267 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001268 }
1269
Ted Kremenekf3948042008-03-11 19:44:10 +00001270 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001271};
Ted Kremenekf3948042008-03-11 19:44:10 +00001272
1273void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001274 if (!T.isNull())
1275 Out << "Tracked Type:" << T.getAsString() << '\n';
1276
Ted Kremenekf3948042008-03-11 19:44:10 +00001277 switch (getKind()) {
1278 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001279 case Owned: {
1280 Out << "Owned";
1281 unsigned cnt = getCount();
1282 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001283 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001284 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001285
Ted Kremenek61b9f872008-04-10 23:09:18 +00001286 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001287 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001288 unsigned cnt = getCount();
1289 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001290 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001291 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001292
Ted Kremenek4fd88972008-04-17 18:12:53 +00001293 case ReturnedOwned: {
1294 Out << "ReturnedOwned";
1295 unsigned cnt = getCount();
1296 if (cnt) Out << " (+ " << cnt << ")";
1297 break;
1298 }
1299
1300 case ReturnedNotOwned: {
1301 Out << "ReturnedNotOwned";
1302 unsigned cnt = getCount();
1303 if (cnt) Out << " (+ " << cnt << ")";
1304 break;
1305 }
1306
Ted Kremenekf3948042008-03-11 19:44:10 +00001307 case Released:
1308 Out << "Released";
1309 break;
1310
Ted Kremenekdb863712008-04-16 22:32:20 +00001311 case ErrorLeak:
1312 Out << "Leaked";
1313 break;
1314
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001315 case ErrorLeakReturned:
1316 Out << "Leaked (Bad naming)";
1317 break;
1318
Ted Kremenekf3948042008-03-11 19:44:10 +00001319 case ErrorUseAfterRelease:
1320 Out << "Use-After-Release [ERROR]";
1321 break;
1322
1323 case ErrorReleaseNotOwned:
1324 Out << "Release of Not-Owned [ERROR]";
1325 break;
1326 }
1327}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001328
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001329} // end anonymous namespace
1330
1331//===----------------------------------------------------------------------===//
1332// RefBindings - State used to track object reference counts.
1333//===----------------------------------------------------------------------===//
1334
Ted Kremenek2dabd432008-12-05 02:27:51 +00001335typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001336static int RefBIndex = 0;
Ted Kremenek33b6f632009-02-19 23:47:02 +00001337static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001338
1339namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001340 template<>
1341 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1342 static inline void* GDMIndex() { return &RefBIndex; }
1343 };
1344}
Ted Kremenek6d348932008-10-21 15:53:15 +00001345
1346//===----------------------------------------------------------------------===//
1347// ARBindings - State used to track objects in autorelease pools.
1348//===----------------------------------------------------------------------===//
1349
Ted Kremenek2dabd432008-12-05 02:27:51 +00001350typedef llvm::ImmutableSet<SymbolRef> ARPoolContents;
1351typedef llvm::ImmutableList< std::pair<SymbolRef, ARPoolContents*> > ARBindings;
Ted Kremenek6d348932008-10-21 15:53:15 +00001352static int AutoRBIndex = 0;
1353
1354namespace clang {
1355 template<>
1356 struct GRStateTrait<ARBindings> : public GRStatePartialTrait<ARBindings> {
1357 static inline void* GDMIndex() { return &AutoRBIndex; }
1358 };
1359}
1360
Ted Kremenek13922612008-04-16 20:40:59 +00001361//===----------------------------------------------------------------------===//
1362// Transfer functions.
1363//===----------------------------------------------------------------------===//
1364
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001365namespace {
1366
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001367class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001368public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001369 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001370 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001371 virtual void Print(std::ostream& Out, const GRState* state,
1372 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001373 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001374
1375private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001376 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1377 SummaryLogTy;
1378
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001379 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001380 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001381 const LangOptions& LOpts;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001382
Ted Kremenekcf701772009-02-05 06:50:21 +00001383 BugType *useAfterRelease, *releaseNotOwned;
1384 BugType *leakWithinFunction, *leakAtReturn;
1385 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001386
Ted Kremenek2dabd432008-12-05 02:27:51 +00001387 RefBindings Update(RefBindings B, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001388 RefVal::Kind& hasErr, RefBindings::Factory& RefBFactory);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001389
Ted Kremenek2dabd432008-12-05 02:27:51 +00001390 RefVal::Kind& Update(GRStateRef& state, SymbolRef sym, RefVal V,
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001391 ArgEffect E, RefVal::Kind& hasErr) {
1392
1393 state = state.set<RefBindings>(Update(state.get<RefBindings>(), sym, V,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001394 E, hasErr,
1395 state.get_context<RefBindings>()));
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001396 return hasErr;
1397 }
1398
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001399 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1400 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001401 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001402 ExplodedNode<GRState>* Pred,
1403 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001404 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001405
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001406 std::pair<GRStateRef, bool>
1407 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001408 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenekdb863712008-04-16 22:32:20 +00001409
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001410public:
Ted Kremenek13922612008-04-16 20:40:59 +00001411
Ted Kremenek78d46242008-07-22 16:21:24 +00001412 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001413 : Summaries(Ctx, gcenabled),
Ted Kremenekcf701772009-02-05 06:50:21 +00001414 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1415 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001416
Ted Kremenekcf701772009-02-05 06:50:21 +00001417 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001418
Ted Kremenekcf118d42009-02-04 23:49:09 +00001419 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001420
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001421 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1422 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001423 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001424
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001425 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001426 const LangOptions& getLangOptions() const { return LOpts; }
1427
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001428 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1429 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1430 return I == SummaryLog.end() ? 0 : I->second;
1431 }
1432
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001433 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001434
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001435 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001436 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001437 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001438 Expr* Ex,
1439 Expr* Receiver,
1440 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001441 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001442 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001443
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001444 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001445 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001446 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001447 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001448 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001449
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001450
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001451 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001452 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001453 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001454 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001455 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001456
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001457 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001458 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001459 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001460 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001461 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001462
Ted Kremenek41573eb2009-02-14 01:43:44 +00001463 // Stores.
1464 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1465
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001466 // End-of-path.
1467
1468 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001469 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001470
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001471 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001472 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001473 GRStmtNodeBuilder<GRState>& Builder,
1474 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001475 Stmt* S, const GRState* state,
1476 SymbolReaper& SymReaper);
1477
Ted Kremenek4fd88972008-04-17 18:12:53 +00001478 // Return statements.
1479
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001480 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001481 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001482 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001483 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001484 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001485
1486 // Assumptions.
1487
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001488 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001489 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001490 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001491};
1492
1493} // end anonymous namespace
1494
Ted Kremenek8dd56462008-04-18 03:39:05 +00001495
Ted Kremenekae6814e2008-08-13 21:24:49 +00001496void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1497 const char* nl, const char* sep) {
1498
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001499 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001500
Ted Kremenekae6814e2008-08-13 21:24:49 +00001501 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001502 Out << sep << nl;
1503
1504 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1505 Out << (*I).first << " : ";
1506 (*I).second.print(Out);
1507 Out << nl;
1508 }
1509}
1510
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001511static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001512 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001513}
1514
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001515static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1516 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001517}
1518
Ted Kremenek14993892008-05-06 02:41:27 +00001519static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1520 return Summ ? Summ->getReceiverEffect() : DoNothing;
1521}
1522
Ted Kremenek70a733e2008-07-18 17:24:20 +00001523static inline bool IsEndPath(RetainSummary* Summ) {
1524 return Summ ? Summ->isEndPath() : false;
1525}
1526
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001527
Ted Kremenek553cf182008-06-25 21:21:56 +00001528/// GetReturnType - Used to get the return type of a message expression or
1529/// function call with the intention of affixing that type to a tracked symbol.
1530/// While the the return type can be queried directly from RetEx, when
1531/// invoking class methods we augment to the return type to be that of
1532/// a pointer to the class (as opposed it just being id).
1533static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1534
1535 QualType RetTy = RetE->getType();
1536
1537 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00001538 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001539 if (!PT)
1540 return RetTy;
1541
1542 // If RetEx is not a message expression just return its type.
1543 // If RetEx is a message expression, return its types if it is something
1544 /// more specific than id.
1545
1546 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1547
Steve Naroff389bf462009-02-12 17:52:19 +00001548 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00001549 return RetTy;
1550
1551 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1552
1553 // At this point we know the return type of the message expression is id.
1554 // If we have an ObjCInterceDecl, we know this is a call to a class method
1555 // whose type we can resolve. In such cases, promote the return type to
1556 // Class*.
1557 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1558}
1559
1560
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001561void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001562 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001563 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001564 Expr* Ex,
1565 Expr* Receiver,
1566 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001567 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001568 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001569
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001570 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001571 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001572 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00001573
1574 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001575 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001576 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001577 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00001578 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001579
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001580 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001581 SVal V = state.GetSVal(*I);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001582
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001583 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001584 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001585 if (RefBindings::data_type* T = state.get<RefBindings>(Sym))
1586 if (Update(state, Sym, *T, GetArgE(Summ, idx), hasErr)) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001587 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001588 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001589 break;
1590 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001591 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001592 else if (isa<Loc>(V)) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001593 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek070a8252008-07-09 18:11:16 +00001594
1595 if (GetArgE(Summ, idx) == DoNothingByRef)
1596 continue;
1597
1598 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001599
1600 // FIXME: Either this logic should also be replicated in GRSimpleVals
1601 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00001602
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001603 // FIXME: We can have collisions on the conjured symbol if the
1604 // expression *I also creates conjured symbols. We probably want
1605 // to identify conjured symbols by an expression pair: the enclosing
1606 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00001607 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00001608
Ted Kremenek993f1c72008-10-17 20:28:54 +00001609 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek90b32362008-12-17 19:42:34 +00001610
1611 // Blast through AnonTypedRegions to get the original region type.
1612 while (R) {
1613 const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R);
1614 if (!ATR) break;
1615 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1616 }
1617
Ted Kremenek9e240492008-10-04 05:50:14 +00001618 if (R) {
Ted Kremenek40e86d92008-12-18 23:34:57 +00001619
1620 // Is the invalidated variable something that we were tracking?
1621 SVal X = state.GetSVal(Loc::MakeVal(R));
1622
1623 if (isa<loc::SymbolVal>(X)) {
1624 SymbolRef Sym = cast<loc::SymbolVal>(X).getSymbol();
1625 state = state.remove<RefBindings>(Sym);
1626 }
1627
Ted Kremenek9e240492008-10-04 05:50:14 +00001628 // Set the value of the variable to be a conjured symbol.
1629 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek6eddeb12008-12-13 21:49:13 +00001630 QualType T = R->getRValueType(Ctx);
Ted Kremenek9e240492008-10-04 05:50:14 +00001631
Ted Kremenekfd301942008-10-17 22:23:12 +00001632 // FIXME: handle structs.
Ted Kremenek062e2f92008-11-13 06:10:40 +00001633 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001634 SymbolRef NewSym =
Ted Kremenekfd301942008-10-17 22:23:12 +00001635 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1636
Ted Kremenek90b32362008-12-17 19:42:34 +00001637 state = state.BindLoc(Loc::MakeVal(R),
Ted Kremenekfd301942008-10-17 22:23:12 +00001638 Loc::IsLocType(T)
1639 ? cast<SVal>(loc::SymbolVal(NewSym))
1640 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1641 }
1642 else {
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001643 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenekfd301942008-10-17 22:23:12 +00001644 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001645 }
1646 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001647 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001648 }
1649 else {
1650 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001651 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001652 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001653 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001654 else if (isa<nonloc::LocAsInteger>(V))
1655 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001656 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001657
Ted Kremenek553cf182008-06-25 21:21:56 +00001658 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001659 if (!ErrorExpr && Receiver) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001660 SVal V = state.GetSVal(Receiver);
1661 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001662 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001663 if (const RefVal* T = state.get<RefBindings>(Sym))
1664 if (Update(state, Sym, *T, GetReceiverE(Summ), hasErr)) {
Ted Kremenek14993892008-05-06 02:41:27 +00001665 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001666 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00001667 }
Ted Kremenek14993892008-05-06 02:41:27 +00001668 }
1669 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001670
Ted Kremenek553cf182008-06-25 21:21:56 +00001671 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001672 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001673 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001674 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001675 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001676 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001677
Ted Kremenek70a733e2008-07-18 17:24:20 +00001678 // Consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001679 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001680
1681 switch (RE.getKind()) {
1682 default:
1683 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001684
Ted Kremenekfd301942008-10-17 22:23:12 +00001685 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001686
Ted Kremenekf9561e52008-04-11 20:23:24 +00001687 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001688 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1689 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001690
Ted Kremenekfd301942008-10-17 22:23:12 +00001691 // FIXME: We eventually should handle structs and other compound types
1692 // that are returned by value.
1693
1694 QualType T = Ex->getType();
1695
Ted Kremenek062e2f92008-11-13 06:10:40 +00001696 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001697 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001698 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001699
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001700 SVal X = Loc::IsLocType(T)
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001701 ? cast<SVal>(loc::SymbolVal(Sym))
1702 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenekf9561e52008-04-11 20:23:24 +00001703
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001704 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001705 }
1706
Ted Kremenek940b1d82008-04-10 23:44:06 +00001707 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00001708 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001709
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001710 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001711 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001712 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001713 assert (idx < (unsigned) (arg_end - arg_beg));
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001714 SVal V = state.GetSVal(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001715 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001716 break;
1717 }
1718
Ted Kremenek14993892008-05-06 02:41:27 +00001719 case RetEffect::ReceiverAlias: {
1720 assert (Receiver);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001721 SVal V = state.GetSVal(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001722 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00001723 break;
1724 }
1725
Ted Kremeneka7344702008-06-23 18:02:52 +00001726 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001727 case RetEffect::OwnedSymbol: {
1728 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001729 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001730 QualType RetT = GetReturnType(Ex, Eng.getContext());
1731 state =
1732 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001733 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001734
Ted Kremeneka7344702008-06-23 18:02:52 +00001735 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00001736 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1737 bool isFeasible;
1738 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1739 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1740 }
Ted Kremeneka7344702008-06-23 18:02:52 +00001741
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001742 break;
1743 }
1744
1745 case RetEffect::NotOwnedSymbol: {
1746 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001747 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek553cf182008-06-25 21:21:56 +00001748 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001749
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001750 state =
1751 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001752 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001753 break;
1754 }
1755 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001756
Ted Kremenekf5b34b12009-02-18 02:00:25 +00001757 // Generate a sink node if we are at the end of a path.
1758 GRExprEngine::NodeTy *NewNode =
1759 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1760 : Builder.MakeNode(Dst, Ex, Pred, state);
1761
1762 // Annotate the edge with summary we used.
1763 // FIXME: This assumes that we always use the same summary when generating
1764 // this node.
1765 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001766}
1767
1768
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001769void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001770 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001771 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001772 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001773 ExplodedNode<GRState>* Pred) {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001774
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001775 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1776 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001777
1778 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1779 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001780}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001781
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001782void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001783 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001784 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001785 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001786 ExplodedNode<GRState>* Pred) {
Ted Kremenekb3095252008-05-06 04:20:12 +00001787 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001788
Ted Kremenek553cf182008-06-25 21:21:56 +00001789 if (Expr* Receiver = ME->getReceiver()) {
1790 // We need the type-information of the tracked receiver object
1791 // Retrieve it from the state.
1792 ObjCInterfaceDecl* ID = 0;
1793
1794 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1795 // a chain of lookups.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001796 const GRState* St = Builder.GetState(Pred);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001797 SVal V = Eng.getStateManager().GetSVal(St, Receiver );
Ted Kremenek553cf182008-06-25 21:21:56 +00001798
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001799 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001800 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek553cf182008-06-25 21:21:56 +00001801
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001802 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001803 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001804
1805 if (const PointerType* PT = Ty->getAsPointerType()) {
1806 QualType PointeeTy = PT->getPointeeType();
1807
1808 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1809 ID = IT->getDecl();
1810 }
1811 }
1812 }
1813
1814 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001815
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001816 // Special-case: are we sending a mesage to "self"?
1817 // This is a hack. When we have full-IP this should be removed.
1818 if (!Summ) {
1819 ObjCMethodDecl* MD =
1820 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1821
1822 if (MD) {
1823 if (Expr* Receiver = ME->getReceiver()) {
1824 SVal X = Eng.getStateManager().GetSVal(St, Receiver);
1825 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001826 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1827 // Create a summmary where all of the arguments "StopTracking".
1828 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1829 DoNothing,
1830 StopTracking);
1831 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001832 }
1833 }
1834 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001835 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001836 else
Ted Kremenek1f180c32008-06-23 22:21:20 +00001837 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1838 ME->getSelector());
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001839
Ted Kremenekb3095252008-05-06 04:20:12 +00001840 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1841 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001842}
Ted Kremenek5216ad72009-02-14 03:16:10 +00001843
1844namespace {
1845class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1846 GRStateRef state;
1847public:
1848 StopTrackingCallback(GRStateRef st) : state(st) {}
1849 GRStateRef getState() { return state; }
1850
1851 bool VisitSymbol(SymbolRef sym) {
1852 state = state.remove<RefBindings>(sym);
1853 return true;
1854 }
Ted Kremenekb3095252008-05-06 04:20:12 +00001855
Ted Kremenek5216ad72009-02-14 03:16:10 +00001856 const GRState* getState() const { return state.getState(); }
1857};
1858} // end anonymous namespace
1859
1860
Ted Kremenek41573eb2009-02-14 01:43:44 +00001861void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001862 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00001863 bool escapes = false;
1864
Ted Kremeneka496d162008-10-18 03:49:51 +00001865 // A value escapes in three possible cases (this may change):
1866 //
1867 // (1) we are binding to something that is not a memory region.
1868 // (2) we are binding to a memregion that does not have stack storage
1869 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00001870 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00001871 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00001872
Ted Kremenek41573eb2009-02-14 01:43:44 +00001873 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00001874 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00001875 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001876 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1877 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00001878
1879 if (!escapes) {
1880 // To test (3), generate a new state with the binding removed. If it is
1881 // the same state, then it escapes (since the store cannot represent
1882 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00001883 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00001884 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001885 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00001886
Ted Kremenek5216ad72009-02-14 03:16:10 +00001887 // If our store can represent the binding and we aren't storing to something
1888 // that doesn't have local storage then just return and have the simulation
1889 // state continue as is.
1890 if (!escapes)
1891 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00001892
Ted Kremenek5216ad72009-02-14 03:16:10 +00001893 // Otherwise, find all symbols referenced by 'val' that we are tracking
1894 // and stop tracking them.
1895 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00001896}
1897
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001898std::pair<GRStateRef,bool>
1899CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1900 const GRState* St, const Decl* CD,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001901 SymbolRef sid,
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001902 RefVal V, bool& hasLeak) {
Ted Kremenekdb863712008-04-16 22:32:20 +00001903
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001904 GRStateRef state(St, VMgr);
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001905 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001906 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001907
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001908 if (V.isReturnedOwned() && V.getCount() == 0)
1909 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00001910 std::string s = MD->getSelector().getAsString();
Ted Kremenek4c79e552008-11-05 16:54:44 +00001911 if (!followsReturnRule(s.c_str())) {
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001912 hasLeak = true;
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001913 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
1914 return std::make_pair(state, true);
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001915 }
1916 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001917
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001918 // All other cases.
1919
1920 hasLeak = V.isOwned() ||
1921 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001922
Ted Kremenekdb863712008-04-16 22:32:20 +00001923 if (!hasLeak)
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001924 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001925
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001926 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
1927 false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001928}
1929
Ted Kremenek652adc62008-04-24 23:57:27 +00001930
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001931
Ted Kremenek652adc62008-04-24 23:57:27 +00001932// Dead symbols.
1933
Ted Kremenekcf701772009-02-05 06:50:21 +00001934
Ted Kremenek652adc62008-04-24 23:57:27 +00001935
Ted Kremenek4fd88972008-04-17 18:12:53 +00001936 // Return statements.
1937
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001938void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001939 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001940 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001941 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001942 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001943
1944 Expr* RetE = S->getRetValue();
1945 if (!RetE) return;
1946
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001947 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001948 SVal V = state.GetSVal(RetE);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001949
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001950 if (!isa<loc::SymbolVal>(V))
Ted Kremenek4fd88972008-04-17 18:12:53 +00001951 return;
1952
1953 // Get the reference count binding (if any).
Ted Kremenek2dabd432008-12-05 02:27:51 +00001954 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001955 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001956
1957 if (!T)
1958 return;
1959
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001960 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001961 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001962
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001963 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001964 case RefVal::Owned: {
1965 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001966 assert (cnt > 0);
1967 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001968 break;
1969 }
1970
1971 case RefVal::NotOwned: {
1972 unsigned cnt = X.getCount();
1973 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1974 : RefVal::makeReturnedNotOwned();
1975 break;
1976 }
1977
1978 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001979 return;
1980 }
1981
1982 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001983 state = state.set<RefBindings>(Sym, X);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001984 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001985}
1986
Ted Kremenekcb612922008-04-18 19:23:43 +00001987// Assumptions.
1988
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001989const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
1990 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001991 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00001992 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00001993
1994 // FIXME: We may add to the interface of EvalAssume the list of symbols
1995 // whose assumptions have changed. For now we just iterate through the
1996 // bindings and check if any of the tracked symbols are NULL. This isn't
1997 // too bad since the number of symbols we will track in practice are
1998 // probably small and EvalAssume is only called at branches and a few
1999 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002000 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002001
2002 if (B.isEmpty())
2003 return St;
2004
2005 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002006
2007 GRStateRef state(St, VMgr);
2008 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002009
2010 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002011 // Check if the symbol is null (or equal to any constant).
2012 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00002013 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002014 changed = true;
2015 B = RefBFactory.Remove(B, I.getKey());
2016 }
2017 }
2018
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002019 if (changed)
2020 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00002021
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002022 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00002023}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002024
Ted Kremenek2dabd432008-12-05 02:27:51 +00002025RefBindings CFRefCount::Update(RefBindings B, SymbolRef sym,
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002026 RefVal V, ArgEffect E,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002027 RefVal::Kind& hasErr,
2028 RefBindings::Factory& RefBFactory) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00002029
2030 // In GC mode [... release] and [... retain] do nothing.
2031 switch (E) {
2032 default: break;
2033 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2034 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00002035 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002036 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002037
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002038 switch (E) {
2039 default:
2040 assert (false && "Unhandled CFRef transition.");
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002041
2042 case MayEscape:
2043 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002044 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002045 break;
2046 }
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002047 // Fall-through.
Ted Kremenek070a8252008-07-09 18:11:16 +00002048 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002049 case DoNothing:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002050 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002051 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002052 hasErr = V.getKind();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002053 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002054 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002055 return B;
Ted Kremeneke19f4492008-06-30 16:57:41 +00002056
Ted Kremenekabf43972009-01-28 21:44:40 +00002057 case Autorelease:
2058 if (isGCEnabled()) return B;
2059 // Fall-through.
Ted Kremenek14993892008-05-06 02:41:27 +00002060 case StopTracking:
2061 return RefBFactory.Remove(B, sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002062
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002063 case IncRef:
2064 switch (V.getKind()) {
2065 default:
2066 assert(false);
2067
2068 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002069 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00002070 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002071 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002072 case RefVal::Released:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002073 if (isGCEnabled())
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002074 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek65c91652008-04-29 05:44:10 +00002075 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002076 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek65c91652008-04-29 05:44:10 +00002077 hasErr = V.getKind();
2078 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002079 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002080 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002081 break;
2082
Ted Kremenek553cf182008-06-25 21:21:56 +00002083 case SelfOwn:
2084 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002085 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002086 case DecRef:
2087 switch (V.getKind()) {
2088 default:
2089 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002090
Ted Kremenek553cf182008-06-25 21:21:56 +00002091 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002092 assert(V.getCount() > 0);
2093 if (V.getCount() == 1) V = V ^ RefVal::Released;
2094 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002095 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002096
Ted Kremenek553cf182008-06-25 21:21:56 +00002097 case RefVal::NotOwned:
2098 if (V.getCount() > 0)
2099 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00002100 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002101 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002102 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00002103 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002104 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002105
2106 case RefVal::Released:
Ted Kremenek553cf182008-06-25 21:21:56 +00002107 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002108 hasErr = V.getKind();
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002109 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002110 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002111 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002112 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002113 return RefBFactory.Add(B, sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002114}
2115
Ted Kremenekfa34b332008-04-09 01:10:13 +00002116//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002117// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00002118//===----------------------------------------------------------------------===//
2119
Ted Kremenek8dd56462008-04-18 03:39:05 +00002120namespace {
2121
2122 //===-------------===//
2123 // Bug Descriptions. //
2124 //===-------------===//
2125
Ted Kremenekcf118d42009-02-04 23:49:09 +00002126 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002127 protected:
2128 CFRefCount& TF;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002129
2130 CFRefBug(CFRefCount* tf, const char* name)
2131 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002132 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002133
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002134 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00002135 const CFRefCount& getTF() const { return TF; }
2136
Ted Kremenekcf118d42009-02-04 23:49:09 +00002137 // FIXME: Eventually remove.
2138 virtual const char* getDescription() const = 0;
2139
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002140 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002141 };
2142
2143 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2144 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002145 UseAfterRelease(CFRefCount* tf)
2146 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002147
Ted Kremenekcf118d42009-02-04 23:49:09 +00002148 const char* getDescription() const {
Ted Kremenek9e476de2008-08-12 18:30:56 +00002149 return "Reference-counted object is used after it is released.";
Ted Kremenekcf701772009-02-05 06:50:21 +00002150 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002151 };
2152
2153 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2154 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002155 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2156
2157 const char* getDescription() const {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002158 return "Incorrect decrement of the reference count of a "
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002159 "CoreFoundation object: "
Ted Kremenek8dd56462008-04-18 03:39:05 +00002160 "The object is not owned at this point by the caller.";
2161 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002162 };
2163
2164 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002165 const bool isReturn;
2166 protected:
2167 Leak(CFRefCount* tf, const char* name, bool isRet)
2168 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002169 public:
Ted Kremenek8dd56462008-04-18 03:39:05 +00002170
Ted Kremenekd3057212009-02-07 22:38:00 +00002171 const char* getDescription() const { return ""; }
Ted Kremenek3148eb42009-01-24 00:55:43 +00002172
Ted Kremeneke45e57f2009-02-05 00:38:00 +00002173 bool isLeak() const { return true; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002174 };
Ted Kremenekcf118d42009-02-04 23:49:09 +00002175
2176 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2177 public:
2178 LeakAtReturn(CFRefCount* tf, const char* name)
2179 : Leak(tf, name, true) {}
2180 };
2181
2182 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2183 public:
2184 LeakWithinFunction(CFRefCount* tf, const char* name)
2185 : Leak(tf, name, false) {}
2186 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002187
2188 //===---------===//
2189 // Bug Reports. //
2190 //===---------===//
2191
2192 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek66d97062009-02-07 22:04:05 +00002193 protected:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002194 SymbolRef Sym;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002195 const CFRefCount &TF;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002196 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002197 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2198 ExplodedNode<GRState> *n, SymbolRef sym)
2199 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002200
2201 virtual ~CFRefReport() {}
2202
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002203 CFRefBug& getBugType() {
2204 return (CFRefBug&) RangedBugReport::getBugType();
2205 }
2206 const CFRefBug& getBugType() const {
2207 return (const CFRefBug&) RangedBugReport::getBugType();
2208 }
2209
2210 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2211 const SourceRange*& end) {
2212
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002213 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002214 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002215 else
2216 beg = end = 0;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002217 }
2218
Ted Kremenek2dabd432008-12-05 02:27:51 +00002219 SymbolRef getSymbol() const { return Sym; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002220
Ted Kremenek3148eb42009-01-24 00:55:43 +00002221 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2222 const ExplodedNode<GRState>* N);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002223
Ted Kremenek3148eb42009-01-24 00:55:43 +00002224 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002225
Ted Kremenek3148eb42009-01-24 00:55:43 +00002226 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2227 const ExplodedNode<GRState>* PrevN,
2228 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002229 BugReporter& BR,
2230 NodeResolver& NR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002231 };
2232
Ted Kremenekcf118d42009-02-04 23:49:09 +00002233 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremeneke469fa02009-02-07 22:19:59 +00002234 SourceLocation AllocSite;
2235 const MemRegion* AllocBinding;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002236 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002237 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2238 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenekd3057212009-02-07 22:38:00 +00002239 GRExprEngine& Eng);
Ted Kremenek66d97062009-02-07 22:04:05 +00002240
2241 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2242 const ExplodedNode<GRState>* N);
2243
Ted Kremeneke469fa02009-02-07 22:19:59 +00002244 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekcf118d42009-02-04 23:49:09 +00002245 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002246} // end anonymous namespace
2247
Ted Kremenekcf118d42009-02-04 23:49:09 +00002248void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenekcf701772009-02-05 06:50:21 +00002249 useAfterRelease = new UseAfterRelease(this);
2250 BR.Register(useAfterRelease);
2251
2252 releaseNotOwned = new BadRelease(this);
2253 BR.Register(releaseNotOwned);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002254
2255 // First register "return" leaks.
2256 const char* name = 0;
2257
2258 if (isGCEnabled())
2259 name = "[naming convention] leak of returned object (GC)";
2260 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2261 name = "[naming convention] leak of returned object (hybrid MM, "
2262 "non-GC)";
2263 else {
2264 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2265 name = "[naming convention] leak of returned object";
2266 }
2267
Ted Kremenekcf701772009-02-05 06:50:21 +00002268 leakAtReturn = new LeakAtReturn(this, name);
2269 BR.Register(leakAtReturn);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002270
Ted Kremenekcf118d42009-02-04 23:49:09 +00002271 // Second, register leaks within a function/method.
2272 if (isGCEnabled())
2273 name = "leak (GC)";
2274 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2275 name = "leak (hybrid MM, non-GC)";
2276 else {
2277 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2278 name = "leak";
2279 }
2280
Ted Kremenekcf701772009-02-05 06:50:21 +00002281 leakWithinFunction = new LeakWithinFunction(this, name);
2282 BR.Register(leakWithinFunction);
2283
2284 // Save the reference to the BugReporter.
2285 this->BR = &BR;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002286}
Ted Kremenek072192b2008-04-30 23:47:44 +00002287
2288static const char* Msgs[] = {
2289 "Code is compiled in garbage collection only mode" // GC only
2290 " (the bug occurs with garbage collection enabled).",
2291
2292 "Code is compiled without garbage collection.", // No GC.
2293
2294 "Code is compiled for use with and without garbage collection (GC)."
2295 " The bug occurs with GC enabled.", // Hybrid, with GC.
2296
2297 "Code is compiled for use with and without garbage collection (GC)."
2298 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2299};
2300
2301std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2302 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2303
2304 switch (TF.getLangOptions().getGCMode()) {
2305 default:
2306 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002307
2308 case LangOptions::GCOnly:
2309 assert (TF.isGCEnabled());
Ted Kremenek9e476de2008-08-12 18:30:56 +00002310 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2311
Ted Kremenek072192b2008-04-30 23:47:44 +00002312 case LangOptions::NonGC:
2313 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002314 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2315
2316 case LangOptions::HybridGC:
2317 if (TF.isGCEnabled())
2318 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2319 else
2320 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2321 }
2322}
2323
Ted Kremenek27019002009-02-18 21:57:45 +00002324static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2325 ArgEffect X) {
2326 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2327 I!=E; ++I)
2328 if (*I == X) return true;
2329
2330 return false;
2331}
2332
Ted Kremenek3148eb42009-01-24 00:55:43 +00002333PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2334 const ExplodedNode<GRState>* PrevN,
2335 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002336 BugReporter& BR,
2337 NodeResolver& NR) {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002338
Ted Kremenek611a15a2009-01-28 05:29:13 +00002339 // Check if the type state has changed.
2340 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2341 GRStateRef PrevSt(PrevN->getState(), StMgr);
2342 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek20982802009-01-28 05:06:46 +00002343
Ted Kremenek611a15a2009-01-28 05:29:13 +00002344 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2345 if (!CurrT) return NULL;
2346
2347 const RefVal& CurrV = *CurrT;
2348 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenekce48e002008-05-05 17:53:17 +00002349
Ted Kremenek27019002009-02-18 21:57:45 +00002350 // Create a string buffer to constain all the useful things we want
2351 // to tell the user.
2352 std::string sbuf;
2353 llvm::raw_string_ostream os(sbuf);
2354
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002355 // This is the allocation site since the previous node had no bindings
2356 // for this symbol.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002357 if (!PrevT) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002358 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2359
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002360 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2361 // Get the name of the callee (if it is available).
2362 SVal X = CurrSt.GetSVal(CE->getCallee());
2363 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2364 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2365 else
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002366 os << "function call";
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002367 }
2368 else {
2369 assert (isa<ObjCMessageExpr>(S));
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002370 os << "Method";
Ted Kremenekce48e002008-05-05 17:53:17 +00002371 }
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002372
Ted Kremenek961b61d2009-01-28 06:06:36 +00002373 if (CurrV.getObjKind() == RetEffect::CF) {
2374 os << " returns a Core Foundation object with a ";
2375 }
2376 else {
2377 assert (CurrV.getObjKind() == RetEffect::ObjC);
2378 os << " returns an Objective-C object with a ";
2379 }
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002380
Ted Kremenek23b8eaa2009-01-28 06:25:48 +00002381 if (CurrV.isOwned()) {
2382 os << "+1 retain count (owning reference).";
2383
2384 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2385 assert(CurrV.getObjKind() == RetEffect::CF);
2386 os << " "
2387 "Core Foundation objects are not automatically garbage collected.";
2388 }
2389 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002390 else {
2391 assert (CurrV.isNotOwned());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002392 os << "+0 retain count (non-owning reference).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002393 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002394
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002395 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002396 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002397
2398 if (Expr* Exp = dyn_cast<Expr>(S))
2399 P->addRange(Exp->getSourceRange());
2400
2401 return P;
2402 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002403
Ted Kremenek27019002009-02-18 21:57:45 +00002404 // Gather up the effects that were performed on the object at this
2405 // program point
2406 llvm::SmallVector<ArgEffect, 2> AEffects;
2407
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002408 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2409 // We only have summaries attached to nodes after evaluating CallExpr and
2410 // ObjCMessageExprs.
2411 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2412
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002413 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2414 // Iterate through the parameter expressions and see if the symbol
2415 // was ever passed as an argument.
2416 unsigned i = 0;
2417
2418 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2419 AI!=AE; ++AI, ++i) {
Ted Kremenek27019002009-02-18 21:57:45 +00002420
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002421 // Retrieve the value of the arugment.
2422 SVal X = CurrSt.GetSVal(*AI);
Ted Kremenek27019002009-02-18 21:57:45 +00002423
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002424 // Is it the symbol we're interested in?
2425 if (!isa<loc::SymbolVal>(X) ||
2426 Sym != cast<loc::SymbolVal>(X).getSymbol())
2427 continue;
Ted Kremenek79c140b2008-04-18 05:32:44 +00002428
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002429 // We have an argument. Get the effect!
2430 AEffects.push_back(Summ->getArg(i));
Ted Kremenek79c140b2008-04-18 05:32:44 +00002431 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002432 }
2433 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2434 if (Expr *receiver = ME->getReceiver()) {
Ted Kremenek27019002009-02-18 21:57:45 +00002435 SVal RetV = CurrSt.GetSVal(receiver);
2436 if (isa<loc::SymbolVal>(RetV) &&
2437 Sym == cast<loc::SymbolVal>(RetV).getSymbol()) {
2438 // The symbol we are tracking is the receiver.
2439 AEffects.push_back(Summ->getReceiverEffect());
2440 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002441 }
2442 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002443 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002444
Ted Kremenek27019002009-02-18 21:57:45 +00002445 do {
2446 // Get the previous type state.
2447 RefVal PrevV = *PrevT;
2448
2449 // Specially handle CFMakeCollectable and friends.
2450 if (contains(AEffects, MakeCollectable)) {
2451 // Get the name of the function.
2452 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2453 loc::FuncVal FV =
2454 cast<loc::FuncVal>(CurrSt.GetSVal(cast<CallExpr>(S)->getCallee()));
2455 const std::string& FName = FV.getDecl()->getNameAsString();
2456
2457 if (TF.isGCEnabled()) {
2458 // Determine if the object's reference count was pushed to zero.
2459 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2460
2461 os << "In GC mode a call to '" << FName
2462 << "' decrements an object's retain count and registers the "
2463 "object with the garbage collector. ";
2464
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002465 if (CurrV.getKind() == RefVal::Released) {
2466 assert(CurrV.getCount() == 0);
2467 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek27019002009-02-18 21:57:45 +00002468 "automatically collected by the garbage collector.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002469 }
Ted Kremenek27019002009-02-18 21:57:45 +00002470 else
2471 os << "An object must have a 0 retain count to be garbage collected. "
2472 "After this call its retain count is +" << CurrV.getCount()
2473 << '.';
2474 }
2475 else
2476 os << "When GC is not enabled a call to '" << FName
2477 << "' has no effect on its argument.";
2478
2479 // Nothing more to say.
2480 break;
2481 }
2482
2483 // Determine if the typestate has changed.
2484 if (!(PrevV == CurrV))
2485 switch (CurrV.getKind()) {
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002486 case RefVal::Owned:
2487 case RefVal::NotOwned:
2488
2489 if (PrevV.getCount() == CurrV.getCount())
2490 return 0;
2491
2492 if (PrevV.getCount() > CurrV.getCount())
2493 os << "Reference count decremented.";
2494 else
2495 os << "Reference count incremented.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002496
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002497 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002498 os << " The object now has +" << Count;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002499
2500 if (Count > 1)
2501 os << " retain counts.";
2502 else
2503 os << " retain count.";
2504 }
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002505
2506 if (PrevV.getKind() == RefVal::Released) {
2507 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2508 os << " The object is not eligible for garbage collection until the "
2509 "retain count reaches 0 again.";
2510 }
2511
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002512 break;
2513
2514 case RefVal::Released:
2515 os << "Object released.";
2516 break;
2517
2518 case RefVal::ReturnedOwned:
2519 os << "Object returned to caller as an owning reference (single retain "
2520 "count transferred to caller).";
2521 break;
2522
2523 case RefVal::ReturnedNotOwned:
2524 os << "Object returned to caller with a +0 (non-owning) retain count.";
2525 break;
2526
2527 default:
2528 return NULL;
Ted Kremenek27019002009-02-18 21:57:45 +00002529 }
2530
2531 // Emit any remaining diagnostics for the argument effects (if any).
2532 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2533 E=AEffects.end(); I != E; ++I) {
2534
2535 // A bunch of things have alternate behavior under GC.
2536 if (TF.isGCEnabled())
2537 switch (*I) {
2538 default: break;
2539 case Autorelease:
2540 os << "In GC mode an 'autorelease' has no effect.";
2541 continue;
2542 case IncRefMsg:
2543 os << "In GC mode the 'retain' message has no effect.";
2544 continue;
2545 case DecRefMsg:
2546 os << "In GC mode the 'release' message has no effect.";
2547 continue;
2548 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002549 }
Ted Kremenek27019002009-02-18 21:57:45 +00002550 } while(0);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002551
2552 if (os.str().empty())
2553 return 0; // We have nothing to say!
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002554
2555 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2556 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002557 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002558
2559 // Add the range by scanning the children of the statement for any bindings
2560 // to Sym.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002561 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2562 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek20982802009-01-28 05:06:46 +00002563 SVal X = CurrSt.GetSVal(Exp);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002564 if (loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&X))
Ted Kremenek1f62ef32009-02-18 22:17:20 +00002565 if (SV->getSymbol() == Sym) {
2566 P->addRange(Exp->getSourceRange());
2567 break;
2568 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002569 }
2570
2571 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002572}
2573
Ted Kremenek9e240492008-10-04 05:50:14 +00002574namespace {
2575class VISIBILITY_HIDDEN FindUniqueBinding :
2576 public StoreManager::BindingsHandler {
Ted Kremenek2dabd432008-12-05 02:27:51 +00002577 SymbolRef Sym;
Ted Kremenek9e240492008-10-04 05:50:14 +00002578 MemRegion* Binding;
2579 bool First;
2580
2581 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002582 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenek9e240492008-10-04 05:50:14 +00002583
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002584 bool HandleBinding(StoreManager& SMgr, Store store, MemRegion* R, SVal val) {
2585 if (const loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002586 if (SV->getSymbol() != Sym)
2587 return true;
2588 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002589 else if (const nonloc::SymbolVal* SV=dyn_cast<nonloc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002590 if (SV->getSymbol() != Sym)
2591 return true;
2592 }
2593 else
2594 return true;
2595
2596 if (Binding) {
2597 First = false;
2598 return false;
2599 }
2600 else
2601 Binding = R;
2602
2603 return true;
2604 }
2605
2606 operator bool() { return First && Binding; }
2607 MemRegion* getRegion() { return Binding; }
2608};
2609}
2610
Ted Kremenek3148eb42009-01-24 00:55:43 +00002611static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremeneke469fa02009-02-07 22:19:59 +00002612GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002613 SymbolRef Sym) {
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002614
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002615 // Find both first node that referred to the tracked symbol and the
2616 // memory location that value was store to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002617 const ExplodedNode<GRState>* Last = N;
2618 const MemRegion* FirstBinding = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002619
2620 while (N) {
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002621 const GRState* St = N->getState();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002622 RefBindings B = St->get<RefBindings>();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002623
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002624 if (!B.lookup(Sym))
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002625 break;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002626
Ted Kremeneke469fa02009-02-07 22:19:59 +00002627 FindUniqueBinding FB(Sym);
2628 StateMgr.iterBindings(St, FB);
2629 if (FB) FirstBinding = FB.getRegion();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002630
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002631 Last = N;
2632 N = N->pred_empty() ? NULL : *(N->pred_begin());
2633 }
2634
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002635 return std::make_pair(Last, FirstBinding);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002636}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002637
Ted Kremenek3148eb42009-01-24 00:55:43 +00002638PathDiagnosticPiece*
2639CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002640
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002641 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002642 // Tell the BugReporter to report cases when the tracked symbol is
2643 // assigned to different variables, etc.
Ted Kremenekc0959972008-07-02 21:24:01 +00002644 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek66d97062009-02-07 22:04:05 +00002645 return RangedBugReport::getEndPath(BR, EndN);
2646}
2647
2648PathDiagnosticPiece*
2649CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2650
2651 GRBugReporter& BR = cast<GRBugReporter>(br);
2652 // Tell the BugReporter to report cases when the tracked symbol is
2653 // assigned to different variables, etc.
2654 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2655
2656 // We are reporting a leak. Walk up the graph to get to the first node where
2657 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002658 // is stored to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002659 const ExplodedNode<GRState>* AllocNode = 0;
2660 const MemRegion* FirstBinding = 0;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002661
2662 llvm::tie(AllocNode, FirstBinding) =
Ted Kremeneke469fa02009-02-07 22:19:59 +00002663 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002664
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002665 // Get the allocate site.
2666 assert (AllocNode);
2667 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002668
Ted Kremeneke28565b2008-05-05 18:50:19 +00002669 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002670 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002671
Ted Kremenekd5597922009-02-18 23:28:26 +00002672 // Get the leak site. We want to find the last place where the symbol
2673 // was used in an expression.
2674 const ExplodedNode<GRState>* LeakN = EndN;
2675 Stmt *S = 0;
Ted Kremeneke28565b2008-05-05 18:50:19 +00002676
Ted Kremenekd5597922009-02-18 23:28:26 +00002677 while (LeakN) {
2678 ProgramPoint P = LeakN->getLocation();
Ted Kremenekd5597922009-02-18 23:28:26 +00002679
2680 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2681 S = PS->getStmt();
2682 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
2683 S = BE->getSrc()->getTerminator();
2684
2685 if (S) {
2686 // Scan 'S' for uses of Sym.
2687 GRStateRef state(LeakN->getState(), BR.getStateManager());
2688 bool foundSymbol = false;
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002689
2690 // First check if 'S' itself binds to the symbol.
2691 if (Expr *Ex = dyn_cast<Expr>(S)) {
2692 SVal X = state.GetSVal(Ex);
2693 if (isa<loc::SymbolVal>(X) &&
2694 cast<loc::SymbolVal>(X).getSymbol() == Sym)
2695 foundSymbol = true;
2696 }
2697
2698 if (!foundSymbol)
2699 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2700 I!=E; ++I)
2701 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
2702 SVal X = state.GetSVal(Ex);
2703 if (isa<loc::SymbolVal>(X) &&
2704 cast<loc::SymbolVal>(X).getSymbol() == Sym){
2705 foundSymbol = true;
2706 break;
2707 }
Ted Kremenekd5597922009-02-18 23:28:26 +00002708 }
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002709
Ted Kremenekd5597922009-02-18 23:28:26 +00002710 if (foundSymbol)
2711 break;
2712 }
2713
2714 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2715 }
2716
2717 assert(LeakN && S && "No leak site found.");
Ted Kremeneke28565b2008-05-05 18:50:19 +00002718
Ted Kremeneke28565b2008-05-05 18:50:19 +00002719 // Generate the diagnostic.
Ted Kremenek572b2782009-02-18 22:59:04 +00002720 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenekc9e3d862009-02-07 21:59:45 +00002721 std::string sbuf;
2722 llvm::raw_string_ostream os(sbuf);
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002723
Ted Kremeneke28565b2008-05-05 18:50:19 +00002724 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002725
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002726 if (FirstBinding)
Ted Kremenek9e240492008-10-04 05:50:14 +00002727 os << " and stored into '" << FirstBinding->getString() << '\'';
2728
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002729 // Get the retain count.
2730 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2731
2732 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenek04f9d462008-12-02 01:26:07 +00002733 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2734 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2735 // to the caller for NS objects.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002736 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2737 os << " is returned from a method whose name ('"
Chris Lattner077bf5e2008-11-24 03:33:13 +00002738 << MD.getSelector().getAsString()
Ted Kremenek234a4c22009-01-07 00:39:56 +00002739 << "') does not contain 'copy' or otherwise starts with"
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002740 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002741 " in the Memory Management Guide for Cocoa (object leaked).";
2742 }
2743 else
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002744 os << " is no longer referenced after this point and has a retain count of"
2745 " +"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002746 << RV->getCount() << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002747
Ted Kremenek572b2782009-02-18 22:59:04 +00002748 return new PathDiagnosticPiece(L, os.str());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002749}
2750
Ted Kremenek989d5192008-04-17 23:43:50 +00002751
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002752CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2753 ExplodedNode<GRState> *n,
Ted Kremenekd3057212009-02-07 22:38:00 +00002754 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002755 : CFRefReport(D, tf, n, sym)
Ted Kremeneke469fa02009-02-07 22:19:59 +00002756{
2757
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002758 // Most bug reports are cached at the location where they occured.
2759 // With leaks, we want to unique them by the location where they were
Ted Kremeneke469fa02009-02-07 22:19:59 +00002760 // allocated, and only report a single path. To do this, we need to find
2761 // the allocation site of a piece of tracked memory, which we do via a
2762 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2763 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2764 // that all ancestor nodes that represent the allocation site have the
2765 // same SourceLocation.
2766 const ExplodedNode<GRState>* AllocNode = 0;
2767
2768 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekd3057212009-02-07 22:38:00 +00002769 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremeneke469fa02009-02-07 22:19:59 +00002770
Ted Kremeneke469fa02009-02-07 22:19:59 +00002771 // Get the SourceLocation for the allocation site.
Ted Kremenekd3057212009-02-07 22:38:00 +00002772 ProgramPoint P = AllocNode->getLocation();
Ted Kremeneke469fa02009-02-07 22:19:59 +00002773 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenekd3057212009-02-07 22:38:00 +00002774
2775 // Fill in the description of the bug.
2776 Description.clear();
2777 llvm::raw_string_ostream os(Description);
2778 SourceManager& SMgr = Eng.getContext().getSourceManager();
2779 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekc5c60002009-02-07 22:54:59 +00002780 os << "Potential leak of object allocated on line " << AllocLine;
2781
2782 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2783 if (AllocBinding)
2784 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002785}
2786
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002787//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00002788// Handle dead symbols and end-of-path.
2789//===----------------------------------------------------------------------===//
2790
2791void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2792 GREndPathNodeBuilder<GRState>& Builder) {
2793
2794 const GRState* St = Builder.getState();
2795 RefBindings B = St->get<RefBindings>();
2796
2797 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2798 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2799
2800 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2801 bool hasLeak = false;
2802
2803 std::pair<GRStateRef, bool> X =
2804 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2805 (*I).first, (*I).second, hasLeak);
2806
2807 St = X.first;
2808 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2809 }
2810
2811 if (Leaked.empty())
2812 return;
2813
2814 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2815
2816 if (!N)
2817 return;
2818
2819 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2820 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2821
2822 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2823 : leakWithinFunction);
2824 assert(BT && "BugType not initialized.");
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002825 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00002826 BR->EmitReport(report);
2827 }
2828}
2829
2830void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2831 GRExprEngine& Eng,
2832 GRStmtNodeBuilder<GRState>& Builder,
2833 ExplodedNode<GRState>* Pred,
2834 Stmt* S,
2835 const GRState* St,
2836 SymbolReaper& SymReaper) {
2837
Ted Kremenek33b6f632009-02-19 23:47:02 +00002838 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenekcf701772009-02-05 06:50:21 +00002839 RefBindings B = St->get<RefBindings>();
2840 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2841
2842 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2843 E = SymReaper.dead_end(); I != E; ++I) {
2844
2845 const RefVal* T = B.lookup(*I);
2846 if (!T) continue;
2847
2848 bool hasLeak = false;
2849
2850 std::pair<GRStateRef, bool> X
Ted Kremenek33b6f632009-02-19 23:47:02 +00002851 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00002852
2853 St = X.first;
2854
2855 if (hasLeak)
2856 Leaked.push_back(std::make_pair(*I,X.second));
2857 }
2858
Ted Kremenek33b6f632009-02-19 23:47:02 +00002859 if (!Leaked.empty()) {
2860 // Create a new intermediate node representing the leak point. We
2861 // use a special program point that represents this checker-specific
2862 // transition. We use the address of RefBIndex as a unique tag for this
2863 // checker. We will create another node (if we don't cache out) that
2864 // removes the retain-count bindings from the state.
2865 // NOTE: We use 'generateNode' so that it does interplay with the
2866 // auto-transition logic.
2867 ExplodedNode<GRState>* N =
2868 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00002869
Ted Kremenek33b6f632009-02-19 23:47:02 +00002870 if (!N)
2871 return;
2872
2873 // Generate the bug reports.
2874 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
2875 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2876
2877 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2878 : leakWithinFunction);
2879 assert(BT && "BugType not initialized.");
2880 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
2881 BR->EmitReport(report);
2882 }
Ted Kremenekcf701772009-02-05 06:50:21 +00002883
Ted Kremenek33b6f632009-02-19 23:47:02 +00002884 Pred = N;
Ted Kremenekcf701772009-02-05 06:50:21 +00002885 }
Ted Kremenek33b6f632009-02-19 23:47:02 +00002886
2887 // Now generate a new node that nukes the old bindings.
2888 GRStateRef state(St, Eng.getStateManager());
2889 RefBindings::Factory& F = state.get_context<RefBindings>();
2890
2891 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2892 E = SymReaper.dead_end(); I!=E; ++I)
2893 B = F.Remove(B, *I);
2894
2895 state = state.set<RefBindings>(B);
2896 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00002897}
2898
2899void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2900 GRStmtNodeBuilder<GRState>& Builder,
2901 Expr* NodeExpr, Expr* ErrorExpr,
2902 ExplodedNode<GRState>* Pred,
2903 const GRState* St,
2904 RefVal::Kind hasErr, SymbolRef Sym) {
2905 Builder.BuildSinks = true;
2906 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2907
2908 if (!N) return;
2909
2910 CFRefBug *BT = 0;
2911
2912 if (hasErr == RefVal::ErrorUseAfterRelease)
2913 BT = static_cast<CFRefBug*>(useAfterRelease);
2914 else {
2915 assert(hasErr == RefVal::ErrorReleaseNotOwned);
2916 BT = static_cast<CFRefBug*>(releaseNotOwned);
2917 }
2918
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002919 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00002920 report->addRange(ErrorExpr->getSourceRange());
2921 BR->EmitReport(report);
2922}
2923
2924//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00002925// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002926//===----------------------------------------------------------------------===//
2927
Ted Kremenek072192b2008-04-30 23:47:44 +00002928GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2929 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00002930 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00002931}