blob: 8e120afecc2618879b256917bdb056745cadddbc [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000042using llvm::CStrInCStrNoCase;
Ted Kremenek827f93b2008-03-06 00:08:09 +000043
Ted Kremenekb6f09542008-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 Kremenekb88ec272008-10-30 23:14:58 +000057 while (*s == '_') ++s;
Ted Kremenek35920ed2009-01-07 00:39:56 +000058 return CStrInCStrNoCase(s, "copy")
59 || CStrInCStrNoCase(s, "new") == s
60 || CStrInCStrNoCase(s, "alloc") == s;
Ted Kremenekcdd3bb22008-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 Kremenekb6f09542008-10-24 21:18:08 +000067
Ted Kremenek7d421f32008-04-09 23:49:11 +000068//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +000069// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +000070//===----------------------------------------------------------------------===//
71
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +000072static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +000073 IdentifierInfo* II = &Ctx.Idents.get(name);
74 return Ctx.Selectors.getSelector(0, &II);
75}
76
Ted Kremenek0e344d42008-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 Kremenek272aa852008-06-25 21:21:56 +000082//===----------------------------------------------------------------------===//
83// Type querying functions.
84//===----------------------------------------------------------------------===//
85
Ted Kremenek17144e82009-01-12 21:45:02 +000086static bool hasPrefix(const char* s, const char* prefix) {
87 if (!prefix)
88 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +000089
Ted Kremenek17144e82009-01-12 21:45:02 +000090 char c = *s;
91 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +000092
Ted Kremenek17144e82009-01-12 21:45:02 +000093 while (c != '\0' && cP != '\0') {
94 if (c != cP) break;
95 c = *(++s);
96 cP = *(++prefix);
97 }
Ted Kremenek62820d82008-05-07 20:06:41 +000098
Ted Kremenek17144e82009-01-12 21:45:02 +000099 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000100}
101
Ted Kremenek17144e82009-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 Kremenek4c5378c2008-07-15 16:50:12 +0000109
Ted Kremenek17144e82009-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 Kremenek4c5378c2008-07-15 16:50:12 +0000116 return false;
Ted Kremenek17144e82009-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 Kremenek4c5378c2008-07-15 16:50:12 +0000121 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000122
123 // Does the name start with the prefix?
124 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000125}
126
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000127//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000128// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000129//===----------------------------------------------------------------------===//
130
Ted Kremenek272aa852008-06-25 21:21:56 +0000131namespace {
132/// ArgEffect is used to summarize a function/method call's effect on a
133/// particular argument.
Ted Kremenek58dd95b2009-02-18 18:54:33 +0000134enum ArgEffect { IncRefMsg, IncRef,
135 DecRefMsg, DecRef,
Ted Kremenek2126bef2009-02-18 21:57:45 +0000136 MakeCollectable,
Ted Kremenek58dd95b2009-02-18 18:54:33 +0000137 DoNothing, DoNothingByRef,
Ted Kremenekede40b72008-07-09 18:11:16 +0000138 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek272aa852008-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 Kremeneka7338b42008-03-11 06:39:11 +0000143}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000144
Ted Kremeneka7338b42008-03-11 06:39:11 +0000145namespace llvm {
Ted Kremenek272aa852008-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 Kremeneka7338b42008-03-11 06:39:11 +0000154} // end llvm namespace
155
156namespace {
Ted Kremenek272aa852008-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 Kremeneka7338b42008-03-11 06:39:11 +0000161public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000162 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
163 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000164
165 enum ObjKind { CF, ObjC, AnyObj };
166
Ted Kremeneka7338b42008-03-11 06:39:11 +0000167private:
Ted Kremenek68621b92009-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 Kremenek827f93b2008-03-06 00:08:09 +0000174
Ted Kremeneka7338b42008-03-11 06:39:11 +0000175public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000176 Kind getKind() const { return K; }
177
178 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000179
180 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000181 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000182 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000183 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000184
Ted Kremenek272aa852008-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 Kremenek68621b92009-01-28 05:56:51 +0000191 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
192 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000193 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000194 static RetEffect MakeNotOwned(ObjKind o) {
195 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000196 }
197 static RetEffect MakeNoRet() {
198 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000199 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000200
Ted Kremenek272aa852008-06-25 21:21:56 +0000201 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000202 ID.AddInteger((unsigned)K);
203 ID.AddInteger((unsigned)O);
204 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000205 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000206};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000207
Ted Kremenek272aa852008-06-25 21:21:56 +0000208
209class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-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 Kremeneka7338b42008-03-11 06:39:11 +0000213 ArgEffects* Args;
Ted Kremenekbcaff792008-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 Kremenek272aa852008-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 Kremenek266d8b62008-05-06 02:26:56 +0000221 ArgEffect Receiver;
Ted Kremenek272aa852008-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 Kremeneka7338b42008-03-11 06:39:11 +0000226 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000227
Ted Kremenekf2717b02008-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 Kremeneka7338b42008-03-11 06:39:11 +0000232public:
233
Ted Kremenekbcaff792008-05-06 15:44:25 +0000234 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000235 ArgEffect ReceiverEff, bool endpath = false)
236 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
237 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000238
Ted Kremenek272aa852008-06-25 21:21:56 +0000239 /// getArg - Return the argument effect on the argument specified by
240 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000241 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000242
Ted Kremenekae855d42008-04-24 17:22:33 +0000243 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000244 return DefaultArgEffect;
Ted Kremenekae855d42008-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 Kremenek272aa852008-06-25 21:21:56 +0000249 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-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 Kremenekbcaff792008-05-06 15:44:25 +0000254 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000255
256 if (idx == I->first)
257 return I->second;
258 }
259
Ted Kremenekbcaff792008-05-06 15:44:25 +0000260 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000261 }
262
Ted Kremenek272aa852008-06-25 21:21:56 +0000263 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000264 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000265 return Ret;
266 }
267
Ted Kremenekf2717b02008-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 Kremenek272aa852008-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 Kremenek266d8b62008-05-06 02:26:56 +0000274 ArgEffect getReceiverEffect() const {
275 return Receiver;
276 }
277
Ted Kremenek2719e982008-06-17 02:43:46 +0000278 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000279
Ted Kremenek2719e982008-06-17 02:43:46 +0000280 ExprIterator begin_args() const { return Args->begin(); }
281 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000282
Ted Kremenek266d8b62008-05-06 02:26:56 +0000283 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000284 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000285 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000286 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000287 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000288 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000289 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000290 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000291 }
292
293 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000294 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000295 }
296};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000297} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000298
Ted Kremenek272aa852008-06-25 21:21:56 +0000299//===----------------------------------------------------------------------===//
300// Data structures for constructing summaries.
301//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000302
Ted Kremenek272aa852008-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 Kremenek84f010c2008-06-23 23:30:29 +0000320}
321
322namespace llvm {
Ted Kremenek272aa852008-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 Kremenek84f010c2008-06-23 23:30:29 +0000328
Ted Kremenek272aa852008-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 Kremenek84f010c2008-06-23 23:30:29 +0000353} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000354
Ted Kremenek84f010c2008-06-23 23:30:29 +0000355namespace {
Ted Kremenek272aa852008-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 Kremenek9449ca92008-08-12 20:41:56 +0000394
Ted Kremenek272aa852008-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 Kremeneka8c3c432008-05-05 22:11:16 +0000447
448 //==-----------------------------------------------------------------==//
449 // Typedefs.
450 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000451
Ted Kremeneka8c3c432008-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 Kremenek84f010c2008-06-23 23:30:29 +0000461 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000462
463 //==-----------------------------------------------------------------==//
464 // Data.
465 //==-----------------------------------------------------------------==//
466
Ted Kremenek272aa852008-06-25 21:21:56 +0000467 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000468 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000469
Ted Kremenekede40b72008-07-09 18:11:16 +0000470 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
471 /// "CFDictionaryCreate".
472 IdentifierInfo* CFDictionaryCreateII;
473
Ted Kremenek272aa852008-06-25 21:21:56 +0000474 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000475 const bool GCEnabled;
476
Ted Kremenek272aa852008-06-25 21:21:56 +0000477 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000478 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000479
Ted Kremenek272aa852008-06-25 21:21:56 +0000480 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000481 FuncSummariesTy FuncSummaries;
482
Ted Kremenek272aa852008-06-25 21:21:56 +0000483 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
484 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000485 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000486
Ted Kremenek272aa852008-06-25 21:21:56 +0000487 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000488 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000489
Ted Kremenek272aa852008-06-25 21:21:56 +0000490 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000491 ArgEffectsSetTy ArgEffectsSet;
492
Ted Kremenek272aa852008-06-25 21:21:56 +0000493 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
494 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000495 llvm::BumpPtrAllocator BPAlloc;
496
Ted Kremenek272aa852008-06-25 21:21:56 +0000497 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000498 ArgEffects ScratchArgs;
499
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000500 RetainSummary* StopSummary;
501
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000502 //==-----------------------------------------------------------------==//
503 // Methods.
504 //==-----------------------------------------------------------------==//
505
Ted Kremenek272aa852008-06-25 21:21:56 +0000506 /// getArgEffects - Returns a persistent ArgEffects object based on the
507 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000508 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000509
Ted Kremenek562c1302008-05-05 16:51:50 +0000510 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000511
512public:
Ted Kremenek17144e82009-01-12 21:45:02 +0000513 RetainSummary* getUnarySummary(FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000514
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000515 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
516 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000517 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000518
Ted Kremenek266d8b62008-05-06 02:26:56 +0000519 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000520 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000521 ArgEffect DefaultEff = MayEscape,
522 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000523
Ted Kremenek266d8b62008-05-06 02:26:56 +0000524 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000525 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000526 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000527 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000528 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000529
Ted Kremenekbcaff792008-05-06 15:44:25 +0000530 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000531 if (StopSummary)
532 return StopSummary;
533
534 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
535 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000536
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000537 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000538 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000539
Ted Kremenek272aa852008-06-25 21:21:56 +0000540 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000541
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000542 void InitializeClassMethodSummaries();
543 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000544
Ted Kremenek35920ed2009-01-07 00:39:56 +0000545 bool isTrackedObjectType(QualType T);
546
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000547private:
548
Ted Kremenekf2717b02008-07-18 17:24:20 +0000549 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
550 RetainSummary* Summ) {
551 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
552 }
553
Ted Kremenek272aa852008-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 Kremenek45642a42008-08-12 18:48:50 +0000562 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenekf2717b02008-07-18 17:24:20 +0000563
Ted Kremenek3d6ddbb2008-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 Kremenekf2717b02008-07-18 17:24:20 +0000571 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
572 }
Ted Kremenek45642a42008-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 Kremenek3d6ddbb2008-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 Kremenek45642a42008-08-12 18:48:50 +0000586 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000587 va_end(argp);
588 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000589
Ted Kremeneka7338b42008-03-11 06:39:11 +0000590public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000591
592 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000593 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000594 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000595 GCEnabled(gcenabled), StopSummary(0) {
596
597 InitializeClassMethodSummaries();
598 InitializeMethodSummaries();
599 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000600
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000601 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000602
Ted Kremenekd13c1872008-06-24 03:56:45 +0000603 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000604 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000605 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenek926abf22008-05-06 04:20:12 +0000606
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000607 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000608};
609
610} // end anonymous namespace
611
612//===----------------------------------------------------------------------===//
613// Implementation of checker data structures.
614//===----------------------------------------------------------------------===//
615
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000616RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-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 Kremenek42ea0322008-05-05 23:55:01 +0000622 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
623 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000624 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000625}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000626
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000627ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000628
Ted Kremenekae855d42008-04-24 17:22:33 +0000629 if (ScratchArgs.empty())
630 return NULL;
631
632 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000633 llvm::FoldingSetNodeID profile;
634 profile.Add(ScratchArgs);
635 void* InsertPos;
636
Ted Kremenekae855d42008-04-24 17:22:33 +0000637 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000638 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000639 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000640
Ted Kremenekae855d42008-04-24 17:22:33 +0000641 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000642 ScratchArgs.clear();
643 return &E->getValue();
644 }
645
646 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000647 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000648
649 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000650 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000651
652 ScratchArgs.clear();
653 return &E->getValue();
654}
655
Ted Kremenek266d8b62008-05-06 02:26:56 +0000656RetainSummary*
657RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000658 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000659 ArgEffect DefaultEff,
660 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000661
Ted Kremenekae855d42008-04-24 17:22:33 +0000662 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000663 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000664 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
665 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000666
Ted Kremenekae855d42008-04-24 17:22:33 +0000667 // Look up the uniqued summary, or create one if it doesn't exist.
668 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000669 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000670
671 if (Summ)
672 return Summ;
673
Ted Kremenekae855d42008-04-24 17:22:33 +0000674 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000675 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000676 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000677 SummarySet.InsertNode(Summ, InsertPos);
678
679 return Summ;
680}
681
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000682//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-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 Kremeneka8c3c432008-05-05 22:11:16 +0000710// Summary creation for functions (largely uses of Core Foundation).
711//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000712
Ted Kremenek17144e82009-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 Kremenekd13c1872008-06-24 03:56:45 +0000723RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000724
725 SourceLocation Loc = FD->getLocation();
726
727 if (!Loc.isFileID())
728 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000729
Ted Kremenekae855d42008-04-24 17:22:33 +0000730 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000731 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000732
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000733 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000734 return I->second;
735
736 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000737 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000738
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000739 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000740 // We generate "stop" summaries for implicitly defined functions.
741 if (FD->isImplicit()) {
742 S = getPersistentStopSummary();
743 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000744 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000745
Ted Kremenekc239b9c2009-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 Kremenek17144e82009-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 Kremenekcfc50c72008-10-22 20:54:52 +0000764 }
Ted Kremenek17144e82009-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 Kremenek7b293682009-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 Kremenekcf071252009-02-05 22:34:53 +0000832 CStrInCStrNoCase(FName, "SetValue") ||
833 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000834 ? MayEscape : DoNothing;
835
836 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000837 }
838 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000839 }
840 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000841
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000842 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000843 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000844}
845
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000846RetainSummary*
847RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
848 const char* FName) {
849
Ted Kremenek562c1302008-05-05 16:51:50 +0000850 if (strstr(FName, "Create") || strstr(FName, "Copy"))
851 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000852
Ted Kremenek562c1302008-05-05 16:51:50 +0000853 if (strstr(FName, "Get"))
854 return getCFSummaryGetRule(FD);
855
856 return 0;
857}
858
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000859RetainSummary*
Ted Kremenek17144e82009-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 Kremeneka8c3c432008-05-05 22:11:16 +0000866
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000867 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000868
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000869 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +0000870 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000871 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000872 return getPersistentSummary(RetEffect::MakeAlias(0),
873 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000874 }
875
876 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000877 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000878 return getPersistentSummary(RetEffect::MakeNoRet(),
879 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000880 }
881
882 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +0000883 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
884 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000885 }
886
887 default:
Ted Kremenek562c1302008-05-05 16:51:50 +0000888 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +0000889 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +0000890 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000891}
892
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000893RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000894 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-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 Kremenek68621b92009-01-28 05:56:51 +0000901 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000902}
903
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000904RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000905 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +0000906 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
907 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000908}
909
Ted Kremeneka7338b42008-03-11 06:39:11 +0000910//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000911// Summary creation for Selectors.
912//===----------------------------------------------------------------------===//
913
Ted Kremenekbcaff792008-05-06 15:44:25 +0000914RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000915RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +0000916 assert(ScratchArgs.empty());
917
Ted Kremenek802cfc72009-02-20 00:05:35 +0000918 // 'init' methods only return an alias if the return type is a location type.
919 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +0000920 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +0000921 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
922 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +0000923
Ted Kremenek272aa852008-06-25 21:21:56 +0000924 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +0000925 return Summ;
926}
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000927
Ted Kremenek272aa852008-06-25 21:21:56 +0000928
Ted Kremenekbcaff792008-05-06 15:44:25 +0000929RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000930RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
931 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000932
933 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +0000934
Ted Kremenek272aa852008-06-25 21:21:56 +0000935 // Look up a summary in our summary cache.
936 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000937
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000938 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +0000939 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +0000940
Ted Kremenek35920ed2009-01-07 00:39:56 +0000941 // "initXXX": pass-through for receiver.
Ted Kremenek42ea0322008-05-05 23:55:01 +0000942 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000943 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +0000944
Ted Kremenek988c4472008-06-02 17:14:13 +0000945 if (strncmp(s, "init", 4) == 0 || strncmp(s, "_init", 5) == 0)
Ted Kremenek35920ed2009-01-07 00:39:56 +0000946 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000947
Ted Kremenek35920ed2009-01-07 00:39:56 +0000948 // Look for methods that return an owned object.
949 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek5496f6d2008-05-07 04:25:59 +0000950 return 0;
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000951
Ted Kremenek35920ed2009-01-07 00:39:56 +0000952 if (followsFundamentalRule(s)) {
953 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +0000954 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000955 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +0000956 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000957 return Summ;
958 }
Ted Kremenekbcaff792008-05-06 15:44:25 +0000959
Ted Kremenek42ea0322008-05-05 23:55:01 +0000960 return 0;
961}
962
Ted Kremeneka7722b72008-05-06 21:26:51 +0000963RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000964RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
965 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +0000966
Ted Kremenek272aa852008-06-25 21:21:56 +0000967 // FIXME: Eventually we should properly do class method summaries, but
968 // it requires us being able to walk the type hierarchy. Unfortunately,
969 // we cannot do this with just an IdentifierInfo* for the class name.
970
Ted Kremeneka7722b72008-05-06 21:26:51 +0000971 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +0000972 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000973
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000974 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +0000975 return I->second;
976
Ted Kremenek4c479322008-05-06 23:07:13 +0000977 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +0000978}
979
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000980void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +0000981
982 assert (ScratchArgs.empty());
983
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000984 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +0000985 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000986
Ted Kremenek0e344d42008-05-06 00:30:21 +0000987 RetainSummary* Summ = getPersistentSummary(E);
988
Ted Kremenek272aa852008-06-25 21:21:56 +0000989 // Create the summaries for "alloc", "new", and "allocWithZone:" for
990 // NSObject and its derivatives.
991 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
992 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
993 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000994
995 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000996 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +0000997 GetNullarySelector("currentHandler", Ctx),
998 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +0000999
1000 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001001 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1002 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1003 GetUnarySelector("addObject", Ctx),
1004 getPersistentSummary(RetEffect::MakeNoRet(),
1005 DoNothing, DoNothing));
Ted Kremenek0e344d42008-05-06 00:30:21 +00001006}
1007
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001008void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001009
1010 assert (ScratchArgs.empty());
1011
Ted Kremeneka7722b72008-05-06 21:26:51 +00001012 // Create the "init" selector. It just acts as a pass-through for the
1013 // receiver.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001014 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
1015 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001016
1017 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001018 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001019 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001020
Ted Kremeneke44927e2008-07-01 17:21:27 +00001021 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001022
1023 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001024 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1025
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001026 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001027 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001028
Ted Kremenek266d8b62008-05-06 02:26:56 +00001029 // Create the "retain" selector.
1030 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001031 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001032 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001033
1034 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001035 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001036 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001037
1038 // Create the "drain" selector.
1039 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001040 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001041
1042 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001043 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001044 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001045
Ted Kremenek45642a42008-08-12 18:48:50 +00001046 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001047 RetainSummary *NSWindowSumm =
1048 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenek45642a42008-08-12 18:48:50 +00001049
1050 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1051 "styleMask", "backing", "defer", NULL);
1052
1053 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1054 "styleMask", "backing", "defer", "screen", NULL);
1055
1056 // For NSPanel (which subclasses NSWindow), allocated objects are not
1057 // self-owned.
1058 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1059 "styleMask", "backing", "defer", NULL);
1060
1061 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1062 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001063
Ted Kremenekf2717b02008-07-18 17:24:20 +00001064 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001065 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1066 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001067
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001068 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1069 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001070}
1071
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001072//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001073// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001074//===----------------------------------------------------------------------===//
1075
Ted Kremeneka7338b42008-03-11 06:39:11 +00001076namespace {
1077
Ted Kremenek7d421f32008-04-09 23:49:11 +00001078class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001079public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001080 enum Kind {
1081 Owned = 0, // Owning reference.
1082 NotOwned, // Reference is not owned by still valid (not freed).
1083 Released, // Object has been released.
1084 ReturnedOwned, // Returned object passes ownership to caller.
1085 ReturnedNotOwned, // Return object does not pass ownership to caller.
1086 ErrorUseAfterRelease, // Object used after released.
1087 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek311f3d42008-10-22 23:56:21 +00001088 ErrorLeak, // A memory leak due to excessive reference counts.
1089 ErrorLeakReturned // A memory leak due to the returning method not having
1090 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001091 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001092
1093private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001094 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001095 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001096 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001097 QualType T;
1098
Ted Kremenek68621b92009-01-28 05:56:51 +00001099 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1100 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001101
Ted Kremenek68621b92009-01-28 05:56:51 +00001102 RefVal(Kind k, unsigned cnt = 0)
1103 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1104
1105public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001106 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001107
1108 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001109
Ted Kremenek272aa852008-06-25 21:21:56 +00001110 unsigned getCount() const { return Cnt; }
1111 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001112
1113 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001114
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001115 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1116
Ted Kremenek0106e202008-10-24 20:32:50 +00001117 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001118
Ted Kremenekffefc352008-04-11 22:25:11 +00001119 bool isOwned() const {
1120 return getKind() == Owned;
1121 }
1122
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001123 bool isNotOwned() const {
1124 return getKind() == NotOwned;
1125 }
1126
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001127 bool isReturnedOwned() const {
1128 return getKind() == ReturnedOwned;
1129 }
1130
1131 bool isReturnedNotOwned() const {
1132 return getKind() == ReturnedNotOwned;
1133 }
1134
1135 bool isNonLeakError() const {
1136 Kind k = getKind();
1137 return isError(k) && !isLeak(k);
1138 }
1139
1140 // State creation: normal state.
1141
Ted Kremenek68621b92009-01-28 05:56:51 +00001142 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1143 unsigned Count = 1) {
1144 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001145 }
1146
Ted Kremenek68621b92009-01-28 05:56:51 +00001147 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1148 unsigned Count = 0) {
1149 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001150 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001151
1152 static RefVal makeReturnedOwned(unsigned Count) {
1153 return RefVal(ReturnedOwned, Count);
1154 }
1155
1156 static RefVal makeReturnedNotOwned() {
1157 return RefVal(ReturnedNotOwned);
1158 }
1159
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001160 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001161
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001162 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001163 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001164 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001165
Ted Kremenek272aa852008-06-25 21:21:56 +00001166 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001167 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001168 }
1169
1170 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001171 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001172 }
1173
1174 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001175 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001176 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001177
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001178 void Profile(llvm::FoldingSetNodeID& ID) const {
1179 ID.AddInteger((unsigned) kind);
1180 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001181 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001182 }
1183
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001184 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001185};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001186
1187void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001188 if (!T.isNull())
1189 Out << "Tracked Type:" << T.getAsString() << '\n';
1190
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001191 switch (getKind()) {
1192 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001193 case Owned: {
1194 Out << "Owned";
1195 unsigned cnt = getCount();
1196 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001197 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001198 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001199
Ted Kremenekc4f81022008-04-10 23:09:18 +00001200 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001201 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001202 unsigned cnt = getCount();
1203 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001204 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001205 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001206
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001207 case ReturnedOwned: {
1208 Out << "ReturnedOwned";
1209 unsigned cnt = getCount();
1210 if (cnt) Out << " (+ " << cnt << ")";
1211 break;
1212 }
1213
1214 case ReturnedNotOwned: {
1215 Out << "ReturnedNotOwned";
1216 unsigned cnt = getCount();
1217 if (cnt) Out << " (+ " << cnt << ")";
1218 break;
1219 }
1220
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001221 case Released:
1222 Out << "Released";
1223 break;
1224
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001225 case ErrorLeak:
1226 Out << "Leaked";
1227 break;
1228
Ted Kremenek311f3d42008-10-22 23:56:21 +00001229 case ErrorLeakReturned:
1230 Out << "Leaked (Bad naming)";
1231 break;
1232
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001233 case ErrorUseAfterRelease:
1234 Out << "Use-After-Release [ERROR]";
1235 break;
1236
1237 case ErrorReleaseNotOwned:
1238 Out << "Release of Not-Owned [ERROR]";
1239 break;
1240 }
1241}
Ted Kremenek0d721572008-03-11 17:48:22 +00001242
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001243} // end anonymous namespace
1244
1245//===----------------------------------------------------------------------===//
1246// RefBindings - State used to track object reference counts.
1247//===----------------------------------------------------------------------===//
1248
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001249typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001250static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001251static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001252
1253namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001254 template<>
1255 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1256 static inline void* GDMIndex() { return &RefBIndex; }
1257 };
1258}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001259
1260//===----------------------------------------------------------------------===//
1261// ARBindings - State used to track objects in autorelease pools.
1262//===----------------------------------------------------------------------===//
1263
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001264typedef llvm::ImmutableSet<SymbolRef> ARPoolContents;
1265typedef llvm::ImmutableList< std::pair<SymbolRef, ARPoolContents*> > ARBindings;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001266static int AutoRBIndex = 0;
1267
1268namespace clang {
1269 template<>
1270 struct GRStateTrait<ARBindings> : public GRStatePartialTrait<ARBindings> {
1271 static inline void* GDMIndex() { return &AutoRBIndex; }
1272 };
1273}
1274
Ted Kremenek7aef4842008-04-16 20:40:59 +00001275//===----------------------------------------------------------------------===//
1276// Transfer functions.
1277//===----------------------------------------------------------------------===//
1278
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001279namespace {
1280
Ted Kremenek7d421f32008-04-09 23:49:11 +00001281class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001282public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001283 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001284 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001285 virtual void Print(std::ostream& Out, const GRState* state,
1286 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001287 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001288
1289private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001290 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1291 SummaryLogTy;
1292
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001293 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001294 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001295 const LangOptions& LOpts;
Ted Kremenek91781202008-08-17 03:20:02 +00001296
Ted Kremenek708af042009-02-05 06:50:21 +00001297 BugType *useAfterRelease, *releaseNotOwned;
1298 BugType *leakWithinFunction, *leakAtReturn;
1299 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001300
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001301 RefBindings Update(RefBindings B, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenek91781202008-08-17 03:20:02 +00001302 RefVal::Kind& hasErr, RefBindings::Factory& RefBFactory);
Ted Kremenek1feab292008-04-16 04:28:53 +00001303
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001304 RefVal::Kind& Update(GRStateRef& state, SymbolRef sym, RefVal V,
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001305 ArgEffect E, RefVal::Kind& hasErr) {
1306
1307 state = state.set<RefBindings>(Update(state.get<RefBindings>(), sym, V,
Ted Kremenek91781202008-08-17 03:20:02 +00001308 E, hasErr,
1309 state.get_context<RefBindings>()));
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001310 return hasErr;
1311 }
1312
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001313 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1314 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001315 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001316 ExplodedNode<GRState>* Pred,
1317 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001318 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001319
Ted Kremenek0106e202008-10-24 20:32:50 +00001320 std::pair<GRStateRef, bool>
1321 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001322 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001323
Ted Kremeneka7338b42008-03-11 06:39:11 +00001324public:
Ted Kremenek7aef4842008-04-16 20:40:59 +00001325
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001326 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001327 : Summaries(Ctx, gcenabled),
Ted Kremenek708af042009-02-05 06:50:21 +00001328 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1329 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001330
Ted Kremenek708af042009-02-05 06:50:21 +00001331 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001332
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001333 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001334
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001335 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1336 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001337 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001338
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001339 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001340 const LangOptions& getLangOptions() const { return LOpts; }
1341
Ted Kremenekc26c4692009-02-18 03:48:14 +00001342 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1343 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1344 return I == SummaryLog.end() ? 0 : I->second;
1345 }
1346
Ted Kremeneka7338b42008-03-11 06:39:11 +00001347 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001348
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001349 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001350 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001351 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001352 Expr* Ex,
1353 Expr* Receiver,
1354 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001355 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001356 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001357
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001358 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001359 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001360 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001361 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001362 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001363
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001364
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001365 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001366 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001367 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001368 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001369 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001370
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001371 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001372 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001373 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001374 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001375 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001376
Ted Kremeneka42be302009-02-14 01:43:44 +00001377 // Stores.
1378 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1379
Ted Kremenekffefc352008-04-11 22:25:11 +00001380 // End-of-path.
1381
1382 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001383 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001384
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001385 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001386 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001387 GRStmtNodeBuilder<GRState>& Builder,
1388 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001389 Stmt* S, const GRState* state,
1390 SymbolReaper& SymReaper);
1391
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001392 // Return statements.
1393
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001394 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001395 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001396 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001397 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001398 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001399
1400 // Assumptions.
1401
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001402 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001403 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001404 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001405};
1406
1407} // end anonymous namespace
1408
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001409
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001410void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1411 const char* nl, const char* sep) {
1412
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001413 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001414
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001415 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001416 Out << sep << nl;
1417
1418 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1419 Out << (*I).first << " : ";
1420 (*I).second.print(Out);
1421 Out << nl;
1422 }
1423}
1424
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001425static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001426 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001427}
1428
Ted Kremenek266d8b62008-05-06 02:26:56 +00001429static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1430 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001431}
1432
Ted Kremenek227c5372008-05-06 02:41:27 +00001433static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1434 return Summ ? Summ->getReceiverEffect() : DoNothing;
1435}
1436
Ted Kremenekf2717b02008-07-18 17:24:20 +00001437static inline bool IsEndPath(RetainSummary* Summ) {
1438 return Summ ? Summ->isEndPath() : false;
1439}
1440
Ted Kremenek1feab292008-04-16 04:28:53 +00001441
Ted Kremenek272aa852008-06-25 21:21:56 +00001442/// GetReturnType - Used to get the return type of a message expression or
1443/// function call with the intention of affixing that type to a tracked symbol.
1444/// While the the return type can be queried directly from RetEx, when
1445/// invoking class methods we augment to the return type to be that of
1446/// a pointer to the class (as opposed it just being id).
1447static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1448
1449 QualType RetTy = RetE->getType();
1450
1451 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001452 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001453 if (!PT)
1454 return RetTy;
1455
1456 // If RetEx is not a message expression just return its type.
1457 // If RetEx is a message expression, return its types if it is something
1458 /// more specific than id.
1459
1460 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1461
Steve Naroff17c03822009-02-12 17:52:19 +00001462 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001463 return RetTy;
1464
1465 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1466
1467 // At this point we know the return type of the message expression is id.
1468 // If we have an ObjCInterceDecl, we know this is a call to a class method
1469 // whose type we can resolve. In such cases, promote the return type to
1470 // Class*.
1471 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1472}
1473
1474
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001475void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001476 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001477 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001478 Expr* Ex,
1479 Expr* Receiver,
1480 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001481 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001482 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001483
Ted Kremeneka7338b42008-03-11 06:39:11 +00001484 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001485 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001486 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001487
1488 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001489 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001490 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001491 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001492 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001493
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001494 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001495 SVal V = state.GetSVal(*I);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001496
Zhongxing Xu097fc982008-10-17 05:57:07 +00001497 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001498 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001499 if (RefBindings::data_type* T = state.get<RefBindings>(Sym))
1500 if (Update(state, Sym, *T, GetArgE(Summ, idx), hasErr)) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001501 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001502 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001503 break;
1504 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001505 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001506 else if (isa<Loc>(V)) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001507 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001508
1509 if (GetArgE(Summ, idx) == DoNothingByRef)
1510 continue;
1511
1512 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001513
1514 // FIXME: Either this logic should also be replicated in GRSimpleVals
1515 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001516
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001517 // FIXME: We can have collisions on the conjured symbol if the
1518 // expression *I also creates conjured symbols. We probably want
1519 // to identify conjured symbols by an expression pair: the enclosing
1520 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001521 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001522
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001523 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001524
1525 // Blast through AnonTypedRegions to get the original region type.
1526 while (R) {
1527 const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R);
1528 if (!ATR) break;
1529 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1530 }
1531
Ted Kremenekb15eba42008-10-04 05:50:14 +00001532 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001533
1534 // Is the invalidated variable something that we were tracking?
1535 SVal X = state.GetSVal(Loc::MakeVal(R));
1536
1537 if (isa<loc::SymbolVal>(X)) {
1538 SymbolRef Sym = cast<loc::SymbolVal>(X).getSymbol();
1539 state = state.remove<RefBindings>(Sym);
1540 }
1541
Ted Kremenekb15eba42008-10-04 05:50:14 +00001542 // Set the value of the variable to be a conjured symbol.
1543 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekf5da3252008-12-13 21:49:13 +00001544 QualType T = R->getRValueType(Ctx);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001545
Ted Kremenek8f90e712008-10-17 22:23:12 +00001546 // FIXME: handle structs.
Ted Kremenek79413a52008-11-13 06:10:40 +00001547 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001548 SymbolRef NewSym =
Ted Kremenek8f90e712008-10-17 22:23:12 +00001549 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1550
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001551 state = state.BindLoc(Loc::MakeVal(R),
Ted Kremenek8f90e712008-10-17 22:23:12 +00001552 Loc::IsLocType(T)
1553 ? cast<SVal>(loc::SymbolVal(NewSym))
1554 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1555 }
1556 else {
Ted Kremenek09102db2008-11-12 19:22:09 +00001557 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8f90e712008-10-17 22:23:12 +00001558 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001559 }
1560 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001561 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001562 }
1563 else {
1564 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001565 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001566 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001567 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001568 else if (isa<nonloc::LocAsInteger>(V))
1569 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001570 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001571
Ted Kremenek272aa852008-06-25 21:21:56 +00001572 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001573 if (!ErrorExpr && Receiver) {
Zhongxing Xu097fc982008-10-17 05:57:07 +00001574 SVal V = state.GetSVal(Receiver);
1575 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001576 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001577 if (const RefVal* T = state.get<RefBindings>(Sym))
1578 if (Update(state, Sym, *T, GetReceiverE(Summ), hasErr)) {
Ted Kremenek227c5372008-05-06 02:41:27 +00001579 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001580 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001581 }
Ted Kremenek227c5372008-05-06 02:41:27 +00001582 }
1583 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001584
Ted Kremenek272aa852008-06-25 21:21:56 +00001585 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001586 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001587 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001588 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001589 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001590 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001591
Ted Kremenekf2717b02008-07-18 17:24:20 +00001592 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001593 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001594
1595 switch (RE.getKind()) {
1596 default:
1597 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001598
Ted Kremenek8f90e712008-10-17 22:23:12 +00001599 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001600
Ted Kremenek455dd862008-04-11 20:23:24 +00001601 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001602 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1603 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001604
Ted Kremenek8f90e712008-10-17 22:23:12 +00001605 // FIXME: We eventually should handle structs and other compound types
1606 // that are returned by value.
1607
1608 QualType T = Ex->getType();
1609
Ted Kremenek79413a52008-11-13 06:10:40 +00001610 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001611 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001612 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001613
Ted Kremenek802cfc72009-02-20 00:05:35 +00001614 SVal X = Loc::IsLocType(T)
Zhongxing Xu097fc982008-10-17 05:57:07 +00001615 ? cast<SVal>(loc::SymbolVal(Sym))
1616 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001617
Ted Kremenek09102db2008-11-12 19:22:09 +00001618 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001619 }
1620
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001621 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00001622 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001623
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001624 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001625 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001626 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001627 assert (idx < (unsigned) (arg_end - arg_beg));
Zhongxing Xu097fc982008-10-17 05:57:07 +00001628 SVal V = state.GetSVal(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00001629 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001630 break;
1631 }
1632
Ted Kremenek227c5372008-05-06 02:41:27 +00001633 case RetEffect::ReceiverAlias: {
1634 assert (Receiver);
Zhongxing Xu097fc982008-10-17 05:57:07 +00001635 SVal V = state.GetSVal(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00001636 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00001637 break;
1638 }
1639
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001640 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001641 case RetEffect::OwnedSymbol: {
1642 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001643 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek68621b92009-01-28 05:56:51 +00001644 QualType RetT = GetReturnType(Ex, Eng.getContext());
1645 state =
1646 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001647 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001648
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001649 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremeneke62fd052009-01-28 22:27:59 +00001650 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1651 bool isFeasible;
1652 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1653 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1654 }
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001655
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001656 break;
1657 }
1658
1659 case RetEffect::NotOwnedSymbol: {
1660 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001661 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001662 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001663
Ted Kremenek68621b92009-01-28 05:56:51 +00001664 state =
1665 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001666 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001667 break;
1668 }
1669 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001670
Ted Kremenek0dd65012009-02-18 02:00:25 +00001671 // Generate a sink node if we are at the end of a path.
1672 GRExprEngine::NodeTy *NewNode =
1673 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1674 : Builder.MakeNode(Dst, Ex, Pred, state);
1675
1676 // Annotate the edge with summary we used.
1677 // FIXME: This assumes that we always use the same summary when generating
1678 // this node.
1679 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001680}
1681
1682
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001683void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001684 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001685 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001686 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001687 ExplodedNode<GRState>* Pred) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001688
Zhongxing Xu097fc982008-10-17 05:57:07 +00001689 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1690 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001691
1692 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1693 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001694}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001695
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001696void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001697 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001698 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001699 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001700 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00001701 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001702
Ted Kremenek272aa852008-06-25 21:21:56 +00001703 if (Expr* Receiver = ME->getReceiver()) {
1704 // We need the type-information of the tracked receiver object
1705 // Retrieve it from the state.
1706 ObjCInterfaceDecl* ID = 0;
1707
1708 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1709 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001710 const GRState* St = Builder.GetState(Pred);
Zhongxing Xu097fc982008-10-17 05:57:07 +00001711 SVal V = Eng.getStateManager().GetSVal(St, Receiver );
Ted Kremenek272aa852008-06-25 21:21:56 +00001712
Zhongxing Xu097fc982008-10-17 05:57:07 +00001713 if (isa<loc::SymbolVal>(V)) {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001714 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek272aa852008-06-25 21:21:56 +00001715
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001716 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00001717 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001718
1719 if (const PointerType* PT = Ty->getAsPointerType()) {
1720 QualType PointeeTy = PT->getPointeeType();
1721
1722 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1723 ID = IT->getDecl();
1724 }
1725 }
1726 }
1727
1728 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00001729
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001730 // Special-case: are we sending a mesage to "self"?
1731 // This is a hack. When we have full-IP this should be removed.
1732 if (!Summ) {
1733 ObjCMethodDecl* MD =
1734 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1735
1736 if (MD) {
1737 if (Expr* Receiver = ME->getReceiver()) {
1738 SVal X = Eng.getStateManager().GetSVal(St, Receiver);
1739 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00001740 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1741 // Create a summmary where all of the arguments "StopTracking".
1742 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1743 DoNothing,
1744 StopTracking);
1745 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001746 }
1747 }
1748 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001749 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001750 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001751 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1752 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001753
Ted Kremenek926abf22008-05-06 04:20:12 +00001754 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1755 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001756}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001757
1758namespace {
1759class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1760 GRStateRef state;
1761public:
1762 StopTrackingCallback(GRStateRef st) : state(st) {}
1763 GRStateRef getState() { return state; }
1764
1765 bool VisitSymbol(SymbolRef sym) {
1766 state = state.remove<RefBindings>(sym);
1767 return true;
1768 }
Ted Kremenek926abf22008-05-06 04:20:12 +00001769
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001770 const GRState* getState() const { return state.getState(); }
1771};
1772} // end anonymous namespace
1773
1774
Ted Kremeneka42be302009-02-14 01:43:44 +00001775void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00001776 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00001777 bool escapes = false;
1778
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001779 // A value escapes in three possible cases (this may change):
1780 //
1781 // (1) we are binding to something that is not a memory region.
1782 // (2) we are binding to a memregion that does not have stack storage
1783 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00001784 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00001785 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001786
Ted Kremeneka42be302009-02-14 01:43:44 +00001787 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00001788 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00001789 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00001790 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1791 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001792
1793 if (!escapes) {
1794 // To test (3), generate a new state with the binding removed. If it is
1795 // the same state, then it escapes (since the store cannot represent
1796 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00001797 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001798 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001799 }
Ted Kremeneka42be302009-02-14 01:43:44 +00001800
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001801 // If our store can represent the binding and we aren't storing to something
1802 // that doesn't have local storage then just return and have the simulation
1803 // state continue as is.
1804 if (!escapes)
1805 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001806
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001807 // Otherwise, find all symbols referenced by 'val' that we are tracking
1808 // and stop tracking them.
1809 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001810}
1811
Ted Kremenek0106e202008-10-24 20:32:50 +00001812std::pair<GRStateRef,bool>
1813CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1814 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001815 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00001816 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001817
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001818 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00001819 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00001820 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001821
Ted Kremenek311f3d42008-10-22 23:56:21 +00001822 if (V.isReturnedOwned() && V.getCount() == 0)
1823 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00001824 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00001825 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00001826 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00001827 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
1828 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00001829 }
1830 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001831
Ted Kremenek311f3d42008-10-22 23:56:21 +00001832 // All other cases.
1833
1834 hasLeak = V.isOwned() ||
1835 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001836
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001837 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00001838 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001839
Ted Kremenek0106e202008-10-24 20:32:50 +00001840 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
1841 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001842}
1843
Ted Kremenek541db372008-04-24 23:57:27 +00001844
Ted Kremenekffefc352008-04-11 22:25:11 +00001845
Ted Kremenek541db372008-04-24 23:57:27 +00001846// Dead symbols.
1847
Ted Kremenek708af042009-02-05 06:50:21 +00001848
Ted Kremenek541db372008-04-24 23:57:27 +00001849
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001850 // Return statements.
1851
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001852void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001853 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001854 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001855 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001856 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001857
1858 Expr* RetE = S->getRetValue();
1859 if (!RetE) return;
1860
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001861 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Zhongxing Xu097fc982008-10-17 05:57:07 +00001862 SVal V = state.GetSVal(RetE);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001863
Zhongxing Xu097fc982008-10-17 05:57:07 +00001864 if (!isa<loc::SymbolVal>(V))
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001865 return;
1866
1867 // Get the reference count binding (if any).
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001868 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001869 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001870
1871 if (!T)
1872 return;
1873
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001874 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00001875 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001876
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001877 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001878 case RefVal::Owned: {
1879 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001880 assert (cnt > 0);
1881 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001882 break;
1883 }
1884
1885 case RefVal::NotOwned: {
1886 unsigned cnt = X.getCount();
1887 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1888 : RefVal::makeReturnedNotOwned();
1889 break;
1890 }
1891
1892 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001893 return;
1894 }
1895
1896 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00001897 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001898 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001899}
1900
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001901// Assumptions.
1902
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001903const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
1904 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001905 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001906 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001907
1908 // FIXME: We may add to the interface of EvalAssume the list of symbols
1909 // whose assumptions have changed. For now we just iterate through the
1910 // bindings and check if any of the tracked symbols are NULL. This isn't
1911 // too bad since the number of symbols we will track in practice are
1912 // probably small and EvalAssume is only called at branches and a few
1913 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001914 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001915
1916 if (B.isEmpty())
1917 return St;
1918
1919 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00001920
1921 GRStateRef state(St, VMgr);
1922 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001923
1924 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001925 // Check if the symbol is null (or equal to any constant).
1926 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00001927 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001928 changed = true;
1929 B = RefBFactory.Remove(B, I.getKey());
1930 }
1931 }
1932
Ted Kremenek91781202008-08-17 03:20:02 +00001933 if (changed)
1934 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001935
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001936 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001937}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001938
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001939RefBindings CFRefCount::Update(RefBindings B, SymbolRef sym,
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001940 RefVal V, ArgEffect E,
Ted Kremenek91781202008-08-17 03:20:02 +00001941 RefVal::Kind& hasErr,
1942 RefBindings::Factory& RefBFactory) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001943
1944 // In GC mode [... release] and [... retain] do nothing.
1945 switch (E) {
1946 default: break;
1947 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
1948 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00001949 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001950 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001951
Ted Kremenek0d721572008-03-11 17:48:22 +00001952 switch (E) {
1953 default:
1954 assert (false && "Unhandled CFRef transition.");
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001955
1956 case MayEscape:
1957 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00001958 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001959 break;
1960 }
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001961 // Fall-through.
Ted Kremenekede40b72008-07-09 18:11:16 +00001962 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00001963 case DoNothing:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001964 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek272aa852008-06-25 21:21:56 +00001965 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00001966 hasErr = V.getKind();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001967 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001968 }
Ted Kremenek0d721572008-03-11 17:48:22 +00001969 return B;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00001970
Ted Kremenek9b112d22009-01-28 21:44:40 +00001971 case Autorelease:
1972 if (isGCEnabled()) return B;
1973 // Fall-through.
Ted Kremenek227c5372008-05-06 02:41:27 +00001974 case StopTracking:
1975 return RefBFactory.Remove(B, sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001976
Ted Kremenek0d721572008-03-11 17:48:22 +00001977 case IncRef:
1978 switch (V.getKind()) {
1979 default:
1980 assert(false);
1981
1982 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00001983 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00001984 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001985 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00001986 case RefVal::Released:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001987 if (isGCEnabled())
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00001988 V = (V ^ RefVal::Owned) + 1;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00001989 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00001990 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00001991 hasErr = V.getKind();
1992 }
Ted Kremenek0d721572008-03-11 17:48:22 +00001993 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001994 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001995 break;
1996
Ted Kremenek272aa852008-06-25 21:21:56 +00001997 case SelfOwn:
1998 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001999 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002000 case DecRef:
2001 switch (V.getKind()) {
2002 default:
2003 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002004
Ted Kremenek272aa852008-06-25 21:21:56 +00002005 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002006 assert(V.getCount() > 0);
2007 if (V.getCount() == 1) V = V ^ RefVal::Released;
2008 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002009 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002010
Ted Kremenek272aa852008-06-25 21:21:56 +00002011 case RefVal::NotOwned:
2012 if (V.getCount() > 0)
2013 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002014 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002015 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002016 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002017 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002018 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002019
2020 case RefVal::Released:
Ted Kremenek272aa852008-06-25 21:21:56 +00002021 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002022 hasErr = V.getKind();
Ted Kremenek0d721572008-03-11 17:48:22 +00002023 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002024 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002025 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002026 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002027 return RefBFactory.Add(B, sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002028}
2029
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002030//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002031// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002032//===----------------------------------------------------------------------===//
2033
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002034namespace {
2035
2036 //===-------------===//
2037 // Bug Descriptions. //
2038 //===-------------===//
2039
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002040 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002041 protected:
2042 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002043
2044 CFRefBug(CFRefCount* tf, const char* name)
2045 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002046 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002047
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002048 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002049 const CFRefCount& getTF() const { return TF; }
2050
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002051 // FIXME: Eventually remove.
2052 virtual const char* getDescription() const = 0;
2053
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002054 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002055 };
2056
2057 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2058 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002059 UseAfterRelease(CFRefCount* tf)
2060 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002061
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002062 const char* getDescription() const {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002063 return "Reference-counted object is used after it is released.";
Ted Kremenek708af042009-02-05 06:50:21 +00002064 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002065 };
2066
2067 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2068 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002069 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2070
2071 const char* getDescription() const {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002072 return "Incorrect decrement of the reference count of a "
Ted Kremeneka8503952008-04-18 04:55:01 +00002073 "CoreFoundation object: "
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002074 "The object is not owned at this point by the caller.";
2075 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002076 };
2077
2078 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002079 const bool isReturn;
2080 protected:
2081 Leak(CFRefCount* tf, const char* name, bool isRet)
2082 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002083 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002084
Ted Kremenek44274e62009-02-07 22:38:00 +00002085 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002086
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002087 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002088 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002089
2090 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2091 public:
2092 LeakAtReturn(CFRefCount* tf, const char* name)
2093 : Leak(tf, name, true) {}
2094 };
2095
2096 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2097 public:
2098 LeakWithinFunction(CFRefCount* tf, const char* name)
2099 : Leak(tf, name, false) {}
2100 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002101
2102 //===---------===//
2103 // Bug Reports. //
2104 //===---------===//
2105
2106 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002107 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002108 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002109 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002110 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002111 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2112 ExplodedNode<GRState> *n, SymbolRef sym)
2113 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002114
2115 virtual ~CFRefReport() {}
2116
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002117 CFRefBug& getBugType() {
2118 return (CFRefBug&) RangedBugReport::getBugType();
2119 }
2120 const CFRefBug& getBugType() const {
2121 return (const CFRefBug&) RangedBugReport::getBugType();
2122 }
2123
2124 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2125 const SourceRange*& end) {
2126
Ted Kremenek198cae02008-05-02 20:53:50 +00002127 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002128 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002129 else
2130 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002131 }
2132
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002133 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002134
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002135 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2136 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002137
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002138 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002139
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002140 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2141 const ExplodedNode<GRState>* PrevN,
2142 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002143 BugReporter& BR,
2144 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002145 };
2146
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002147 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002148 SourceLocation AllocSite;
2149 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002150 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002151 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2152 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002153 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002154
2155 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2156 const ExplodedNode<GRState>* N);
2157
Ted Kremenek86617f42009-02-07 22:19:59 +00002158 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002159 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002160} // end anonymous namespace
2161
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002162void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002163 useAfterRelease = new UseAfterRelease(this);
2164 BR.Register(useAfterRelease);
2165
2166 releaseNotOwned = new BadRelease(this);
2167 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002168
2169 // First register "return" leaks.
2170 const char* name = 0;
2171
2172 if (isGCEnabled())
2173 name = "[naming convention] leak of returned object (GC)";
2174 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2175 name = "[naming convention] leak of returned object (hybrid MM, "
2176 "non-GC)";
2177 else {
2178 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2179 name = "[naming convention] leak of returned object";
2180 }
2181
Ted Kremenek708af042009-02-05 06:50:21 +00002182 leakAtReturn = new LeakAtReturn(this, name);
2183 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002184
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002185 // Second, register leaks within a function/method.
2186 if (isGCEnabled())
2187 name = "leak (GC)";
2188 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2189 name = "leak (hybrid MM, non-GC)";
2190 else {
2191 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2192 name = "leak";
2193 }
2194
Ted Kremenek708af042009-02-05 06:50:21 +00002195 leakWithinFunction = new LeakWithinFunction(this, name);
2196 BR.Register(leakWithinFunction);
2197
2198 // Save the reference to the BugReporter.
2199 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002200}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002201
2202static const char* Msgs[] = {
2203 "Code is compiled in garbage collection only mode" // GC only
2204 " (the bug occurs with garbage collection enabled).",
2205
2206 "Code is compiled without garbage collection.", // No GC.
2207
2208 "Code is compiled for use with and without garbage collection (GC)."
2209 " The bug occurs with GC enabled.", // Hybrid, with GC.
2210
2211 "Code is compiled for use with and without garbage collection (GC)."
2212 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2213};
2214
2215std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2216 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2217
2218 switch (TF.getLangOptions().getGCMode()) {
2219 default:
2220 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002221
2222 case LangOptions::GCOnly:
2223 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002224 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2225
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002226 case LangOptions::NonGC:
2227 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002228 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2229
2230 case LangOptions::HybridGC:
2231 if (TF.isGCEnabled())
2232 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2233 else
2234 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2235 }
2236}
2237
Ted Kremenek2126bef2009-02-18 21:57:45 +00002238static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2239 ArgEffect X) {
2240 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2241 I!=E; ++I)
2242 if (*I == X) return true;
2243
2244 return false;
2245}
2246
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002247PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2248 const ExplodedNode<GRState>* PrevN,
2249 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002250 BugReporter& BR,
2251 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002252
Ted Kremenek71745d92009-01-28 05:29:13 +00002253 // Check if the type state has changed.
2254 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2255 GRStateRef PrevSt(PrevN->getState(), StMgr);
2256 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002257
Ted Kremenek71745d92009-01-28 05:29:13 +00002258 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2259 if (!CurrT) return NULL;
2260
2261 const RefVal& CurrV = *CurrT;
2262 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002263
Ted Kremenek2126bef2009-02-18 21:57:45 +00002264 // Create a string buffer to constain all the useful things we want
2265 // to tell the user.
2266 std::string sbuf;
2267 llvm::raw_string_ostream os(sbuf);
2268
Ted Kremenekc26c4692009-02-18 03:48:14 +00002269 // This is the allocation site since the previous node had no bindings
2270 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002271 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002272 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2273
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002274 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2275 // Get the name of the callee (if it is available).
2276 SVal X = CurrSt.GetSVal(CE->getCallee());
2277 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2278 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2279 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002280 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002281 }
2282 else {
2283 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002284 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002285 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002286
Ted Kremenek18878b12009-01-28 06:06:36 +00002287 if (CurrV.getObjKind() == RetEffect::CF) {
2288 os << " returns a Core Foundation object with a ";
2289 }
2290 else {
2291 assert (CurrV.getObjKind() == RetEffect::ObjC);
2292 os << " returns an Objective-C object with a ";
2293 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002294
Ted Kremenekabe30922009-01-28 06:25:48 +00002295 if (CurrV.isOwned()) {
2296 os << "+1 retain count (owning reference).";
2297
2298 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2299 assert(CurrV.getObjKind() == RetEffect::CF);
2300 os << " "
2301 "Core Foundation objects are not automatically garbage collected.";
2302 }
2303 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002304 else {
2305 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002306 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002307 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002308
Ted Kremeneka8503952008-04-18 04:55:01 +00002309 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenekbc543722009-01-28 04:47:13 +00002310 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002311
2312 if (Expr* Exp = dyn_cast<Expr>(S))
2313 P->addRange(Exp->getSourceRange());
2314
2315 return P;
2316 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002317
Ted Kremenek2126bef2009-02-18 21:57:45 +00002318 // Gather up the effects that were performed on the object at this
2319 // program point
2320 llvm::SmallVector<ArgEffect, 2> AEffects;
2321
Ted Kremenekc26c4692009-02-18 03:48:14 +00002322 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2323 // We only have summaries attached to nodes after evaluating CallExpr and
2324 // ObjCMessageExprs.
2325 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2326
Ted Kremenekc26c4692009-02-18 03:48:14 +00002327 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2328 // Iterate through the parameter expressions and see if the symbol
2329 // was ever passed as an argument.
2330 unsigned i = 0;
2331
2332 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2333 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002334
Ted Kremenekc26c4692009-02-18 03:48:14 +00002335 // Retrieve the value of the arugment.
2336 SVal X = CurrSt.GetSVal(*AI);
Ted Kremenek2126bef2009-02-18 21:57:45 +00002337
Ted Kremenekc26c4692009-02-18 03:48:14 +00002338 // Is it the symbol we're interested in?
2339 if (!isa<loc::SymbolVal>(X) ||
2340 Sym != cast<loc::SymbolVal>(X).getSymbol())
2341 continue;
Ted Kremenek752b5842008-04-18 05:32:44 +00002342
Ted Kremenekc26c4692009-02-18 03:48:14 +00002343 // We have an argument. Get the effect!
2344 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002345 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002346 }
2347 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2348 if (Expr *receiver = ME->getReceiver()) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002349 SVal RetV = CurrSt.GetSVal(receiver);
2350 if (isa<loc::SymbolVal>(RetV) &&
2351 Sym == cast<loc::SymbolVal>(RetV).getSymbol()) {
2352 // The symbol we are tracking is the receiver.
2353 AEffects.push_back(Summ->getReceiverEffect());
2354 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002355 }
2356 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002357 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002358
Ted Kremenek2126bef2009-02-18 21:57:45 +00002359 do {
2360 // Get the previous type state.
2361 RefVal PrevV = *PrevT;
2362
2363 // Specially handle CFMakeCollectable and friends.
2364 if (contains(AEffects, MakeCollectable)) {
2365 // Get the name of the function.
2366 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2367 loc::FuncVal FV =
2368 cast<loc::FuncVal>(CurrSt.GetSVal(cast<CallExpr>(S)->getCallee()));
2369 const std::string& FName = FV.getDecl()->getNameAsString();
2370
2371 if (TF.isGCEnabled()) {
2372 // Determine if the object's reference count was pushed to zero.
2373 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2374
2375 os << "In GC mode a call to '" << FName
2376 << "' decrements an object's retain count and registers the "
2377 "object with the garbage collector. ";
2378
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002379 if (CurrV.getKind() == RefVal::Released) {
2380 assert(CurrV.getCount() == 0);
2381 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002382 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002383 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002384 else
2385 os << "An object must have a 0 retain count to be garbage collected. "
2386 "After this call its retain count is +" << CurrV.getCount()
2387 << '.';
2388 }
2389 else
2390 os << "When GC is not enabled a call to '" << FName
2391 << "' has no effect on its argument.";
2392
2393 // Nothing more to say.
2394 break;
2395 }
2396
2397 // Determine if the typestate has changed.
2398 if (!(PrevV == CurrV))
2399 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002400 case RefVal::Owned:
2401 case RefVal::NotOwned:
2402
2403 if (PrevV.getCount() == CurrV.getCount())
2404 return 0;
2405
2406 if (PrevV.getCount() > CurrV.getCount())
2407 os << "Reference count decremented.";
2408 else
2409 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002410
Ted Kremenekc26c4692009-02-18 03:48:14 +00002411 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002412 os << " The object now has +" << Count;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002413
2414 if (Count > 1)
2415 os << " retain counts.";
2416 else
2417 os << " retain count.";
2418 }
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002419
2420 if (PrevV.getKind() == RefVal::Released) {
2421 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2422 os << " The object is not eligible for garbage collection until the "
2423 "retain count reaches 0 again.";
2424 }
2425
Ted Kremenekc26c4692009-02-18 03:48:14 +00002426 break;
2427
2428 case RefVal::Released:
2429 os << "Object released.";
2430 break;
2431
2432 case RefVal::ReturnedOwned:
2433 os << "Object returned to caller as an owning reference (single retain "
2434 "count transferred to caller).";
2435 break;
2436
2437 case RefVal::ReturnedNotOwned:
2438 os << "Object returned to caller with a +0 (non-owning) retain count.";
2439 break;
2440
2441 default:
2442 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002443 }
2444
2445 // Emit any remaining diagnostics for the argument effects (if any).
2446 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2447 E=AEffects.end(); I != E; ++I) {
2448
2449 // A bunch of things have alternate behavior under GC.
2450 if (TF.isGCEnabled())
2451 switch (*I) {
2452 default: break;
2453 case Autorelease:
2454 os << "In GC mode an 'autorelease' has no effect.";
2455 continue;
2456 case IncRefMsg:
2457 os << "In GC mode the 'retain' message has no effect.";
2458 continue;
2459 case DecRefMsg:
2460 os << "In GC mode the 'release' message has no effect.";
2461 continue;
2462 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002463 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002464 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002465
2466 if (os.str().empty())
2467 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002468
2469 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2470 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenekbc543722009-01-28 04:47:13 +00002471 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002472
2473 // Add the range by scanning the children of the statement for any bindings
2474 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002475 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2476 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek335a3022009-01-28 05:06:46 +00002477 SVal X = CurrSt.GetSVal(Exp);
Zhongxing Xu097fc982008-10-17 05:57:07 +00002478 if (loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&X))
Ted Kremenekfd3f8da2009-02-18 22:17:20 +00002479 if (SV->getSymbol() == Sym) {
2480 P->addRange(Exp->getSourceRange());
2481 break;
2482 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002483 }
2484
2485 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002486}
2487
Ted Kremenekb15eba42008-10-04 05:50:14 +00002488namespace {
2489class VISIBILITY_HIDDEN FindUniqueBinding :
2490 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002491 SymbolRef Sym;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002492 MemRegion* Binding;
2493 bool First;
2494
2495 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002496 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002497
Zhongxing Xu097fc982008-10-17 05:57:07 +00002498 bool HandleBinding(StoreManager& SMgr, Store store, MemRegion* R, SVal val) {
2499 if (const loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&val)) {
Ted Kremenekb15eba42008-10-04 05:50:14 +00002500 if (SV->getSymbol() != Sym)
2501 return true;
2502 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002503 else if (const nonloc::SymbolVal* SV=dyn_cast<nonloc::SymbolVal>(&val)) {
Ted Kremenekb15eba42008-10-04 05:50:14 +00002504 if (SV->getSymbol() != Sym)
2505 return true;
2506 }
2507 else
2508 return true;
2509
2510 if (Binding) {
2511 First = false;
2512 return false;
2513 }
2514 else
2515 Binding = R;
2516
2517 return true;
2518 }
2519
2520 operator bool() { return First && Binding; }
2521 MemRegion* getRegion() { return Binding; }
2522};
2523}
2524
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002525static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00002526GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002527 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00002528
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002529 // Find both first node that referred to the tracked symbol and the
2530 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002531 const ExplodedNode<GRState>* Last = N;
2532 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002533
2534 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002535 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002536 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002537
Ted Kremenek6064a362008-07-07 16:21:19 +00002538 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002539 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002540
Ted Kremenek86617f42009-02-07 22:19:59 +00002541 FindUniqueBinding FB(Sym);
2542 StateMgr.iterBindings(St, FB);
2543 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002544
Ted Kremenekd7e26782008-05-16 18:33:44 +00002545 Last = N;
2546 N = N->pred_empty() ? NULL : *(N->pred_begin());
2547 }
2548
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002549 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002550}
Ted Kremenek4c479322008-05-06 23:07:13 +00002551
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002552PathDiagnosticPiece*
2553CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002554
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002555 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek86953652008-05-22 23:45:19 +00002556 // Tell the BugReporter to report cases when the tracked symbol is
2557 // assigned to different variables, etc.
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002558 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002559 return RangedBugReport::getEndPath(BR, EndN);
2560}
2561
2562PathDiagnosticPiece*
2563CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2564
2565 GRBugReporter& BR = cast<GRBugReporter>(br);
2566 // Tell the BugReporter to report cases when the tracked symbol is
2567 // assigned to different variables, etc.
2568 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2569
2570 // We are reporting a leak. Walk up the graph to get to the first node where
2571 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00002572 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002573 const ExplodedNode<GRState>* AllocNode = 0;
2574 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002575
2576 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00002577 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002578
Ted Kremenekd7e26782008-05-16 18:33:44 +00002579 // Get the allocate site.
2580 assert (AllocNode);
2581 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002582
Ted Kremenekea794e92008-05-05 18:50:19 +00002583 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00002584 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002585
Ted Kremeneke0336742009-02-18 23:28:26 +00002586 // Get the leak site. We want to find the last place where the symbol
2587 // was used in an expression.
2588 const ExplodedNode<GRState>* LeakN = EndN;
2589 Stmt *S = 0;
Ted Kremenekea794e92008-05-05 18:50:19 +00002590
Ted Kremeneke0336742009-02-18 23:28:26 +00002591 while (LeakN) {
2592 ProgramPoint P = LeakN->getLocation();
Ted Kremeneke0336742009-02-18 23:28:26 +00002593
2594 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2595 S = PS->getStmt();
2596 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
2597 S = BE->getSrc()->getTerminator();
2598
2599 if (S) {
2600 // Scan 'S' for uses of Sym.
2601 GRStateRef state(LeakN->getState(), BR.getStateManager());
2602 bool foundSymbol = false;
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002603
2604 // First check if 'S' itself binds to the symbol.
2605 if (Expr *Ex = dyn_cast<Expr>(S)) {
2606 SVal X = state.GetSVal(Ex);
2607 if (isa<loc::SymbolVal>(X) &&
2608 cast<loc::SymbolVal>(X).getSymbol() == Sym)
2609 foundSymbol = true;
2610 }
2611
2612 if (!foundSymbol)
2613 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2614 I!=E; ++I)
2615 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
2616 SVal X = state.GetSVal(Ex);
2617 if (isa<loc::SymbolVal>(X) &&
2618 cast<loc::SymbolVal>(X).getSymbol() == Sym){
2619 foundSymbol = true;
2620 break;
2621 }
Ted Kremeneke0336742009-02-18 23:28:26 +00002622 }
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002623
Ted Kremeneke0336742009-02-18 23:28:26 +00002624 if (foundSymbol)
2625 break;
2626 }
2627
2628 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2629 }
2630
2631 assert(LeakN && S && "No leak site found.");
Ted Kremenekea794e92008-05-05 18:50:19 +00002632
Ted Kremenekea794e92008-05-05 18:50:19 +00002633 // Generate the diagnostic.
Ted Kremenek323207b2009-02-18 22:59:04 +00002634 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenek59f9fe12009-02-07 21:59:45 +00002635 std::string sbuf;
2636 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00002637
Ted Kremenekea794e92008-05-05 18:50:19 +00002638 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002639
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002640 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002641 os << " and stored into '" << FirstBinding->getString() << '\'';
2642
Ted Kremenek311f3d42008-10-22 23:56:21 +00002643 // Get the retain count.
2644 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2645
2646 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00002647 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2648 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2649 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00002650 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2651 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00002652 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00002653 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00002654 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002655 " in the Memory Management Guide for Cocoa (object leaked).";
2656 }
2657 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00002658 os << " is no longer referenced after this point and has a retain count of"
2659 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002660 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002661
Ted Kremenek323207b2009-02-18 22:59:04 +00002662 return new PathDiagnosticPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002663}
2664
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002665
Ted Kremenekc26c4692009-02-18 03:48:14 +00002666CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2667 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00002668 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002669 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00002670{
2671
Ted Kremenekd7e26782008-05-16 18:33:44 +00002672 // Most bug reports are cached at the location where they occured.
2673 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00002674 // allocated, and only report a single path. To do this, we need to find
2675 // the allocation site of a piece of tracked memory, which we do via a
2676 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2677 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2678 // that all ancestor nodes that represent the allocation site have the
2679 // same SourceLocation.
2680 const ExplodedNode<GRState>* AllocNode = 0;
2681
2682 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00002683 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00002684
Ted Kremenek86617f42009-02-07 22:19:59 +00002685 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00002686 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00002687 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00002688
2689 // Fill in the description of the bug.
2690 Description.clear();
2691 llvm::raw_string_ostream os(Description);
2692 SourceManager& SMgr = Eng.getContext().getSourceManager();
2693 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00002694 os << "Potential leak of object allocated on line " << AllocLine;
2695
2696 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2697 if (AllocBinding)
2698 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00002699}
2700
Ted Kremeneka7338b42008-03-11 06:39:11 +00002701//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00002702// Handle dead symbols and end-of-path.
2703//===----------------------------------------------------------------------===//
2704
2705void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2706 GREndPathNodeBuilder<GRState>& Builder) {
2707
2708 const GRState* St = Builder.getState();
2709 RefBindings B = St->get<RefBindings>();
2710
2711 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2712 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2713
2714 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2715 bool hasLeak = false;
2716
2717 std::pair<GRStateRef, bool> X =
2718 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2719 (*I).first, (*I).second, hasLeak);
2720
2721 St = X.first;
2722 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2723 }
2724
2725 if (Leaked.empty())
2726 return;
2727
2728 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2729
2730 if (!N)
2731 return;
2732
2733 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2734 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2735
2736 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2737 : leakWithinFunction);
2738 assert(BT && "BugType not initialized.");
Ted Kremenekc26c4692009-02-18 03:48:14 +00002739 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00002740 BR->EmitReport(report);
2741 }
2742}
2743
2744void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2745 GRExprEngine& Eng,
2746 GRStmtNodeBuilder<GRState>& Builder,
2747 ExplodedNode<GRState>* Pred,
2748 Stmt* S,
2749 const GRState* St,
2750 SymbolReaper& SymReaper) {
2751
Ted Kremenek876d8df2009-02-19 23:47:02 +00002752 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00002753 RefBindings B = St->get<RefBindings>();
2754 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2755
2756 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2757 E = SymReaper.dead_end(); I != E; ++I) {
2758
2759 const RefVal* T = B.lookup(*I);
2760 if (!T) continue;
2761
2762 bool hasLeak = false;
2763
2764 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00002765 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00002766
2767 St = X.first;
2768
2769 if (hasLeak)
2770 Leaked.push_back(std::make_pair(*I,X.second));
2771 }
2772
Ted Kremenek876d8df2009-02-19 23:47:02 +00002773 if (!Leaked.empty()) {
2774 // Create a new intermediate node representing the leak point. We
2775 // use a special program point that represents this checker-specific
2776 // transition. We use the address of RefBIndex as a unique tag for this
2777 // checker. We will create another node (if we don't cache out) that
2778 // removes the retain-count bindings from the state.
2779 // NOTE: We use 'generateNode' so that it does interplay with the
2780 // auto-transition logic.
2781 ExplodedNode<GRState>* N =
2782 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00002783
Ted Kremenek876d8df2009-02-19 23:47:02 +00002784 if (!N)
2785 return;
2786
2787 // Generate the bug reports.
2788 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
2789 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2790
2791 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2792 : leakWithinFunction);
2793 assert(BT && "BugType not initialized.");
2794 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
2795 BR->EmitReport(report);
2796 }
Ted Kremenek708af042009-02-05 06:50:21 +00002797
Ted Kremenek876d8df2009-02-19 23:47:02 +00002798 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00002799 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00002800
2801 // Now generate a new node that nukes the old bindings.
2802 GRStateRef state(St, Eng.getStateManager());
2803 RefBindings::Factory& F = state.get_context<RefBindings>();
2804
2805 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2806 E = SymReaper.dead_end(); I!=E; ++I)
2807 B = F.Remove(B, *I);
2808
2809 state = state.set<RefBindings>(B);
2810 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00002811}
2812
2813void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2814 GRStmtNodeBuilder<GRState>& Builder,
2815 Expr* NodeExpr, Expr* ErrorExpr,
2816 ExplodedNode<GRState>* Pred,
2817 const GRState* St,
2818 RefVal::Kind hasErr, SymbolRef Sym) {
2819 Builder.BuildSinks = true;
2820 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2821
2822 if (!N) return;
2823
2824 CFRefBug *BT = 0;
2825
2826 if (hasErr == RefVal::ErrorUseAfterRelease)
2827 BT = static_cast<CFRefBug*>(useAfterRelease);
2828 else {
2829 assert(hasErr == RefVal::ErrorReleaseNotOwned);
2830 BT = static_cast<CFRefBug*>(releaseNotOwned);
2831 }
2832
Ted Kremenekc26c4692009-02-18 03:48:14 +00002833 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00002834 report->addRange(ErrorExpr->getSourceRange());
2835 BR->EmitReport(report);
2836}
2837
2838//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00002839// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002840//===----------------------------------------------------------------------===//
2841
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002842GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2843 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00002844 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00002845}