blob: d79186d8ccc41efae41031b1ffc50d90b6e41400 [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 Kremenek900a2d72008-05-07 18:36:45 +000042using llvm::CStrInCStrNoCase;
Ted Kremenek2fff37e2008-03-06 00:08:09 +000043
Ted Kremenek5c74d502008-10-24 21:18:08 +000044// The "fundamental rule" for naming conventions of methods:
45// (url broken into two lines)
46// http://developer.apple.com/documentation/Cocoa/Conceptual/
47// MemoryMgmt/Tasks/MemoryManagementRules.html
48//
49// "You take ownership of an object if you create it using a method whose name
50// begins with “alloc” or “new” or contains “copy” (for example, alloc,
51// newObject, or mutableCopy), or if you send it a retain message. You are
52// responsible for relinquishing ownership of objects you own using release
53// or autorelease. Any other time you receive an object, you must
54// not release it."
55//
56static bool followsFundamentalRule(const char* s) {
Ted Kremeneke1e91af2008-10-30 23:14:58 +000057 while (*s == '_') ++s;
Ted Kremenek234a4c22009-01-07 00:39:56 +000058 return CStrInCStrNoCase(s, "copy")
59 || CStrInCStrNoCase(s, "new") == s
60 || CStrInCStrNoCase(s, "alloc") == s;
Ted Kremenek4c79e552008-11-05 16:54:44 +000061}
62
63static bool followsReturnRule(const char* s) {
64 while (*s == '_') ++s;
65 return followsFundamentalRule(s) || CStrInCStrNoCase(s, "init") == s;
66}
Ted Kremenek5c74d502008-10-24 21:18:08 +000067
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000068//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000069// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +000070//===----------------------------------------------------------------------===//
71
Ted Kremenekb83e02e2008-05-01 18:31:44 +000072static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +000073 IdentifierInfo* II = &Ctx.Idents.get(name);
74 return Ctx.Selectors.getSelector(0, &II);
75}
76
Ted Kremenek9c32d082008-05-06 00:30:21 +000077static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
78 IdentifierInfo* II = &Ctx.Idents.get(name);
79 return Ctx.Selectors.getSelector(1, &II);
80}
81
Ted Kremenek553cf182008-06-25 21:21:56 +000082//===----------------------------------------------------------------------===//
83// Type querying functions.
84//===----------------------------------------------------------------------===//
85
Ted Kremenek12619382009-01-12 21:45:02 +000086static bool hasPrefix(const char* s, const char* prefix) {
87 if (!prefix)
88 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000089
Ted Kremenek12619382009-01-12 21:45:02 +000090 char c = *s;
91 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000092
Ted Kremenek12619382009-01-12 21:45:02 +000093 while (c != '\0' && cP != '\0') {
94 if (c != cP) break;
95 c = *(++s);
96 cP = *(++prefix);
97 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000098
Ted Kremenek12619382009-01-12 21:45:02 +000099 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000100}
101
Ted Kremenek12619382009-01-12 21:45:02 +0000102static bool hasSuffix(const char* s, const char* suffix) {
103 const char* loc = strstr(s, suffix);
104 return loc && strcmp(suffix, loc) == 0;
105}
106
107static bool isRefType(QualType RetTy, const char* prefix,
108 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek37d785b2008-07-15 16:50:12 +0000109
Ted Kremenek12619382009-01-12 21:45:02 +0000110 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
111 const char* TDName = TD->getDecl()->getIdentifier()->getName();
112 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
113 }
114
115 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000116 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000117
118 // Is the type void*?
119 const PointerType* PT = RetTy->getAsPointerType();
120 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000121 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000122
123 // Does the name start with the prefix?
124 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000125}
126
Ted Kremenek4fd88972008-04-17 18:12:53 +0000127//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000128// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000129//===----------------------------------------------------------------------===//
130
Ted Kremenek553cf182008-06-25 21:21:56 +0000131namespace {
132/// ArgEffect is used to summarize a function/method call's effect on a
133/// particular argument.
Ted Kremenek1c512f52009-02-18 18:54:33 +0000134enum ArgEffect { IncRefMsg, IncRef,
135 DecRefMsg, DecRef,
Ted Kremenek27019002009-02-18 21:57:45 +0000136 MakeCollectable,
Ted Kremenek1c512f52009-02-18 18:54:33 +0000137 DoNothing, DoNothingByRef,
Ted Kremenek070a8252008-07-09 18:11:16 +0000138 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek553cf182008-06-25 21:21:56 +0000139
140/// ArgEffects summarizes the effects of a function/method call on all of
141/// its arguments.
142typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000143}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000144
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000145namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000146template <> struct FoldingSetTrait<ArgEffects> {
147 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
148 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
149 ID.AddInteger(I->first);
150 ID.AddInteger((unsigned) I->second);
151 }
152 }
153};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000154} // end llvm namespace
155
156namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000157
158/// RetEffect is used to summarize a function/method call's behavior with
159/// respect to its return value.
160class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000161public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000162 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
163 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000164
165 enum ObjKind { CF, ObjC, AnyObj };
166
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000167private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000168 Kind K;
169 ObjKind O;
170 unsigned index;
171
172 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
173 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000174
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000175public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000176 Kind getKind() const { return K; }
177
178 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000179
180 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000181 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000182 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000183 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000184
Ted Kremenek553cf182008-06-25 21:21:56 +0000185 static RetEffect MakeAlias(unsigned Idx) {
186 return RetEffect(Alias, Idx);
187 }
188 static RetEffect MakeReceiverAlias() {
189 return RetEffect(ReceiverAlias);
190 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000191 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
192 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000193 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000194 static RetEffect MakeNotOwned(ObjKind o) {
195 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000196 }
197 static RetEffect MakeNoRet() {
198 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000199 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000200
Ted Kremenek553cf182008-06-25 21:21:56 +0000201 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000202 ID.AddInteger((unsigned)K);
203 ID.AddInteger((unsigned)O);
204 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000205 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000206};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000207
Ted Kremenek553cf182008-06-25 21:21:56 +0000208
209class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000210 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
211 /// specifies the argument (starting from 0). This can be sparsely
212 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000213 ArgEffects* Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000214
215 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
216 /// do not have an entry in Args.
217 ArgEffect DefaultArgEffect;
218
Ted Kremenek553cf182008-06-25 21:21:56 +0000219 /// Receiver - If this summary applies to an Objective-C message expression,
220 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000221 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000222
223 /// Ret - The effect on the return value. Used to indicate if the
224 /// function/method call returns a new tracked symbol, returns an
225 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000226 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000227
Ted Kremenek70a733e2008-07-18 17:24:20 +0000228 /// EndPath - Indicates that execution of this method/function should
229 /// terminate the simulation of a path.
230 bool EndPath;
231
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000232public:
233
Ted Kremenek1bffd742008-05-06 15:44:25 +0000234 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000235 ArgEffect ReceiverEff, bool endpath = false)
236 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
237 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000238
Ted Kremenek553cf182008-06-25 21:21:56 +0000239 /// getArg - Return the argument effect on the argument specified by
240 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000241 ArgEffect getArg(unsigned idx) const {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000242
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000243 if (!Args)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000244 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000245
246 // If Args is present, it is likely to contain only 1 element.
247 // Just do a linear search. Do it from the back because functions with
248 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek553cf182008-06-25 21:21:56 +0000249 // argument they actually modify with respect to the reference count.
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000250 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
251 I!=E; ++I) {
252
253 if (idx > I->first)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000254 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000255
256 if (idx == I->first)
257 return I->second;
258 }
259
Ted Kremenek1bffd742008-05-06 15:44:25 +0000260 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000261 }
262
Ted Kremenek553cf182008-06-25 21:21:56 +0000263 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000264 RetEffect getRetEffect() const {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000265 return Ret;
266 }
267
Ted Kremenek70a733e2008-07-18 17:24:20 +0000268 /// isEndPath - Returns true if executing the given method/function should
269 /// terminate the path.
270 bool isEndPath() const { return EndPath; }
271
Ted Kremenek553cf182008-06-25 21:21:56 +0000272 /// getReceiverEffect - Returns the effect on the receiver of the call.
273 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000274 ArgEffect getReceiverEffect() const {
275 return Receiver;
276 }
277
Ted Kremenek55499762008-06-17 02:43:46 +0000278 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000279
Ted Kremenek55499762008-06-17 02:43:46 +0000280 ExprIterator begin_args() const { return Args->begin(); }
281 ExprIterator end_args() const { return Args->end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000282
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000283 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000284 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000285 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000286 ID.AddPointer(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000287 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000288 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000289 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000290 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000291 }
292
293 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000294 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000295 }
296};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000297} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000298
Ted Kremenek553cf182008-06-25 21:21:56 +0000299//===----------------------------------------------------------------------===//
300// Data structures for constructing summaries.
301//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000302
Ted Kremenek553cf182008-06-25 21:21:56 +0000303namespace {
304class VISIBILITY_HIDDEN ObjCSummaryKey {
305 IdentifierInfo* II;
306 Selector S;
307public:
308 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
309 : II(ii), S(s) {}
310
311 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
312 : II(d ? d->getIdentifier() : 0), S(s) {}
313
314 ObjCSummaryKey(Selector s)
315 : II(0), S(s) {}
316
317 IdentifierInfo* getIdentifier() const { return II; }
318 Selector getSelector() const { return S; }
319};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000320}
321
322namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000323template <> struct DenseMapInfo<ObjCSummaryKey> {
324 static inline ObjCSummaryKey getEmptyKey() {
325 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
326 DenseMapInfo<Selector>::getEmptyKey());
327 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000328
Ted Kremenek553cf182008-06-25 21:21:56 +0000329 static inline ObjCSummaryKey getTombstoneKey() {
330 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
331 DenseMapInfo<Selector>::getTombstoneKey());
332 }
333
334 static unsigned getHashValue(const ObjCSummaryKey &V) {
335 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
336 & 0x88888888)
337 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
338 & 0x55555555);
339 }
340
341 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
342 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
343 RHS.getIdentifier()) &&
344 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
345 RHS.getSelector());
346 }
347
348 static bool isPod() {
349 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
350 DenseMapInfo<Selector>::isPod();
351 }
352};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000353} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000354
Ted Kremenek4f22a782008-06-23 23:30:29 +0000355namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000356class VISIBILITY_HIDDEN ObjCSummaryCache {
357 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
358 MapTy M;
359public:
360 ObjCSummaryCache() {}
361
362 typedef MapTy::iterator iterator;
363
364 iterator find(ObjCInterfaceDecl* D, Selector S) {
365
366 // Do a lookup with the (D,S) pair. If we find a match return
367 // the iterator.
368 ObjCSummaryKey K(D, S);
369 MapTy::iterator I = M.find(K);
370
371 if (I != M.end() || !D)
372 return I;
373
374 // Walk the super chain. If we find a hit with a parent, we'll end
375 // up returning that summary. We actually allow that key (null,S), as
376 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
377 // generate initial summaries without having to worry about NSObject
378 // being declared.
379 // FIXME: We may change this at some point.
380 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
381 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
382 break;
383
384 if (!C)
385 return I;
386 }
387
388 // Cache the summary with original key to make the next lookup faster
389 // and return the iterator.
390 M[K] = I->second;
391 return I;
392 }
393
Ted Kremenek98530452008-08-12 20:41:56 +0000394
Ted Kremenek553cf182008-06-25 21:21:56 +0000395 iterator find(Expr* Receiver, Selector S) {
396 return find(getReceiverDecl(Receiver), S);
397 }
398
399 iterator find(IdentifierInfo* II, Selector S) {
400 // FIXME: Class method lookup. Right now we dont' have a good way
401 // of going between IdentifierInfo* and the class hierarchy.
402 iterator I = M.find(ObjCSummaryKey(II, S));
403 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
404 }
405
406 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
407
408 const PointerType* PT = E->getType()->getAsPointerType();
409 if (!PT) return 0;
410
411 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
412 if (!OI) return 0;
413
414 return OI ? OI->getDecl() : 0;
415 }
416
417 iterator end() { return M.end(); }
418
419 RetainSummary*& operator[](ObjCMessageExpr* ME) {
420
421 Selector S = ME->getSelector();
422
423 if (Expr* Receiver = ME->getReceiver()) {
424 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
425 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
426 }
427
428 return M[ObjCSummaryKey(ME->getClassName(), S)];
429 }
430
431 RetainSummary*& operator[](ObjCSummaryKey K) {
432 return M[K];
433 }
434
435 RetainSummary*& operator[](Selector S) {
436 return M[ ObjCSummaryKey(S) ];
437 }
438};
439} // end anonymous namespace
440
441//===----------------------------------------------------------------------===//
442// Data structures for managing collections of summaries.
443//===----------------------------------------------------------------------===//
444
445namespace {
446class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000447
448 //==-----------------------------------------------------------------==//
449 // Typedefs.
450 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000451
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000452 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
453 ArgEffectsSetTy;
454
455 typedef llvm::FoldingSet<RetainSummary>
456 SummarySetTy;
457
458 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
459 FuncSummariesTy;
460
Ted Kremenek4f22a782008-06-23 23:30:29 +0000461 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000462
463 //==-----------------------------------------------------------------==//
464 // Data.
465 //==-----------------------------------------------------------------==//
466
Ted Kremenek553cf182008-06-25 21:21:56 +0000467 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000468 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000469
Ted Kremenek070a8252008-07-09 18:11:16 +0000470 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
471 /// "CFDictionaryCreate".
472 IdentifierInfo* CFDictionaryCreateII;
473
Ted Kremenek553cf182008-06-25 21:21:56 +0000474 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000475 const bool GCEnabled;
476
Ted Kremenek553cf182008-06-25 21:21:56 +0000477 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +0000478 SummarySetTy SummarySet;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000479
Ted Kremenek553cf182008-06-25 21:21:56 +0000480 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000481 FuncSummariesTy FuncSummaries;
482
Ted Kremenek553cf182008-06-25 21:21:56 +0000483 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
484 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000485 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000486
Ted Kremenek553cf182008-06-25 21:21:56 +0000487 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000488 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000489
Ted Kremenek553cf182008-06-25 21:21:56 +0000490 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000491 ArgEffectsSetTy ArgEffectsSet;
492
Ted Kremenek553cf182008-06-25 21:21:56 +0000493 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
494 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000495 llvm::BumpPtrAllocator BPAlloc;
496
Ted Kremenek553cf182008-06-25 21:21:56 +0000497 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000498 ArgEffects ScratchArgs;
499
Ted Kremenek432af592008-05-06 18:11:36 +0000500 RetainSummary* StopSummary;
501
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000502 //==-----------------------------------------------------------------==//
503 // Methods.
504 //==-----------------------------------------------------------------==//
505
Ted Kremenek553cf182008-06-25 21:21:56 +0000506 /// getArgEffects - Returns a persistent ArgEffects object based on the
507 /// data in ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000508 ArgEffects* getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000509
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000510 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000511
512public:
Ted Kremenek12619382009-01-12 21:45:02 +0000513 RetainSummary* getUnarySummary(FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000514
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000515 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
516 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000517 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000518
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000519 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000520 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000521 ArgEffect DefaultEff = MayEscape,
522 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000523
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000524 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000525 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000526 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000527 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000528 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000529
Ted Kremenek1bffd742008-05-06 15:44:25 +0000530 RetainSummary* getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000531 if (StopSummary)
532 return StopSummary;
533
534 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
535 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000536
Ted Kremenek432af592008-05-06 18:11:36 +0000537 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000538 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000539
Ted Kremenek553cf182008-06-25 21:21:56 +0000540 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000541
Ted Kremenek1f180c32008-06-23 22:21:20 +0000542 void InitializeClassMethodSummaries();
543 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000544
Ted Kremenek234a4c22009-01-07 00:39:56 +0000545 bool isTrackedObjectType(QualType T);
546
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000547private:
548
Ted Kremenek70a733e2008-07-18 17:24:20 +0000549 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
550 RetainSummary* Summ) {
551 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
552 }
553
Ted Kremenek553cf182008-06-25 21:21:56 +0000554 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
555 ObjCClassMethodSummaries[S] = Summ;
556 }
557
558 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
559 ObjCMethodSummaries[S] = Summ;
560 }
561
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000562 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenek70a733e2008-07-18 17:24:20 +0000563
Ted Kremenek9e476de2008-08-12 18:30:56 +0000564 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
565 llvm::SmallVector<IdentifierInfo*, 10> II;
566
567 while (const char* s = va_arg(argp, const char*))
568 II.push_back(&Ctx.Idents.get(s));
569
570 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek70a733e2008-07-18 17:24:20 +0000571 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
572 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000573
574 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
575 va_list argp;
576 va_start(argp, Summ);
577 addInstMethSummary(Cls, Summ, argp);
578 va_end(argp);
579 }
Ted Kremenek9e476de2008-08-12 18:30:56 +0000580
581 void addPanicSummary(const char* Cls, ...) {
582 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
583 DoNothing, DoNothing, true);
584 va_list argp;
585 va_start (argp, Cls);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000586 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000587 va_end(argp);
588 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000589
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000590public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000591
592 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000593 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000594 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek553cf182008-06-25 21:21:56 +0000595 GCEnabled(gcenabled), StopSummary(0) {
596
597 InitializeClassMethodSummaries();
598 InitializeMethodSummaries();
599 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000600
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000601 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000602
Ted Kremenekab592272008-06-24 03:56:45 +0000603 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek553cf182008-06-25 21:21:56 +0000604 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek1f180c32008-06-23 22:21:20 +0000605 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenekb3095252008-05-06 04:20:12 +0000606
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000607 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000608};
609
610} // end anonymous namespace
611
612//===----------------------------------------------------------------------===//
613// Implementation of checker data structures.
614//===----------------------------------------------------------------------===//
615
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000616RetainSummaryManager::~RetainSummaryManager() {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000617
618 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
619 // mitigating the need to do explicit cleanup of the
620 // Argument-Effect summaries.
621
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000622 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
623 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000624 I->getValue().~ArgEffects();
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000625}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000626
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000627ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000628
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000629 if (ScratchArgs.empty())
630 return NULL;
631
632 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000633 llvm::FoldingSetNodeID profile;
634 profile.Add(ScratchArgs);
635 void* InsertPos;
636
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000637 // Look up the uniqued copy, or create a new one.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000638 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000639 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000640
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000641 if (E) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000642 ScratchArgs.clear();
643 return &E->getValue();
644 }
645
646 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek553cf182008-06-25 21:21:56 +0000647 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000648
649 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000650 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000651
652 ScratchArgs.clear();
653 return &E->getValue();
654}
655
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000656RetainSummary*
657RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000658 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000659 ArgEffect DefaultEff,
660 bool isEndPath) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000661
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000662 // Generate a profile for the summary.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000663 llvm::FoldingSetNodeID profile;
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000664 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
665 isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000666
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000667 // Look up the uniqued summary, or create one if it doesn't exist.
668 void* InsertPos;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000669 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000670
671 if (Summ)
672 return Summ;
673
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000674 // Create the summary and return it.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000675 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000676 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000677 SummarySet.InsertNode(Summ, InsertPos);
678
679 return Summ;
680}
681
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000682//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000683// Predicates.
684//===----------------------------------------------------------------------===//
685
686bool RetainSummaryManager::isTrackedObjectType(QualType T) {
687 if (!Ctx.isObjCObjectPointerType(T))
688 return false;
689
690 // Does it subclass NSObject?
691 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
692
693 // We assume that id<..>, id, and "Class" all represent tracked objects.
694 if (!OT)
695 return true;
696
697 // Does the object type subclass NSObject?
698 // FIXME: We can memoize here if this gets too expensive.
699 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
700 ObjCInterfaceDecl* ID = OT->getDecl();
701
702 for ( ; ID ; ID = ID->getSuperClass())
703 if (ID->getIdentifier() == NSObjectII)
704 return true;
705
706 return false;
707}
708
709//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000710// Summary creation for functions (largely uses of Core Foundation).
711//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000712
Ted Kremenek12619382009-01-12 21:45:02 +0000713static bool isRetain(FunctionDecl* FD, const char* FName) {
714 const char* loc = strstr(FName, "Retain");
715 return loc && loc[sizeof("Retain")-1] == '\0';
716}
717
718static bool isRelease(FunctionDecl* FD, const char* FName) {
719 const char* loc = strstr(FName, "Release");
720 return loc && loc[sizeof("Release")-1] == '\0';
721}
722
Ted Kremenekab592272008-06-24 03:56:45 +0000723RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000724
725 SourceLocation Loc = FD->getLocation();
726
727 if (!Loc.isFileID())
728 return NULL;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000729
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000730 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000731 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000732
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000733 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000734 return I->second;
735
736 // No summary. Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000737 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000738
Ted Kremenek37d785b2008-07-15 16:50:12 +0000739 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000740 // We generate "stop" summaries for implicitly defined functions.
741 if (FD->isImplicit()) {
742 S = getPersistentStopSummary();
743 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000744 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000745
Ted Kremenek99890652009-01-16 18:40:33 +0000746 // [PR 3337] Use 'getDesugaredType' to strip away any typedefs on the
747 // function's type.
748 FunctionType* FT = cast<FunctionType>(FD->getType()->getDesugaredType());
Ted Kremenek12619382009-01-12 21:45:02 +0000749 const char* FName = FD->getIdentifier()->getName();
750
751 // Inspect the result type.
752 QualType RetTy = FT->getResultType();
753
754 // FIXME: This should all be refactored into a chain of "summary lookup"
755 // filters.
756 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
757 // FIXES: <rdar://problem/6326900>
758 // This should be addressed using a API table. This strcmp is also
759 // a little gross, but there is no need to super optimize here.
760 assert (ScratchArgs.empty());
761 ScratchArgs.push_back(std::make_pair(1, DecRef));
762 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
763 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000764 }
Ted Kremenek12619382009-01-12 21:45:02 +0000765
766 // Handle: id NSMakeCollectable(CFTypeRef)
767 if (strcmp(FName, "NSMakeCollectable") == 0) {
768 S = (RetTy == Ctx.getObjCIdType())
769 ? getUnarySummary(FT, cfmakecollectable)
770 : getPersistentStopSummary();
771
772 break;
773 }
774
775 if (RetTy->isPointerType()) {
776 // For CoreFoundation ('CF') types.
777 if (isRefType(RetTy, "CF", &Ctx, FName)) {
778 if (isRetain(FD, FName))
779 S = getUnarySummary(FT, cfretain);
780 else if (strstr(FName, "MakeCollectable"))
781 S = getUnarySummary(FT, cfmakecollectable);
782 else
783 S = getCFCreateGetRuleSummary(FD, FName);
784
785 break;
786 }
787
788 // For CoreGraphics ('CG') types.
789 if (isRefType(RetTy, "CG", &Ctx, FName)) {
790 if (isRetain(FD, FName))
791 S = getUnarySummary(FT, cfretain);
792 else
793 S = getCFCreateGetRuleSummary(FD, FName);
794
795 break;
796 }
797
798 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
799 if (isRefType(RetTy, "DADisk") ||
800 isRefType(RetTy, "DADissenter") ||
801 isRefType(RetTy, "DASessionRef")) {
802 S = getCFCreateGetRuleSummary(FD, FName);
803 break;
804 }
805
806 break;
807 }
808
809 // Check for release functions, the only kind of functions that we care
810 // about that don't return a pointer type.
811 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
812 if (isRelease(FD, FName+2))
813 S = getUnarySummary(FT, cfrelease);
814 else {
Ted Kremenek68189282009-01-29 22:45:13 +0000815 assert (ScratchArgs.empty());
816 // Remaining CoreFoundation and CoreGraphics functions.
817 // We use to assume that they all strictly followed the ownership idiom
818 // and that ownership cannot be transferred. While this is technically
819 // correct, many methods allow a tracked object to escape. For example:
820 //
821 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
822 // CFDictionaryAddValue(y, key, x);
823 // CFRelease(x);
824 // ... it is okay to use 'x' since 'y' has a reference to it
825 //
826 // We handle this and similar cases with the follow heuristic. If the
827 // function name contains "InsertValue", "SetValue" or "AddValue" then
828 // we assume that arguments may "escape."
829 //
830 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
831 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +0000832 CStrInCStrNoCase(FName, "SetValue") ||
833 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +0000834 ? MayEscape : DoNothing;
835
836 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +0000837 }
838 }
Ted Kremenek37d785b2008-07-15 16:50:12 +0000839 }
840 while (0);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000841
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000842 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000843 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000844}
845
Ted Kremenek37d785b2008-07-15 16:50:12 +0000846RetainSummary*
847RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
848 const char* FName) {
849
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000850 if (strstr(FName, "Create") || strstr(FName, "Copy"))
851 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000852
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000853 if (strstr(FName, "Get"))
854 return getCFSummaryGetRule(FD);
855
856 return 0;
857}
858
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000859RetainSummary*
Ted Kremenek12619382009-01-12 21:45:02 +0000860RetainSummaryManager::getUnarySummary(FunctionType* FT, UnaryFuncKind func) {
861 // Sanity check that this is *really* a unary function. This can
862 // happen if people do weird things.
863 FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FT);
864 if (!FTP || FTP->getNumArgs() != 1)
865 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000866
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000867 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000868
Ted Kremenek377e2302008-04-29 05:33:51 +0000869 switch (func) {
Ted Kremenek12619382009-01-12 21:45:02 +0000870 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000871 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000872 return getPersistentSummary(RetEffect::MakeAlias(0),
873 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000874 }
875
876 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000877 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000878 return getPersistentSummary(RetEffect::MakeNoRet(),
879 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000880 }
881
882 case cfmakecollectable: {
Ted Kremenek27019002009-02-18 21:57:45 +0000883 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
884 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000885 }
886
887 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000888 assert (false && "Not a supported unary function.");
Ted Kremenek98530452008-08-12 20:41:56 +0000889 return 0;
Ted Kremenek940b1d82008-04-10 23:44:06 +0000890 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000891}
892
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000893RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000894 assert (ScratchArgs.empty());
Ted Kremenek070a8252008-07-09 18:11:16 +0000895
896 if (FD->getIdentifier() == CFDictionaryCreateII) {
897 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
898 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
899 }
900
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000901 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000902}
903
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000904RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000905 assert (ScratchArgs.empty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000906 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
907 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000908}
909
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000910//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000911// Summary creation for Selectors.
912//===----------------------------------------------------------------------===//
913
Ted Kremenek1bffd742008-05-06 15:44:25 +0000914RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +0000915RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000916 assert(ScratchArgs.empty());
917
918 RetainSummary* Summ =
Ted Kremenek9c32d082008-05-06 00:30:21 +0000919 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000920
Ted Kremenek553cf182008-06-25 21:21:56 +0000921 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000922 return Summ;
923}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000924
Ted Kremenek553cf182008-06-25 21:21:56 +0000925
Ted Kremenek1bffd742008-05-06 15:44:25 +0000926RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +0000927RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
928 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000929
930 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000931
Ted Kremenek553cf182008-06-25 21:21:56 +0000932 // Look up a summary in our summary cache.
933 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000934
Ted Kremenek1f180c32008-06-23 22:21:20 +0000935 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000936 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000937
Ted Kremenek234a4c22009-01-07 00:39:56 +0000938 // "initXXX": pass-through for receiver.
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000939 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000940 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +0000941
Ted Kremenek0327f772008-06-02 17:14:13 +0000942 if (strncmp(s, "init", 4) == 0 || strncmp(s, "_init", 5) == 0)
Ted Kremenek234a4c22009-01-07 00:39:56 +0000943 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000944
Ted Kremenek234a4c22009-01-07 00:39:56 +0000945 // Look for methods that return an owned object.
946 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek84060db2008-05-07 04:25:59 +0000947 return 0;
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000948
Ted Kremenek234a4c22009-01-07 00:39:56 +0000949 if (followsFundamentalRule(s)) {
950 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000951 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000952 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek553cf182008-06-25 21:21:56 +0000953 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000954 return Summ;
955 }
Ted Kremenek1bffd742008-05-06 15:44:25 +0000956
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000957 return 0;
958}
959
Ted Kremenekc8395602008-05-06 21:26:51 +0000960RetainSummary*
Ted Kremenek1f180c32008-06-23 22:21:20 +0000961RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
962 Selector S) {
Ted Kremenekc8395602008-05-06 21:26:51 +0000963
Ted Kremenek553cf182008-06-25 21:21:56 +0000964 // FIXME: Eventually we should properly do class method summaries, but
965 // it requires us being able to walk the type hierarchy. Unfortunately,
966 // we cannot do this with just an IdentifierInfo* for the class name.
967
Ted Kremenekc8395602008-05-06 21:26:51 +0000968 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +0000969 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +0000970
Ted Kremenek1f180c32008-06-23 22:21:20 +0000971 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +0000972 return I->second;
973
Ted Kremeneka22cc2f2008-05-06 23:07:13 +0000974 return 0;
Ted Kremenekc8395602008-05-06 21:26:51 +0000975}
976
Ted Kremenek1f180c32008-06-23 22:21:20 +0000977void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +0000978
979 assert (ScratchArgs.empty());
980
Ted Kremeneka7344702008-06-23 18:02:52 +0000981 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000982 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +0000983
Ted Kremenek9c32d082008-05-06 00:30:21 +0000984 RetainSummary* Summ = getPersistentSummary(E);
985
Ted Kremenek553cf182008-06-25 21:21:56 +0000986 // Create the summaries for "alloc", "new", and "allocWithZone:" for
987 // NSObject and its derivatives.
988 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
989 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
990 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +0000991
992 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +0000993 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000994 GetNullarySelector("currentHandler", Ctx),
995 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +0000996
997 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekabf43972009-01-28 21:44:40 +0000998 ScratchArgs.push_back(std::make_pair(0, Autorelease));
999 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1000 GetUnarySelector("addObject", Ctx),
1001 getPersistentSummary(RetEffect::MakeNoRet(),
1002 DoNothing, DoNothing));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001003}
1004
Ted Kremenek1f180c32008-06-23 22:21:20 +00001005void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001006
1007 assert (ScratchArgs.empty());
1008
Ted Kremenekc8395602008-05-06 21:26:51 +00001009 // Create the "init" selector. It just acts as a pass-through for the
1010 // receiver.
Ted Kremenek179064e2008-07-01 17:21:27 +00001011 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
1012 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001013
1014 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +00001015 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001016 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001017
Ted Kremenek179064e2008-07-01 17:21:27 +00001018 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +00001019
1020 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001021 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1022
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001023 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001024 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001025
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001026 // Create the "retain" selector.
1027 E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001028 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001029 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001030
1031 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001032 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001033 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001034
1035 // Create the "drain" selector.
1036 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001037 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001038
1039 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001040 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001041 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001042
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001043 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek179064e2008-07-01 17:21:27 +00001044 RetainSummary *NSWindowSumm =
1045 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001046
1047 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1048 "styleMask", "backing", "defer", NULL);
1049
1050 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1051 "styleMask", "backing", "defer", "screen", NULL);
1052
1053 // For NSPanel (which subclasses NSWindow), allocated objects are not
1054 // self-owned.
1055 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1056 "styleMask", "backing", "defer", NULL);
1057
1058 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1059 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001060
Ted Kremenek70a733e2008-07-18 17:24:20 +00001061 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001062 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1063 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001064
Ted Kremenek9e476de2008-08-12 18:30:56 +00001065 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1066 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001067}
1068
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001069//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001070// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001071//===----------------------------------------------------------------------===//
1072
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001073namespace {
1074
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001075class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001076public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001077 enum Kind {
1078 Owned = 0, // Owning reference.
1079 NotOwned, // Reference is not owned by still valid (not freed).
1080 Released, // Object has been released.
1081 ReturnedOwned, // Returned object passes ownership to caller.
1082 ReturnedNotOwned, // Return object does not pass ownership to caller.
1083 ErrorUseAfterRelease, // Object used after released.
1084 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001085 ErrorLeak, // A memory leak due to excessive reference counts.
1086 ErrorLeakReturned // A memory leak due to the returning method not having
1087 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001088 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001089
1090private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001091 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001092 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001093 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001094 QualType T;
1095
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001096 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1097 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001098
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001099 RefVal(Kind k, unsigned cnt = 0)
1100 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1101
1102public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001103 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001104
1105 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001106
Ted Kremenek553cf182008-06-25 21:21:56 +00001107 unsigned getCount() const { return Cnt; }
1108 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001109
1110 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001111
Ted Kremenek73c750b2008-03-11 18:14:09 +00001112 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1113
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001114 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001115
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001116 bool isOwned() const {
1117 return getKind() == Owned;
1118 }
1119
Ted Kremenekdb863712008-04-16 22:32:20 +00001120 bool isNotOwned() const {
1121 return getKind() == NotOwned;
1122 }
1123
Ted Kremenek4fd88972008-04-17 18:12:53 +00001124 bool isReturnedOwned() const {
1125 return getKind() == ReturnedOwned;
1126 }
1127
1128 bool isReturnedNotOwned() const {
1129 return getKind() == ReturnedNotOwned;
1130 }
1131
1132 bool isNonLeakError() const {
1133 Kind k = getKind();
1134 return isError(k) && !isLeak(k);
1135 }
1136
1137 // State creation: normal state.
1138
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001139 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1140 unsigned Count = 1) {
1141 return RefVal(Owned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001142 }
1143
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001144 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1145 unsigned Count = 0) {
1146 return RefVal(NotOwned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001147 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001148
1149 static RefVal makeReturnedOwned(unsigned Count) {
1150 return RefVal(ReturnedOwned, Count);
1151 }
1152
1153 static RefVal makeReturnedNotOwned() {
1154 return RefVal(ReturnedNotOwned);
1155 }
1156
Ted Kremenek4fd88972008-04-17 18:12:53 +00001157 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001158
Ted Kremenek4fd88972008-04-17 18:12:53 +00001159 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001160 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001161 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001162
Ted Kremenek553cf182008-06-25 21:21:56 +00001163 RefVal operator-(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001164 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001165 }
1166
1167 RefVal operator+(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001168 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001169 }
1170
1171 RefVal operator^(Kind k) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001172 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001173 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001174
Ted Kremenek4fd88972008-04-17 18:12:53 +00001175 void Profile(llvm::FoldingSetNodeID& ID) const {
1176 ID.AddInteger((unsigned) kind);
1177 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001178 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001179 }
1180
Ted Kremenekf3948042008-03-11 19:44:10 +00001181 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001182};
Ted Kremenekf3948042008-03-11 19:44:10 +00001183
1184void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001185 if (!T.isNull())
1186 Out << "Tracked Type:" << T.getAsString() << '\n';
1187
Ted Kremenekf3948042008-03-11 19:44:10 +00001188 switch (getKind()) {
1189 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001190 case Owned: {
1191 Out << "Owned";
1192 unsigned cnt = getCount();
1193 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001194 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001195 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001196
Ted Kremenek61b9f872008-04-10 23:09:18 +00001197 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001198 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001199 unsigned cnt = getCount();
1200 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001201 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001202 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001203
Ted Kremenek4fd88972008-04-17 18:12:53 +00001204 case ReturnedOwned: {
1205 Out << "ReturnedOwned";
1206 unsigned cnt = getCount();
1207 if (cnt) Out << " (+ " << cnt << ")";
1208 break;
1209 }
1210
1211 case ReturnedNotOwned: {
1212 Out << "ReturnedNotOwned";
1213 unsigned cnt = getCount();
1214 if (cnt) Out << " (+ " << cnt << ")";
1215 break;
1216 }
1217
Ted Kremenekf3948042008-03-11 19:44:10 +00001218 case Released:
1219 Out << "Released";
1220 break;
1221
Ted Kremenekdb863712008-04-16 22:32:20 +00001222 case ErrorLeak:
1223 Out << "Leaked";
1224 break;
1225
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001226 case ErrorLeakReturned:
1227 Out << "Leaked (Bad naming)";
1228 break;
1229
Ted Kremenekf3948042008-03-11 19:44:10 +00001230 case ErrorUseAfterRelease:
1231 Out << "Use-After-Release [ERROR]";
1232 break;
1233
1234 case ErrorReleaseNotOwned:
1235 Out << "Release of Not-Owned [ERROR]";
1236 break;
1237 }
1238}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001239
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001240} // end anonymous namespace
1241
1242//===----------------------------------------------------------------------===//
1243// RefBindings - State used to track object reference counts.
1244//===----------------------------------------------------------------------===//
1245
Ted Kremenek2dabd432008-12-05 02:27:51 +00001246typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001247static int RefBIndex = 0;
1248
1249namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001250 template<>
1251 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1252 static inline void* GDMIndex() { return &RefBIndex; }
1253 };
1254}
Ted Kremenek6d348932008-10-21 15:53:15 +00001255
1256//===----------------------------------------------------------------------===//
1257// ARBindings - State used to track objects in autorelease pools.
1258//===----------------------------------------------------------------------===//
1259
Ted Kremenek2dabd432008-12-05 02:27:51 +00001260typedef llvm::ImmutableSet<SymbolRef> ARPoolContents;
1261typedef llvm::ImmutableList< std::pair<SymbolRef, ARPoolContents*> > ARBindings;
Ted Kremenek6d348932008-10-21 15:53:15 +00001262static int AutoRBIndex = 0;
1263
1264namespace clang {
1265 template<>
1266 struct GRStateTrait<ARBindings> : public GRStatePartialTrait<ARBindings> {
1267 static inline void* GDMIndex() { return &AutoRBIndex; }
1268 };
1269}
1270
Ted Kremenek13922612008-04-16 20:40:59 +00001271//===----------------------------------------------------------------------===//
1272// Transfer functions.
1273//===----------------------------------------------------------------------===//
1274
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001275namespace {
1276
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001277class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001278public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001279 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001280 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001281 virtual void Print(std::ostream& Out, const GRState* state,
1282 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001283 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001284
1285private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001286 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1287 SummaryLogTy;
1288
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001289 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001290 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001291 const LangOptions& LOpts;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001292
Ted Kremenekcf701772009-02-05 06:50:21 +00001293 BugType *useAfterRelease, *releaseNotOwned;
1294 BugType *leakWithinFunction, *leakAtReturn;
1295 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001296
Ted Kremenek2dabd432008-12-05 02:27:51 +00001297 RefBindings Update(RefBindings B, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001298 RefVal::Kind& hasErr, RefBindings::Factory& RefBFactory);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001299
Ted Kremenek2dabd432008-12-05 02:27:51 +00001300 RefVal::Kind& Update(GRStateRef& state, SymbolRef sym, RefVal V,
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001301 ArgEffect E, RefVal::Kind& hasErr) {
1302
1303 state = state.set<RefBindings>(Update(state.get<RefBindings>(), sym, V,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001304 E, hasErr,
1305 state.get_context<RefBindings>()));
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001306 return hasErr;
1307 }
1308
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001309 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1310 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001311 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001312 ExplodedNode<GRState>* Pred,
1313 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001314 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001315
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001316 std::pair<GRStateRef, bool>
1317 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001318 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenekdb863712008-04-16 22:32:20 +00001319
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001320public:
Ted Kremenek13922612008-04-16 20:40:59 +00001321
Ted Kremenek78d46242008-07-22 16:21:24 +00001322 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001323 : Summaries(Ctx, gcenabled),
Ted Kremenekcf701772009-02-05 06:50:21 +00001324 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1325 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001326
Ted Kremenekcf701772009-02-05 06:50:21 +00001327 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001328
Ted Kremenekcf118d42009-02-04 23:49:09 +00001329 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001330
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001331 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1332 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001333 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001334
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001335 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001336 const LangOptions& getLangOptions() const { return LOpts; }
1337
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001338 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1339 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1340 return I == SummaryLog.end() ? 0 : I->second;
1341 }
1342
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001343 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001344
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001345 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001346 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001347 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001348 Expr* Ex,
1349 Expr* Receiver,
1350 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001351 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001352 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001353
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001354 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001355 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001356 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001357 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001358 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001359
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001360
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001361 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001362 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001363 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001364 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001365 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001366
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001367 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001368 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001369 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001370 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001371 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001372
Ted Kremenek41573eb2009-02-14 01:43:44 +00001373 // Stores.
1374 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1375
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001376 // End-of-path.
1377
1378 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001379 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001380
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001381 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001382 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001383 GRStmtNodeBuilder<GRState>& Builder,
1384 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001385 Stmt* S, const GRState* state,
1386 SymbolReaper& SymReaper);
1387
Ted Kremenek4fd88972008-04-17 18:12:53 +00001388 // Return statements.
1389
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001390 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001391 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001392 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001393 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001394 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001395
1396 // Assumptions.
1397
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001398 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001399 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001400 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001401};
1402
1403} // end anonymous namespace
1404
Ted Kremenek8dd56462008-04-18 03:39:05 +00001405
Ted Kremenekae6814e2008-08-13 21:24:49 +00001406void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1407 const char* nl, const char* sep) {
1408
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001409 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001410
Ted Kremenekae6814e2008-08-13 21:24:49 +00001411 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001412 Out << sep << nl;
1413
1414 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1415 Out << (*I).first << " : ";
1416 (*I).second.print(Out);
1417 Out << nl;
1418 }
1419}
1420
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001421static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001422 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001423}
1424
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001425static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1426 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001427}
1428
Ted Kremenek14993892008-05-06 02:41:27 +00001429static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1430 return Summ ? Summ->getReceiverEffect() : DoNothing;
1431}
1432
Ted Kremenek70a733e2008-07-18 17:24:20 +00001433static inline bool IsEndPath(RetainSummary* Summ) {
1434 return Summ ? Summ->isEndPath() : false;
1435}
1436
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001437
Ted Kremenek553cf182008-06-25 21:21:56 +00001438/// GetReturnType - Used to get the return type of a message expression or
1439/// function call with the intention of affixing that type to a tracked symbol.
1440/// While the the return type can be queried directly from RetEx, when
1441/// invoking class methods we augment to the return type to be that of
1442/// a pointer to the class (as opposed it just being id).
1443static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1444
1445 QualType RetTy = RetE->getType();
1446
1447 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00001448 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001449 if (!PT)
1450 return RetTy;
1451
1452 // If RetEx is not a message expression just return its type.
1453 // If RetEx is a message expression, return its types if it is something
1454 /// more specific than id.
1455
1456 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1457
Steve Naroff389bf462009-02-12 17:52:19 +00001458 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00001459 return RetTy;
1460
1461 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1462
1463 // At this point we know the return type of the message expression is id.
1464 // If we have an ObjCInterceDecl, we know this is a call to a class method
1465 // whose type we can resolve. In such cases, promote the return type to
1466 // Class*.
1467 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1468}
1469
1470
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001471void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001472 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001473 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001474 Expr* Ex,
1475 Expr* Receiver,
1476 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001477 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001478 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001479
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001480 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001481 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001482 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00001483
1484 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001485 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001486 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001487 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00001488 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001489
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001490 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001491 SVal V = state.GetSVal(*I);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001492
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001493 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001494 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001495 if (RefBindings::data_type* T = state.get<RefBindings>(Sym))
1496 if (Update(state, Sym, *T, GetArgE(Summ, idx), hasErr)) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001497 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001498 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001499 break;
1500 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001501 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001502 else if (isa<Loc>(V)) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001503 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek070a8252008-07-09 18:11:16 +00001504
1505 if (GetArgE(Summ, idx) == DoNothingByRef)
1506 continue;
1507
1508 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001509
1510 // FIXME: Either this logic should also be replicated in GRSimpleVals
1511 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00001512
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001513 // FIXME: We can have collisions on the conjured symbol if the
1514 // expression *I also creates conjured symbols. We probably want
1515 // to identify conjured symbols by an expression pair: the enclosing
1516 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00001517 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00001518
Ted Kremenek993f1c72008-10-17 20:28:54 +00001519 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek90b32362008-12-17 19:42:34 +00001520
1521 // Blast through AnonTypedRegions to get the original region type.
1522 while (R) {
1523 const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R);
1524 if (!ATR) break;
1525 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1526 }
1527
Ted Kremenek9e240492008-10-04 05:50:14 +00001528 if (R) {
Ted Kremenek40e86d92008-12-18 23:34:57 +00001529
1530 // Is the invalidated variable something that we were tracking?
1531 SVal X = state.GetSVal(Loc::MakeVal(R));
1532
1533 if (isa<loc::SymbolVal>(X)) {
1534 SymbolRef Sym = cast<loc::SymbolVal>(X).getSymbol();
1535 state = state.remove<RefBindings>(Sym);
1536 }
1537
Ted Kremenek9e240492008-10-04 05:50:14 +00001538 // Set the value of the variable to be a conjured symbol.
1539 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek6eddeb12008-12-13 21:49:13 +00001540 QualType T = R->getRValueType(Ctx);
Ted Kremenek9e240492008-10-04 05:50:14 +00001541
Ted Kremenekfd301942008-10-17 22:23:12 +00001542 // FIXME: handle structs.
Ted Kremenek062e2f92008-11-13 06:10:40 +00001543 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001544 SymbolRef NewSym =
Ted Kremenekfd301942008-10-17 22:23:12 +00001545 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1546
Ted Kremenek90b32362008-12-17 19:42:34 +00001547 state = state.BindLoc(Loc::MakeVal(R),
Ted Kremenekfd301942008-10-17 22:23:12 +00001548 Loc::IsLocType(T)
1549 ? cast<SVal>(loc::SymbolVal(NewSym))
1550 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1551 }
1552 else {
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001553 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenekfd301942008-10-17 22:23:12 +00001554 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001555 }
1556 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001557 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001558 }
1559 else {
1560 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001561 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001562 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001563 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001564 else if (isa<nonloc::LocAsInteger>(V))
1565 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001566 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001567
Ted Kremenek553cf182008-06-25 21:21:56 +00001568 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001569 if (!ErrorExpr && Receiver) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001570 SVal V = state.GetSVal(Receiver);
1571 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001572 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001573 if (const RefVal* T = state.get<RefBindings>(Sym))
1574 if (Update(state, Sym, *T, GetReceiverE(Summ), hasErr)) {
Ted Kremenek14993892008-05-06 02:41:27 +00001575 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001576 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00001577 }
Ted Kremenek14993892008-05-06 02:41:27 +00001578 }
1579 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001580
Ted Kremenek553cf182008-06-25 21:21:56 +00001581 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001582 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001583 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001584 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001585 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001586 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001587
Ted Kremenek70a733e2008-07-18 17:24:20 +00001588 // Consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001589 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001590
1591 switch (RE.getKind()) {
1592 default:
1593 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001594
Ted Kremenekfd301942008-10-17 22:23:12 +00001595 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001596
Ted Kremenekf9561e52008-04-11 20:23:24 +00001597 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001598 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1599 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001600
Ted Kremenekfd301942008-10-17 22:23:12 +00001601 // FIXME: We eventually should handle structs and other compound types
1602 // that are returned by value.
1603
1604 QualType T = Ex->getType();
1605
Ted Kremenek062e2f92008-11-13 06:10:40 +00001606 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001607 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001608 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001609
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001610 SVal X = Loc::IsLocType(Ex->getType())
1611 ? cast<SVal>(loc::SymbolVal(Sym))
1612 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenekf9561e52008-04-11 20:23:24 +00001613
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001614 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001615 }
1616
Ted Kremenek940b1d82008-04-10 23:44:06 +00001617 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00001618 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001619
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001620 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001621 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001622 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001623 assert (idx < (unsigned) (arg_end - arg_beg));
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001624 SVal V = state.GetSVal(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001625 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001626 break;
1627 }
1628
Ted Kremenek14993892008-05-06 02:41:27 +00001629 case RetEffect::ReceiverAlias: {
1630 assert (Receiver);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001631 SVal V = state.GetSVal(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001632 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00001633 break;
1634 }
1635
Ted Kremeneka7344702008-06-23 18:02:52 +00001636 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001637 case RetEffect::OwnedSymbol: {
1638 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001639 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001640 QualType RetT = GetReturnType(Ex, Eng.getContext());
1641 state =
1642 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001643 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001644
Ted Kremeneka7344702008-06-23 18:02:52 +00001645 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00001646 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1647 bool isFeasible;
1648 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1649 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1650 }
Ted Kremeneka7344702008-06-23 18:02:52 +00001651
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001652 break;
1653 }
1654
1655 case RetEffect::NotOwnedSymbol: {
1656 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001657 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek553cf182008-06-25 21:21:56 +00001658 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001659
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001660 state =
1661 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001662 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001663 break;
1664 }
1665 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001666
Ted Kremenekf5b34b12009-02-18 02:00:25 +00001667 // Generate a sink node if we are at the end of a path.
1668 GRExprEngine::NodeTy *NewNode =
1669 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1670 : Builder.MakeNode(Dst, Ex, Pred, state);
1671
1672 // Annotate the edge with summary we used.
1673 // FIXME: This assumes that we always use the same summary when generating
1674 // this node.
1675 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001676}
1677
1678
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001679void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001680 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001681 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001682 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001683 ExplodedNode<GRState>* Pred) {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001684
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001685 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1686 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001687
1688 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1689 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001690}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001691
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001692void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001693 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001694 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001695 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001696 ExplodedNode<GRState>* Pred) {
Ted Kremenekb3095252008-05-06 04:20:12 +00001697 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001698
Ted Kremenek553cf182008-06-25 21:21:56 +00001699 if (Expr* Receiver = ME->getReceiver()) {
1700 // We need the type-information of the tracked receiver object
1701 // Retrieve it from the state.
1702 ObjCInterfaceDecl* ID = 0;
1703
1704 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1705 // a chain of lookups.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001706 const GRState* St = Builder.GetState(Pred);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001707 SVal V = Eng.getStateManager().GetSVal(St, Receiver );
Ted Kremenek553cf182008-06-25 21:21:56 +00001708
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001709 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001710 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek553cf182008-06-25 21:21:56 +00001711
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001712 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001713 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001714
1715 if (const PointerType* PT = Ty->getAsPointerType()) {
1716 QualType PointeeTy = PT->getPointeeType();
1717
1718 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1719 ID = IT->getDecl();
1720 }
1721 }
1722 }
1723
1724 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001725
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001726 // Special-case: are we sending a mesage to "self"?
1727 // This is a hack. When we have full-IP this should be removed.
1728 if (!Summ) {
1729 ObjCMethodDecl* MD =
1730 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1731
1732 if (MD) {
1733 if (Expr* Receiver = ME->getReceiver()) {
1734 SVal X = Eng.getStateManager().GetSVal(St, Receiver);
1735 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001736 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1737 // Create a summmary where all of the arguments "StopTracking".
1738 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1739 DoNothing,
1740 StopTracking);
1741 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001742 }
1743 }
1744 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001745 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001746 else
Ted Kremenek1f180c32008-06-23 22:21:20 +00001747 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1748 ME->getSelector());
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001749
Ted Kremenekb3095252008-05-06 04:20:12 +00001750 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1751 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001752}
Ted Kremenek5216ad72009-02-14 03:16:10 +00001753
1754namespace {
1755class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1756 GRStateRef state;
1757public:
1758 StopTrackingCallback(GRStateRef st) : state(st) {}
1759 GRStateRef getState() { return state; }
1760
1761 bool VisitSymbol(SymbolRef sym) {
1762 state = state.remove<RefBindings>(sym);
1763 return true;
1764 }
Ted Kremenekb3095252008-05-06 04:20:12 +00001765
Ted Kremenek5216ad72009-02-14 03:16:10 +00001766 const GRState* getState() const { return state.getState(); }
1767};
1768} // end anonymous namespace
1769
1770
Ted Kremenek41573eb2009-02-14 01:43:44 +00001771void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001772 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00001773 bool escapes = false;
1774
Ted Kremeneka496d162008-10-18 03:49:51 +00001775 // A value escapes in three possible cases (this may change):
1776 //
1777 // (1) we are binding to something that is not a memory region.
1778 // (2) we are binding to a memregion that does not have stack storage
1779 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00001780 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00001781 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00001782
Ted Kremenek41573eb2009-02-14 01:43:44 +00001783 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00001784 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00001785 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001786 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1787 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00001788
1789 if (!escapes) {
1790 // To test (3), generate a new state with the binding removed. If it is
1791 // the same state, then it escapes (since the store cannot represent
1792 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00001793 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00001794 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001795 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00001796
Ted Kremenek5216ad72009-02-14 03:16:10 +00001797 // If our store can represent the binding and we aren't storing to something
1798 // that doesn't have local storage then just return and have the simulation
1799 // state continue as is.
1800 if (!escapes)
1801 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00001802
Ted Kremenek5216ad72009-02-14 03:16:10 +00001803 // Otherwise, find all symbols referenced by 'val' that we are tracking
1804 // and stop tracking them.
1805 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00001806}
1807
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001808std::pair<GRStateRef,bool>
1809CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1810 const GRState* St, const Decl* CD,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001811 SymbolRef sid,
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001812 RefVal V, bool& hasLeak) {
Ted Kremenekdb863712008-04-16 22:32:20 +00001813
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001814 GRStateRef state(St, VMgr);
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001815 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001816 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001817
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001818 if (V.isReturnedOwned() && V.getCount() == 0)
1819 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00001820 std::string s = MD->getSelector().getAsString();
Ted Kremenek4c79e552008-11-05 16:54:44 +00001821 if (!followsReturnRule(s.c_str())) {
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001822 hasLeak = true;
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001823 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
1824 return std::make_pair(state, true);
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001825 }
1826 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001827
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001828 // All other cases.
1829
1830 hasLeak = V.isOwned() ||
1831 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001832
Ted Kremenekdb863712008-04-16 22:32:20 +00001833 if (!hasLeak)
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001834 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001835
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001836 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
1837 false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001838}
1839
Ted Kremenek652adc62008-04-24 23:57:27 +00001840
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001841
Ted Kremenek652adc62008-04-24 23:57:27 +00001842// Dead symbols.
1843
Ted Kremenekcf701772009-02-05 06:50:21 +00001844
Ted Kremenek652adc62008-04-24 23:57:27 +00001845
Ted Kremenek4fd88972008-04-17 18:12:53 +00001846 // Return statements.
1847
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001848void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001849 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001850 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001851 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001852 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001853
1854 Expr* RetE = S->getRetValue();
1855 if (!RetE) return;
1856
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001857 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001858 SVal V = state.GetSVal(RetE);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001859
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001860 if (!isa<loc::SymbolVal>(V))
Ted Kremenek4fd88972008-04-17 18:12:53 +00001861 return;
1862
1863 // Get the reference count binding (if any).
Ted Kremenek2dabd432008-12-05 02:27:51 +00001864 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001865 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001866
1867 if (!T)
1868 return;
1869
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001870 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001871 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001872
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001873 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001874 case RefVal::Owned: {
1875 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001876 assert (cnt > 0);
1877 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001878 break;
1879 }
1880
1881 case RefVal::NotOwned: {
1882 unsigned cnt = X.getCount();
1883 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1884 : RefVal::makeReturnedNotOwned();
1885 break;
1886 }
1887
1888 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001889 return;
1890 }
1891
1892 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001893 state = state.set<RefBindings>(Sym, X);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001894 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001895}
1896
Ted Kremenekcb612922008-04-18 19:23:43 +00001897// Assumptions.
1898
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001899const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
1900 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001901 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00001902 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00001903
1904 // FIXME: We may add to the interface of EvalAssume the list of symbols
1905 // whose assumptions have changed. For now we just iterate through the
1906 // bindings and check if any of the tracked symbols are NULL. This isn't
1907 // too bad since the number of symbols we will track in practice are
1908 // probably small and EvalAssume is only called at branches and a few
1909 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001910 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00001911
1912 if (B.isEmpty())
1913 return St;
1914
1915 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001916
1917 GRStateRef state(St, VMgr);
1918 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00001919
1920 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00001921 // Check if the symbol is null (or equal to any constant).
1922 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00001923 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00001924 changed = true;
1925 B = RefBFactory.Remove(B, I.getKey());
1926 }
1927 }
1928
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001929 if (changed)
1930 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00001931
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001932 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00001933}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001934
Ted Kremenek2dabd432008-12-05 02:27:51 +00001935RefBindings CFRefCount::Update(RefBindings B, SymbolRef sym,
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001936 RefVal V, ArgEffect E,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001937 RefVal::Kind& hasErr,
1938 RefBindings::Factory& RefBFactory) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00001939
1940 // In GC mode [... release] and [... retain] do nothing.
1941 switch (E) {
1942 default: break;
1943 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
1944 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00001945 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00001946 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001947
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001948 switch (E) {
1949 default:
1950 assert (false && "Unhandled CFRef transition.");
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001951
1952 case MayEscape:
1953 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00001954 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001955 break;
1956 }
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001957 // Fall-through.
Ted Kremenek070a8252008-07-09 18:11:16 +00001958 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001959 case DoNothing:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001960 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek553cf182008-06-25 21:21:56 +00001961 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001962 hasErr = V.getKind();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001963 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00001964 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001965 return B;
Ted Kremeneke19f4492008-06-30 16:57:41 +00001966
Ted Kremenekabf43972009-01-28 21:44:40 +00001967 case Autorelease:
1968 if (isGCEnabled()) return B;
1969 // Fall-through.
Ted Kremenek14993892008-05-06 02:41:27 +00001970 case StopTracking:
1971 return RefBFactory.Remove(B, sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00001972
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001973 case IncRef:
1974 switch (V.getKind()) {
1975 default:
1976 assert(false);
1977
1978 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001979 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00001980 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00001981 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001982 case RefVal::Released:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001983 if (isGCEnabled())
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00001984 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek65c91652008-04-29 05:44:10 +00001985 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00001986 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek65c91652008-04-29 05:44:10 +00001987 hasErr = V.getKind();
1988 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001989 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00001990 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001991 break;
1992
Ted Kremenek553cf182008-06-25 21:21:56 +00001993 case SelfOwn:
1994 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00001995 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001996 case DecRef:
1997 switch (V.getKind()) {
1998 default:
1999 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002000
Ted Kremenek553cf182008-06-25 21:21:56 +00002001 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002002 assert(V.getCount() > 0);
2003 if (V.getCount() == 1) V = V ^ RefVal::Released;
2004 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002005 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002006
Ted Kremenek553cf182008-06-25 21:21:56 +00002007 case RefVal::NotOwned:
2008 if (V.getCount() > 0)
2009 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00002010 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002011 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002012 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00002013 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002014 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002015
2016 case RefVal::Released:
Ted Kremenek553cf182008-06-25 21:21:56 +00002017 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002018 hasErr = V.getKind();
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002019 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002020 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002021 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002022 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002023 return RefBFactory.Add(B, sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002024}
2025
Ted Kremenekfa34b332008-04-09 01:10:13 +00002026//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002027// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00002028//===----------------------------------------------------------------------===//
2029
Ted Kremenek8dd56462008-04-18 03:39:05 +00002030namespace {
2031
2032 //===-------------===//
2033 // Bug Descriptions. //
2034 //===-------------===//
2035
Ted Kremenekcf118d42009-02-04 23:49:09 +00002036 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002037 protected:
2038 CFRefCount& TF;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002039
2040 CFRefBug(CFRefCount* tf, const char* name)
2041 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002042 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002043
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002044 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00002045 const CFRefCount& getTF() const { return TF; }
2046
Ted Kremenekcf118d42009-02-04 23:49:09 +00002047 // FIXME: Eventually remove.
2048 virtual const char* getDescription() const = 0;
2049
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002050 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002051 };
2052
2053 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2054 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002055 UseAfterRelease(CFRefCount* tf)
2056 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002057
Ted Kremenekcf118d42009-02-04 23:49:09 +00002058 const char* getDescription() const {
Ted Kremenek9e476de2008-08-12 18:30:56 +00002059 return "Reference-counted object is used after it is released.";
Ted Kremenekcf701772009-02-05 06:50:21 +00002060 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002061 };
2062
2063 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2064 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002065 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2066
2067 const char* getDescription() const {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002068 return "Incorrect decrement of the reference count of a "
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002069 "CoreFoundation object: "
Ted Kremenek8dd56462008-04-18 03:39:05 +00002070 "The object is not owned at this point by the caller.";
2071 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002072 };
2073
2074 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002075 const bool isReturn;
2076 protected:
2077 Leak(CFRefCount* tf, const char* name, bool isRet)
2078 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002079 public:
Ted Kremenek8dd56462008-04-18 03:39:05 +00002080
Ted Kremenekd3057212009-02-07 22:38:00 +00002081 const char* getDescription() const { return ""; }
Ted Kremenek3148eb42009-01-24 00:55:43 +00002082
Ted Kremeneke45e57f2009-02-05 00:38:00 +00002083 bool isLeak() const { return true; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002084 };
Ted Kremenekcf118d42009-02-04 23:49:09 +00002085
2086 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2087 public:
2088 LeakAtReturn(CFRefCount* tf, const char* name)
2089 : Leak(tf, name, true) {}
2090 };
2091
2092 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2093 public:
2094 LeakWithinFunction(CFRefCount* tf, const char* name)
2095 : Leak(tf, name, false) {}
2096 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002097
2098 //===---------===//
2099 // Bug Reports. //
2100 //===---------===//
2101
2102 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek66d97062009-02-07 22:04:05 +00002103 protected:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002104 SymbolRef Sym;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002105 const CFRefCount &TF;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002106 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002107 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2108 ExplodedNode<GRState> *n, SymbolRef sym)
2109 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002110
2111 virtual ~CFRefReport() {}
2112
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002113 CFRefBug& getBugType() {
2114 return (CFRefBug&) RangedBugReport::getBugType();
2115 }
2116 const CFRefBug& getBugType() const {
2117 return (const CFRefBug&) RangedBugReport::getBugType();
2118 }
2119
2120 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2121 const SourceRange*& end) {
2122
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002123 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002124 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002125 else
2126 beg = end = 0;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002127 }
2128
Ted Kremenek2dabd432008-12-05 02:27:51 +00002129 SymbolRef getSymbol() const { return Sym; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002130
Ted Kremenek3148eb42009-01-24 00:55:43 +00002131 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2132 const ExplodedNode<GRState>* N);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002133
Ted Kremenek3148eb42009-01-24 00:55:43 +00002134 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002135
Ted Kremenek3148eb42009-01-24 00:55:43 +00002136 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2137 const ExplodedNode<GRState>* PrevN,
2138 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002139 BugReporter& BR,
2140 NodeResolver& NR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002141 };
2142
Ted Kremenekcf118d42009-02-04 23:49:09 +00002143 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremeneke469fa02009-02-07 22:19:59 +00002144 SourceLocation AllocSite;
2145 const MemRegion* AllocBinding;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002146 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002147 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2148 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenekd3057212009-02-07 22:38:00 +00002149 GRExprEngine& Eng);
Ted Kremenek66d97062009-02-07 22:04:05 +00002150
2151 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2152 const ExplodedNode<GRState>* N);
2153
Ted Kremeneke469fa02009-02-07 22:19:59 +00002154 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekcf118d42009-02-04 23:49:09 +00002155 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002156} // end anonymous namespace
2157
Ted Kremenekcf118d42009-02-04 23:49:09 +00002158void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenekcf701772009-02-05 06:50:21 +00002159 useAfterRelease = new UseAfterRelease(this);
2160 BR.Register(useAfterRelease);
2161
2162 releaseNotOwned = new BadRelease(this);
2163 BR.Register(releaseNotOwned);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002164
2165 // First register "return" leaks.
2166 const char* name = 0;
2167
2168 if (isGCEnabled())
2169 name = "[naming convention] leak of returned object (GC)";
2170 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2171 name = "[naming convention] leak of returned object (hybrid MM, "
2172 "non-GC)";
2173 else {
2174 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2175 name = "[naming convention] leak of returned object";
2176 }
2177
Ted Kremenekcf701772009-02-05 06:50:21 +00002178 leakAtReturn = new LeakAtReturn(this, name);
2179 BR.Register(leakAtReturn);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002180
Ted Kremenekcf118d42009-02-04 23:49:09 +00002181 // Second, register leaks within a function/method.
2182 if (isGCEnabled())
2183 name = "leak (GC)";
2184 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2185 name = "leak (hybrid MM, non-GC)";
2186 else {
2187 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2188 name = "leak";
2189 }
2190
Ted Kremenekcf701772009-02-05 06:50:21 +00002191 leakWithinFunction = new LeakWithinFunction(this, name);
2192 BR.Register(leakWithinFunction);
2193
2194 // Save the reference to the BugReporter.
2195 this->BR = &BR;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002196}
Ted Kremenek072192b2008-04-30 23:47:44 +00002197
2198static const char* Msgs[] = {
2199 "Code is compiled in garbage collection only mode" // GC only
2200 " (the bug occurs with garbage collection enabled).",
2201
2202 "Code is compiled without garbage collection.", // No GC.
2203
2204 "Code is compiled for use with and without garbage collection (GC)."
2205 " The bug occurs with GC enabled.", // Hybrid, with GC.
2206
2207 "Code is compiled for use with and without garbage collection (GC)."
2208 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2209};
2210
2211std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2212 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2213
2214 switch (TF.getLangOptions().getGCMode()) {
2215 default:
2216 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002217
2218 case LangOptions::GCOnly:
2219 assert (TF.isGCEnabled());
Ted Kremenek9e476de2008-08-12 18:30:56 +00002220 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2221
Ted Kremenek072192b2008-04-30 23:47:44 +00002222 case LangOptions::NonGC:
2223 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002224 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2225
2226 case LangOptions::HybridGC:
2227 if (TF.isGCEnabled())
2228 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2229 else
2230 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2231 }
2232}
2233
Ted Kremenek27019002009-02-18 21:57:45 +00002234static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2235 ArgEffect X) {
2236 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2237 I!=E; ++I)
2238 if (*I == X) return true;
2239
2240 return false;
2241}
2242
Ted Kremenek3148eb42009-01-24 00:55:43 +00002243PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2244 const ExplodedNode<GRState>* PrevN,
2245 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002246 BugReporter& BR,
2247 NodeResolver& NR) {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002248
Ted Kremenek611a15a2009-01-28 05:29:13 +00002249 // Check if the type state has changed.
2250 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2251 GRStateRef PrevSt(PrevN->getState(), StMgr);
2252 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek20982802009-01-28 05:06:46 +00002253
Ted Kremenek611a15a2009-01-28 05:29:13 +00002254 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2255 if (!CurrT) return NULL;
2256
2257 const RefVal& CurrV = *CurrT;
2258 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenekce48e002008-05-05 17:53:17 +00002259
Ted Kremenek27019002009-02-18 21:57:45 +00002260 // Create a string buffer to constain all the useful things we want
2261 // to tell the user.
2262 std::string sbuf;
2263 llvm::raw_string_ostream os(sbuf);
2264
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002265 // This is the allocation site since the previous node had no bindings
2266 // for this symbol.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002267 if (!PrevT) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002268 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2269
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002270 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2271 // Get the name of the callee (if it is available).
2272 SVal X = CurrSt.GetSVal(CE->getCallee());
2273 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2274 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2275 else
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002276 os << "function call";
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002277 }
2278 else {
2279 assert (isa<ObjCMessageExpr>(S));
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002280 os << "Method";
Ted Kremenekce48e002008-05-05 17:53:17 +00002281 }
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002282
Ted Kremenek961b61d2009-01-28 06:06:36 +00002283 if (CurrV.getObjKind() == RetEffect::CF) {
2284 os << " returns a Core Foundation object with a ";
2285 }
2286 else {
2287 assert (CurrV.getObjKind() == RetEffect::ObjC);
2288 os << " returns an Objective-C object with a ";
2289 }
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002290
Ted Kremenek23b8eaa2009-01-28 06:25:48 +00002291 if (CurrV.isOwned()) {
2292 os << "+1 retain count (owning reference).";
2293
2294 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2295 assert(CurrV.getObjKind() == RetEffect::CF);
2296 os << " "
2297 "Core Foundation objects are not automatically garbage collected.";
2298 }
2299 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002300 else {
2301 assert (CurrV.isNotOwned());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002302 os << "+0 retain count (non-owning reference).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002303 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002304
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002305 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002306 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002307
2308 if (Expr* Exp = dyn_cast<Expr>(S))
2309 P->addRange(Exp->getSourceRange());
2310
2311 return P;
2312 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002313
Ted Kremenek27019002009-02-18 21:57:45 +00002314 // Gather up the effects that were performed on the object at this
2315 // program point
2316 llvm::SmallVector<ArgEffect, 2> AEffects;
2317
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002318 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2319 // We only have summaries attached to nodes after evaluating CallExpr and
2320 // ObjCMessageExprs.
2321 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2322
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002323 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2324 // Iterate through the parameter expressions and see if the symbol
2325 // was ever passed as an argument.
2326 unsigned i = 0;
2327
2328 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2329 AI!=AE; ++AI, ++i) {
Ted Kremenek27019002009-02-18 21:57:45 +00002330
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002331 // Retrieve the value of the arugment.
2332 SVal X = CurrSt.GetSVal(*AI);
Ted Kremenek27019002009-02-18 21:57:45 +00002333
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002334 // Is it the symbol we're interested in?
2335 if (!isa<loc::SymbolVal>(X) ||
2336 Sym != cast<loc::SymbolVal>(X).getSymbol())
2337 continue;
Ted Kremenek79c140b2008-04-18 05:32:44 +00002338
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002339 // We have an argument. Get the effect!
2340 AEffects.push_back(Summ->getArg(i));
Ted Kremenek79c140b2008-04-18 05:32:44 +00002341 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002342 }
2343 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2344 if (Expr *receiver = ME->getReceiver()) {
Ted Kremenek27019002009-02-18 21:57:45 +00002345 SVal RetV = CurrSt.GetSVal(receiver);
2346 if (isa<loc::SymbolVal>(RetV) &&
2347 Sym == cast<loc::SymbolVal>(RetV).getSymbol()) {
2348 // The symbol we are tracking is the receiver.
2349 AEffects.push_back(Summ->getReceiverEffect());
2350 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002351 }
2352 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002353 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002354
Ted Kremenek27019002009-02-18 21:57:45 +00002355 do {
2356 // Get the previous type state.
2357 RefVal PrevV = *PrevT;
2358
2359 // Specially handle CFMakeCollectable and friends.
2360 if (contains(AEffects, MakeCollectable)) {
2361 // Get the name of the function.
2362 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2363 loc::FuncVal FV =
2364 cast<loc::FuncVal>(CurrSt.GetSVal(cast<CallExpr>(S)->getCallee()));
2365 const std::string& FName = FV.getDecl()->getNameAsString();
2366
2367 if (TF.isGCEnabled()) {
2368 // Determine if the object's reference count was pushed to zero.
2369 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2370
2371 os << "In GC mode a call to '" << FName
2372 << "' decrements an object's retain count and registers the "
2373 "object with the garbage collector. ";
2374
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002375 if (CurrV.getKind() == RefVal::Released) {
2376 assert(CurrV.getCount() == 0);
2377 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek27019002009-02-18 21:57:45 +00002378 "automatically collected by the garbage collector.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002379 }
Ted Kremenek27019002009-02-18 21:57:45 +00002380 else
2381 os << "An object must have a 0 retain count to be garbage collected. "
2382 "After this call its retain count is +" << CurrV.getCount()
2383 << '.';
2384 }
2385 else
2386 os << "When GC is not enabled a call to '" << FName
2387 << "' has no effect on its argument.";
2388
2389 // Nothing more to say.
2390 break;
2391 }
2392
2393 // Determine if the typestate has changed.
2394 if (!(PrevV == CurrV))
2395 switch (CurrV.getKind()) {
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002396 case RefVal::Owned:
2397 case RefVal::NotOwned:
2398
2399 if (PrevV.getCount() == CurrV.getCount())
2400 return 0;
2401
2402 if (PrevV.getCount() > CurrV.getCount())
2403 os << "Reference count decremented.";
2404 else
2405 os << "Reference count incremented.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002406
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002407 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002408 os << " The object now has +" << Count;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002409
2410 if (Count > 1)
2411 os << " retain counts.";
2412 else
2413 os << " retain count.";
2414 }
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002415
2416 if (PrevV.getKind() == RefVal::Released) {
2417 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2418 os << " The object is not eligible for garbage collection until the "
2419 "retain count reaches 0 again.";
2420 }
2421
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002422 break;
2423
2424 case RefVal::Released:
2425 os << "Object released.";
2426 break;
2427
2428 case RefVal::ReturnedOwned:
2429 os << "Object returned to caller as an owning reference (single retain "
2430 "count transferred to caller).";
2431 break;
2432
2433 case RefVal::ReturnedNotOwned:
2434 os << "Object returned to caller with a +0 (non-owning) retain count.";
2435 break;
2436
2437 default:
2438 return NULL;
Ted Kremenek27019002009-02-18 21:57:45 +00002439 }
2440
2441 // Emit any remaining diagnostics for the argument effects (if any).
2442 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2443 E=AEffects.end(); I != E; ++I) {
2444
2445 // A bunch of things have alternate behavior under GC.
2446 if (TF.isGCEnabled())
2447 switch (*I) {
2448 default: break;
2449 case Autorelease:
2450 os << "In GC mode an 'autorelease' has no effect.";
2451 continue;
2452 case IncRefMsg:
2453 os << "In GC mode the 'retain' message has no effect.";
2454 continue;
2455 case DecRefMsg:
2456 os << "In GC mode the 'release' message has no effect.";
2457 continue;
2458 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002459 }
Ted Kremenek27019002009-02-18 21:57:45 +00002460 } while(0);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002461
2462 if (os.str().empty())
2463 return 0; // We have nothing to say!
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002464
2465 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2466 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002467 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002468
2469 // Add the range by scanning the children of the statement for any bindings
2470 // to Sym.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002471 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2472 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek20982802009-01-28 05:06:46 +00002473 SVal X = CurrSt.GetSVal(Exp);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002474 if (loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&X))
Ted Kremenek1f62ef32009-02-18 22:17:20 +00002475 if (SV->getSymbol() == Sym) {
2476 P->addRange(Exp->getSourceRange());
2477 break;
2478 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002479 }
2480
2481 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002482}
2483
Ted Kremenek9e240492008-10-04 05:50:14 +00002484namespace {
2485class VISIBILITY_HIDDEN FindUniqueBinding :
2486 public StoreManager::BindingsHandler {
Ted Kremenek2dabd432008-12-05 02:27:51 +00002487 SymbolRef Sym;
Ted Kremenek9e240492008-10-04 05:50:14 +00002488 MemRegion* Binding;
2489 bool First;
2490
2491 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002492 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenek9e240492008-10-04 05:50:14 +00002493
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002494 bool HandleBinding(StoreManager& SMgr, Store store, MemRegion* R, SVal val) {
2495 if (const loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002496 if (SV->getSymbol() != Sym)
2497 return true;
2498 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002499 else if (const nonloc::SymbolVal* SV=dyn_cast<nonloc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002500 if (SV->getSymbol() != Sym)
2501 return true;
2502 }
2503 else
2504 return true;
2505
2506 if (Binding) {
2507 First = false;
2508 return false;
2509 }
2510 else
2511 Binding = R;
2512
2513 return true;
2514 }
2515
2516 operator bool() { return First && Binding; }
2517 MemRegion* getRegion() { return Binding; }
2518};
2519}
2520
Ted Kremenek3148eb42009-01-24 00:55:43 +00002521static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremeneke469fa02009-02-07 22:19:59 +00002522GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002523 SymbolRef Sym) {
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002524
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002525 // Find both first node that referred to the tracked symbol and the
2526 // memory location that value was store to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002527 const ExplodedNode<GRState>* Last = N;
2528 const MemRegion* FirstBinding = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002529
2530 while (N) {
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002531 const GRState* St = N->getState();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002532 RefBindings B = St->get<RefBindings>();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002533
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002534 if (!B.lookup(Sym))
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002535 break;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002536
Ted Kremeneke469fa02009-02-07 22:19:59 +00002537 FindUniqueBinding FB(Sym);
2538 StateMgr.iterBindings(St, FB);
2539 if (FB) FirstBinding = FB.getRegion();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002540
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002541 Last = N;
2542 N = N->pred_empty() ? NULL : *(N->pred_begin());
2543 }
2544
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002545 return std::make_pair(Last, FirstBinding);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002546}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002547
Ted Kremenek3148eb42009-01-24 00:55:43 +00002548PathDiagnosticPiece*
2549CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002550
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002551 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002552 // Tell the BugReporter to report cases when the tracked symbol is
2553 // assigned to different variables, etc.
Ted Kremenekc0959972008-07-02 21:24:01 +00002554 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek66d97062009-02-07 22:04:05 +00002555 return RangedBugReport::getEndPath(BR, EndN);
2556}
2557
2558PathDiagnosticPiece*
2559CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2560
2561 GRBugReporter& BR = cast<GRBugReporter>(br);
2562 // Tell the BugReporter to report cases when the tracked symbol is
2563 // assigned to different variables, etc.
2564 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2565
2566 // We are reporting a leak. Walk up the graph to get to the first node where
2567 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002568 // is stored to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002569 const ExplodedNode<GRState>* AllocNode = 0;
2570 const MemRegion* FirstBinding = 0;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002571
2572 llvm::tie(AllocNode, FirstBinding) =
Ted Kremeneke469fa02009-02-07 22:19:59 +00002573 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002574
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002575 // Get the allocate site.
2576 assert (AllocNode);
2577 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002578
Ted Kremeneke28565b2008-05-05 18:50:19 +00002579 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002580 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002581
Ted Kremeneke28565b2008-05-05 18:50:19 +00002582 // Get the leak site. We may have multiple ExplodedNodes (one with the
2583 // leak) that occur on the same line number; if the node with the leak
2584 // has any immediate predecessor nodes with the same line number, find
2585 // any transitive-successors that have a different statement and use that
2586 // line number instead. This avoids emiting a diagnostic like:
2587 //
2588 // // 'y' is leaked.
2589 // int x = foo(y);
2590 //
2591 // instead we want:
2592 //
2593 // int x = foo(y);
2594 // // 'y' is leaked.
2595
2596 Stmt* S = getStmt(BR); // This is the statement where the leak occured.
2597 assert (S);
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002598 unsigned EndLine = SMgr.getInstantiationLineNumber(S->getLocStart());
Ted Kremeneke28565b2008-05-05 18:50:19 +00002599
Ted Kremeneke28565b2008-05-05 18:50:19 +00002600 // Generate the diagnostic.
Ted Kremenek572b2782009-02-18 22:59:04 +00002601 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenekc9e3d862009-02-07 21:59:45 +00002602 std::string sbuf;
2603 llvm::raw_string_ostream os(sbuf);
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002604
Ted Kremeneke28565b2008-05-05 18:50:19 +00002605 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002606
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002607 if (FirstBinding)
Ted Kremenek9e240492008-10-04 05:50:14 +00002608 os << " and stored into '" << FirstBinding->getString() << '\'';
2609
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002610 // Get the retain count.
2611 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2612
2613 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenek04f9d462008-12-02 01:26:07 +00002614 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2615 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2616 // to the caller for NS objects.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002617 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2618 os << " is returned from a method whose name ('"
Chris Lattner077bf5e2008-11-24 03:33:13 +00002619 << MD.getSelector().getAsString()
Ted Kremenek234a4c22009-01-07 00:39:56 +00002620 << "') does not contain 'copy' or otherwise starts with"
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002621 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002622 " in the Memory Management Guide for Cocoa (object leaked).";
2623 }
2624 else
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002625 os << " is no longer referenced after this point and has a retain count of"
2626 " +"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002627 << RV->getCount() << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002628
Ted Kremenek572b2782009-02-18 22:59:04 +00002629 return new PathDiagnosticPiece(L, os.str());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002630}
2631
Ted Kremenek989d5192008-04-17 23:43:50 +00002632
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002633CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2634 ExplodedNode<GRState> *n,
Ted Kremenekd3057212009-02-07 22:38:00 +00002635 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002636 : CFRefReport(D, tf, n, sym)
Ted Kremeneke469fa02009-02-07 22:19:59 +00002637{
2638
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002639 // Most bug reports are cached at the location where they occured.
2640 // With leaks, we want to unique them by the location where they were
Ted Kremeneke469fa02009-02-07 22:19:59 +00002641 // allocated, and only report a single path. To do this, we need to find
2642 // the allocation site of a piece of tracked memory, which we do via a
2643 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2644 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2645 // that all ancestor nodes that represent the allocation site have the
2646 // same SourceLocation.
2647 const ExplodedNode<GRState>* AllocNode = 0;
2648
2649 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekd3057212009-02-07 22:38:00 +00002650 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremeneke469fa02009-02-07 22:19:59 +00002651
Ted Kremeneke469fa02009-02-07 22:19:59 +00002652 // Get the SourceLocation for the allocation site.
Ted Kremenekd3057212009-02-07 22:38:00 +00002653 ProgramPoint P = AllocNode->getLocation();
Ted Kremeneke469fa02009-02-07 22:19:59 +00002654 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenekd3057212009-02-07 22:38:00 +00002655
2656 // Fill in the description of the bug.
2657 Description.clear();
2658 llvm::raw_string_ostream os(Description);
2659 SourceManager& SMgr = Eng.getContext().getSourceManager();
2660 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekc5c60002009-02-07 22:54:59 +00002661 os << "Potential leak of object allocated on line " << AllocLine;
2662
2663 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2664 if (AllocBinding)
2665 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002666}
2667
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002668//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00002669// Handle dead symbols and end-of-path.
2670//===----------------------------------------------------------------------===//
2671
2672void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2673 GREndPathNodeBuilder<GRState>& Builder) {
2674
2675 const GRState* St = Builder.getState();
2676 RefBindings B = St->get<RefBindings>();
2677
2678 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2679 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2680
2681 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2682 bool hasLeak = false;
2683
2684 std::pair<GRStateRef, bool> X =
2685 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2686 (*I).first, (*I).second, hasLeak);
2687
2688 St = X.first;
2689 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2690 }
2691
2692 if (Leaked.empty())
2693 return;
2694
2695 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2696
2697 if (!N)
2698 return;
2699
2700 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2701 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2702
2703 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2704 : leakWithinFunction);
2705 assert(BT && "BugType not initialized.");
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002706 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00002707 BR->EmitReport(report);
2708 }
2709}
2710
2711void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2712 GRExprEngine& Eng,
2713 GRStmtNodeBuilder<GRState>& Builder,
2714 ExplodedNode<GRState>* Pred,
2715 Stmt* S,
2716 const GRState* St,
2717 SymbolReaper& SymReaper) {
2718
2719 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
2720
2721 RefBindings B = St->get<RefBindings>();
2722 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2723
2724 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2725 E = SymReaper.dead_end(); I != E; ++I) {
2726
2727 const RefVal* T = B.lookup(*I);
2728 if (!T) continue;
2729
2730 bool hasLeak = false;
2731
2732 std::pair<GRStateRef, bool> X
2733 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
2734
2735 St = X.first;
2736
2737 if (hasLeak)
2738 Leaked.push_back(std::make_pair(*I,X.second));
2739 }
2740
2741 if (Leaked.empty())
2742 return;
2743
2744 ExplodedNode<GRState>* N = Builder.MakeNode(Dst, S, Pred, St);
2745
2746 if (!N)
2747 return;
2748
2749 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2750 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2751
2752 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2753 : leakWithinFunction);
2754 assert(BT && "BugType not initialized.");
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002755 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00002756 BR->EmitReport(report);
2757 }
2758}
2759
2760void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2761 GRStmtNodeBuilder<GRState>& Builder,
2762 Expr* NodeExpr, Expr* ErrorExpr,
2763 ExplodedNode<GRState>* Pred,
2764 const GRState* St,
2765 RefVal::Kind hasErr, SymbolRef Sym) {
2766 Builder.BuildSinks = true;
2767 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2768
2769 if (!N) return;
2770
2771 CFRefBug *BT = 0;
2772
2773 if (hasErr == RefVal::ErrorUseAfterRelease)
2774 BT = static_cast<CFRefBug*>(useAfterRelease);
2775 else {
2776 assert(hasErr == RefVal::ErrorReleaseNotOwned);
2777 BT = static_cast<CFRefBug*>(releaseNotOwned);
2778 }
2779
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002780 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00002781 report->addRange(ErrorExpr->getSourceRange());
2782 BR->EmitReport(report);
2783}
2784
2785//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00002786// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002787//===----------------------------------------------------------------------===//
2788
Ted Kremenek072192b2008-04-30 23:47:44 +00002789GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2790 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00002791 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00002792}