blob: 8b3f37f1e53604a152c1d01e99db94011b83641a [file] [log] [blame]
Chris Lattnerbda0b622008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif843e9342008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek2fff37e2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenek072192b2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekc9fa2f72008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek4adc81e2008-08-13 04:27:00 +000018#include "clang/Analysis/PathSensitive/GRState.h"
Ted Kremenekb9d17f92008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenek4dc41cc2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000025#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/FoldingSet.h"
27#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000028#include "llvm/ADT/ImmutableList.h"
Ted Kremenek900a2d72008-05-07 18:36:45 +000029#include "llvm/ADT/StringExtras.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000030#include "llvm/Support/Compiler.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000031#include "llvm/ADT/STLExtras.h"
Ted Kremenekf3948042008-03-11 19:44:10 +000032#include <ostream>
Ted Kremenek98530452008-08-12 20:41:56 +000033#include <stdarg.h>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000034
35using namespace clang;
Ted Kremenek5c74d502008-10-24 21:18:08 +000036
37//===----------------------------------------------------------------------===//
38// Utility functions.
39//===----------------------------------------------------------------------===//
40
Ted Kremenek900a2d72008-05-07 18:36:45 +000041using llvm::CStrInCStrNoCase;
Ted Kremenek2fff37e2008-03-06 00:08:09 +000042
Ted Kremenek5c74d502008-10-24 21:18:08 +000043// The "fundamental rule" for naming conventions of methods:
44// (url broken into two lines)
45// http://developer.apple.com/documentation/Cocoa/Conceptual/
46// MemoryMgmt/Tasks/MemoryManagementRules.html
47//
48// "You take ownership of an object if you create it using a method whose name
49// begins with “alloc” or “new” or contains “copy” (for example, alloc,
50// newObject, or mutableCopy), or if you send it a retain message. You are
51// responsible for relinquishing ownership of objects you own using release
52// or autorelease. Any other time you receive an object, you must
53// not release it."
54//
55static bool followsFundamentalRule(const char* s) {
Ted Kremeneke1e91af2008-10-30 23:14:58 +000056 while (*s == '_') ++s;
Ted Kremenek234a4c22009-01-07 00:39:56 +000057 return CStrInCStrNoCase(s, "copy")
58 || CStrInCStrNoCase(s, "new") == s
59 || CStrInCStrNoCase(s, "alloc") == s;
Ted Kremenek4c79e552008-11-05 16:54:44 +000060}
61
62static bool followsReturnRule(const char* s) {
63 while (*s == '_') ++s;
64 return followsFundamentalRule(s) || CStrInCStrNoCase(s, "init") == s;
65}
Ted Kremenek5c74d502008-10-24 21:18:08 +000066
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000067//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000068// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +000069//===----------------------------------------------------------------------===//
70
Ted Kremenekb83e02e2008-05-01 18:31:44 +000071static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +000072 IdentifierInfo* II = &Ctx.Idents.get(name);
73 return Ctx.Selectors.getSelector(0, &II);
74}
75
Ted Kremenek9c32d082008-05-06 00:30:21 +000076static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
77 IdentifierInfo* II = &Ctx.Idents.get(name);
78 return Ctx.Selectors.getSelector(1, &II);
79}
80
Ted Kremenek553cf182008-06-25 21:21:56 +000081//===----------------------------------------------------------------------===//
82// Type querying functions.
83//===----------------------------------------------------------------------===//
84
Ted Kremenek12619382009-01-12 21:45:02 +000085static bool hasPrefix(const char* s, const char* prefix) {
86 if (!prefix)
87 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000088
Ted Kremenek12619382009-01-12 21:45:02 +000089 char c = *s;
90 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000091
Ted Kremenek12619382009-01-12 21:45:02 +000092 while (c != '\0' && cP != '\0') {
93 if (c != cP) break;
94 c = *(++s);
95 cP = *(++prefix);
96 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000097
Ted Kremenek12619382009-01-12 21:45:02 +000098 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000099}
100
Ted Kremenek12619382009-01-12 21:45:02 +0000101static bool hasSuffix(const char* s, const char* suffix) {
102 const char* loc = strstr(s, suffix);
103 return loc && strcmp(suffix, loc) == 0;
104}
105
106static bool isRefType(QualType RetTy, const char* prefix,
107 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek37d785b2008-07-15 16:50:12 +0000108
Ted Kremenek12619382009-01-12 21:45:02 +0000109 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
110 const char* TDName = TD->getDecl()->getIdentifier()->getName();
111 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
112 }
113
114 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000115 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000116
117 // Is the type void*?
118 const PointerType* PT = RetTy->getAsPointerType();
119 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000120 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000121
122 // Does the name start with the prefix?
123 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000124}
125
Ted Kremenek4fd88972008-04-17 18:12:53 +0000126//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000127// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000128//===----------------------------------------------------------------------===//
129
Ted Kremenek553cf182008-06-25 21:21:56 +0000130namespace {
131/// ArgEffect is used to summarize a function/method call's effect on a
132/// particular argument.
Ted Kremenek070a8252008-07-09 18:11:16 +0000133enum ArgEffect { IncRef, DecRef, DoNothing, DoNothingByRef,
134 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek553cf182008-06-25 21:21:56 +0000135
136/// ArgEffects summarizes the effects of a function/method call on all of
137/// its arguments.
138typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000139}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000140
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000141namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000142template <> struct FoldingSetTrait<ArgEffects> {
143 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
144 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
145 ID.AddInteger(I->first);
146 ID.AddInteger((unsigned) I->second);
147 }
148 }
149};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000150} // end llvm namespace
151
152namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000153
154/// RetEffect is used to summarize a function/method call's behavior with
155/// respect to its return value.
156class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000157public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000158 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
159 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000160
161 enum ObjKind { CF, ObjC, AnyObj };
162
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000163private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000164 Kind K;
165 ObjKind O;
166 unsigned index;
167
168 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
169 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000170
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000171public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000172 Kind getKind() const { return K; }
173
174 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000175
176 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000177 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000178 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000179 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000180
Ted Kremenek553cf182008-06-25 21:21:56 +0000181 static RetEffect MakeAlias(unsigned Idx) {
182 return RetEffect(Alias, Idx);
183 }
184 static RetEffect MakeReceiverAlias() {
185 return RetEffect(ReceiverAlias);
186 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000187 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
188 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000189 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000190 static RetEffect MakeNotOwned(ObjKind o) {
191 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000192 }
193 static RetEffect MakeNoRet() {
194 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000195 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000196
Ted Kremenek553cf182008-06-25 21:21:56 +0000197 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000198 ID.AddInteger((unsigned)K);
199 ID.AddInteger((unsigned)O);
200 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000201 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000202};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000203
Ted Kremenek553cf182008-06-25 21:21:56 +0000204
205class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000206 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
207 /// specifies the argument (starting from 0). This can be sparsely
208 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000209 ArgEffects* Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000210
211 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
212 /// do not have an entry in Args.
213 ArgEffect DefaultArgEffect;
214
Ted Kremenek553cf182008-06-25 21:21:56 +0000215 /// Receiver - If this summary applies to an Objective-C message expression,
216 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000217 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000218
219 /// Ret - The effect on the return value. Used to indicate if the
220 /// function/method call returns a new tracked symbol, returns an
221 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000222 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000223
Ted Kremenek70a733e2008-07-18 17:24:20 +0000224 /// EndPath - Indicates that execution of this method/function should
225 /// terminate the simulation of a path.
226 bool EndPath;
227
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000228public:
229
Ted Kremenek1bffd742008-05-06 15:44:25 +0000230 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000231 ArgEffect ReceiverEff, bool endpath = false)
232 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
233 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000234
Ted Kremenek553cf182008-06-25 21:21:56 +0000235 /// getArg - Return the argument effect on the argument specified by
236 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000237 ArgEffect getArg(unsigned idx) const {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000238
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000239 if (!Args)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000240 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000241
242 // If Args is present, it is likely to contain only 1 element.
243 // Just do a linear search. Do it from the back because functions with
244 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek553cf182008-06-25 21:21:56 +0000245 // argument they actually modify with respect to the reference count.
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000246 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
247 I!=E; ++I) {
248
249 if (idx > I->first)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000250 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000251
252 if (idx == I->first)
253 return I->second;
254 }
255
Ted Kremenek1bffd742008-05-06 15:44:25 +0000256 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000257 }
258
Ted Kremenek553cf182008-06-25 21:21:56 +0000259 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000260 RetEffect getRetEffect() const {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000261 return Ret;
262 }
263
Ted Kremenek70a733e2008-07-18 17:24:20 +0000264 /// isEndPath - Returns true if executing the given method/function should
265 /// terminate the path.
266 bool isEndPath() const { return EndPath; }
267
Ted Kremenek553cf182008-06-25 21:21:56 +0000268 /// getReceiverEffect - Returns the effect on the receiver of the call.
269 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000270 ArgEffect getReceiverEffect() const {
271 return Receiver;
272 }
273
Ted Kremenek55499762008-06-17 02:43:46 +0000274 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000275
Ted Kremenek55499762008-06-17 02:43:46 +0000276 ExprIterator begin_args() const { return Args->begin(); }
277 ExprIterator end_args() const { return Args->end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000278
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000279 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000280 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000281 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000282 ID.AddPointer(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000283 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000284 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000285 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000286 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000287 }
288
289 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000290 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000291 }
292};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000293} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000294
Ted Kremenek553cf182008-06-25 21:21:56 +0000295//===----------------------------------------------------------------------===//
296// Data structures for constructing summaries.
297//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000298
Ted Kremenek553cf182008-06-25 21:21:56 +0000299namespace {
300class VISIBILITY_HIDDEN ObjCSummaryKey {
301 IdentifierInfo* II;
302 Selector S;
303public:
304 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
305 : II(ii), S(s) {}
306
307 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
308 : II(d ? d->getIdentifier() : 0), S(s) {}
309
310 ObjCSummaryKey(Selector s)
311 : II(0), S(s) {}
312
313 IdentifierInfo* getIdentifier() const { return II; }
314 Selector getSelector() const { return S; }
315};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000316}
317
318namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000319template <> struct DenseMapInfo<ObjCSummaryKey> {
320 static inline ObjCSummaryKey getEmptyKey() {
321 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
322 DenseMapInfo<Selector>::getEmptyKey());
323 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000324
Ted Kremenek553cf182008-06-25 21:21:56 +0000325 static inline ObjCSummaryKey getTombstoneKey() {
326 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
327 DenseMapInfo<Selector>::getTombstoneKey());
328 }
329
330 static unsigned getHashValue(const ObjCSummaryKey &V) {
331 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
332 & 0x88888888)
333 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
334 & 0x55555555);
335 }
336
337 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
338 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
339 RHS.getIdentifier()) &&
340 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
341 RHS.getSelector());
342 }
343
344 static bool isPod() {
345 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
346 DenseMapInfo<Selector>::isPod();
347 }
348};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000349} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000350
Ted Kremenek4f22a782008-06-23 23:30:29 +0000351namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000352class VISIBILITY_HIDDEN ObjCSummaryCache {
353 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
354 MapTy M;
355public:
356 ObjCSummaryCache() {}
357
358 typedef MapTy::iterator iterator;
359
360 iterator find(ObjCInterfaceDecl* D, Selector S) {
361
362 // Do a lookup with the (D,S) pair. If we find a match return
363 // the iterator.
364 ObjCSummaryKey K(D, S);
365 MapTy::iterator I = M.find(K);
366
367 if (I != M.end() || !D)
368 return I;
369
370 // Walk the super chain. If we find a hit with a parent, we'll end
371 // up returning that summary. We actually allow that key (null,S), as
372 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
373 // generate initial summaries without having to worry about NSObject
374 // being declared.
375 // FIXME: We may change this at some point.
376 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
377 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
378 break;
379
380 if (!C)
381 return I;
382 }
383
384 // Cache the summary with original key to make the next lookup faster
385 // and return the iterator.
386 M[K] = I->second;
387 return I;
388 }
389
Ted Kremenek98530452008-08-12 20:41:56 +0000390
Ted Kremenek553cf182008-06-25 21:21:56 +0000391 iterator find(Expr* Receiver, Selector S) {
392 return find(getReceiverDecl(Receiver), S);
393 }
394
395 iterator find(IdentifierInfo* II, Selector S) {
396 // FIXME: Class method lookup. Right now we dont' have a good way
397 // of going between IdentifierInfo* and the class hierarchy.
398 iterator I = M.find(ObjCSummaryKey(II, S));
399 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
400 }
401
402 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
403
404 const PointerType* PT = E->getType()->getAsPointerType();
405 if (!PT) return 0;
406
407 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
408 if (!OI) return 0;
409
410 return OI ? OI->getDecl() : 0;
411 }
412
413 iterator end() { return M.end(); }
414
415 RetainSummary*& operator[](ObjCMessageExpr* ME) {
416
417 Selector S = ME->getSelector();
418
419 if (Expr* Receiver = ME->getReceiver()) {
420 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
421 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
422 }
423
424 return M[ObjCSummaryKey(ME->getClassName(), S)];
425 }
426
427 RetainSummary*& operator[](ObjCSummaryKey K) {
428 return M[K];
429 }
430
431 RetainSummary*& operator[](Selector S) {
432 return M[ ObjCSummaryKey(S) ];
433 }
434};
435} // end anonymous namespace
436
437//===----------------------------------------------------------------------===//
438// Data structures for managing collections of summaries.
439//===----------------------------------------------------------------------===//
440
441namespace {
442class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000443
444 //==-----------------------------------------------------------------==//
445 // Typedefs.
446 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000447
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000448 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
449 ArgEffectsSetTy;
450
451 typedef llvm::FoldingSet<RetainSummary>
452 SummarySetTy;
453
454 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
455 FuncSummariesTy;
456
Ted Kremenek4f22a782008-06-23 23:30:29 +0000457 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000458
459 //==-----------------------------------------------------------------==//
460 // Data.
461 //==-----------------------------------------------------------------==//
462
Ted Kremenek553cf182008-06-25 21:21:56 +0000463 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000464 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000465
Ted Kremenek070a8252008-07-09 18:11:16 +0000466 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
467 /// "CFDictionaryCreate".
468 IdentifierInfo* CFDictionaryCreateII;
469
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000471 const bool GCEnabled;
472
Ted Kremenek553cf182008-06-25 21:21:56 +0000473 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +0000474 SummarySetTy SummarySet;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000475
Ted Kremenek553cf182008-06-25 21:21:56 +0000476 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000477 FuncSummariesTy FuncSummaries;
478
Ted Kremenek553cf182008-06-25 21:21:56 +0000479 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
480 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000481 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000482
Ted Kremenek553cf182008-06-25 21:21:56 +0000483 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000484 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000485
Ted Kremenek553cf182008-06-25 21:21:56 +0000486 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000487 ArgEffectsSetTy ArgEffectsSet;
488
Ted Kremenek553cf182008-06-25 21:21:56 +0000489 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
490 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000491 llvm::BumpPtrAllocator BPAlloc;
492
Ted Kremenek553cf182008-06-25 21:21:56 +0000493 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000494 ArgEffects ScratchArgs;
495
Ted Kremenek432af592008-05-06 18:11:36 +0000496 RetainSummary* StopSummary;
497
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000498 //==-----------------------------------------------------------------==//
499 // Methods.
500 //==-----------------------------------------------------------------==//
501
Ted Kremenek553cf182008-06-25 21:21:56 +0000502 /// getArgEffects - Returns a persistent ArgEffects object based on the
503 /// data in ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000504 ArgEffects* getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000505
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000506 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000507
508public:
Ted Kremenek12619382009-01-12 21:45:02 +0000509 RetainSummary* getUnarySummary(FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000510
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000511 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
512 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000513 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000514
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000515 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000516 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000517 ArgEffect DefaultEff = MayEscape,
518 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000519
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000520 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000521 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000522 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000523 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000524 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000525
Ted Kremenek1bffd742008-05-06 15:44:25 +0000526 RetainSummary* getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000527 if (StopSummary)
528 return StopSummary;
529
530 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
531 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000532
Ted Kremenek432af592008-05-06 18:11:36 +0000533 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000534 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000535
Ted Kremenek553cf182008-06-25 21:21:56 +0000536 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000537
Ted Kremenek1f180c32008-06-23 22:21:20 +0000538 void InitializeClassMethodSummaries();
539 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000540
Ted Kremenek234a4c22009-01-07 00:39:56 +0000541 bool isTrackedObjectType(QualType T);
542
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000543private:
544
Ted Kremenek70a733e2008-07-18 17:24:20 +0000545 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
546 RetainSummary* Summ) {
547 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
548 }
549
Ted Kremenek553cf182008-06-25 21:21:56 +0000550 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
551 ObjCClassMethodSummaries[S] = Summ;
552 }
553
554 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
555 ObjCMethodSummaries[S] = Summ;
556 }
557
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000558 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenek70a733e2008-07-18 17:24:20 +0000559
Ted Kremenek9e476de2008-08-12 18:30:56 +0000560 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
561 llvm::SmallVector<IdentifierInfo*, 10> II;
562
563 while (const char* s = va_arg(argp, const char*))
564 II.push_back(&Ctx.Idents.get(s));
565
566 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek70a733e2008-07-18 17:24:20 +0000567 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
568 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000569
570 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
571 va_list argp;
572 va_start(argp, Summ);
573 addInstMethSummary(Cls, Summ, argp);
574 va_end(argp);
575 }
Ted Kremenek9e476de2008-08-12 18:30:56 +0000576
577 void addPanicSummary(const char* Cls, ...) {
578 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
579 DoNothing, DoNothing, true);
580 va_list argp;
581 va_start (argp, Cls);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000582 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000583 va_end(argp);
584 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000585
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000586public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000587
588 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000589 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000590 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek553cf182008-06-25 21:21:56 +0000591 GCEnabled(gcenabled), StopSummary(0) {
592
593 InitializeClassMethodSummaries();
594 InitializeMethodSummaries();
595 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000596
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000597 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000598
Ted Kremenekab592272008-06-24 03:56:45 +0000599 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek553cf182008-06-25 21:21:56 +0000600 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek1f180c32008-06-23 22:21:20 +0000601 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenekb3095252008-05-06 04:20:12 +0000602
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000603 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000604};
605
606} // end anonymous namespace
607
608//===----------------------------------------------------------------------===//
609// Implementation of checker data structures.
610//===----------------------------------------------------------------------===//
611
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000612RetainSummaryManager::~RetainSummaryManager() {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000613
614 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
615 // mitigating the need to do explicit cleanup of the
616 // Argument-Effect summaries.
617
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000618 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
619 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000620 I->getValue().~ArgEffects();
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000621}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000622
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000623ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000624
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000625 if (ScratchArgs.empty())
626 return NULL;
627
628 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000629 llvm::FoldingSetNodeID profile;
630 profile.Add(ScratchArgs);
631 void* InsertPos;
632
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000633 // Look up the uniqued copy, or create a new one.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000634 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000635 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000636
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000637 if (E) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000638 ScratchArgs.clear();
639 return &E->getValue();
640 }
641
642 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek553cf182008-06-25 21:21:56 +0000643 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000644
645 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000646 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000647
648 ScratchArgs.clear();
649 return &E->getValue();
650}
651
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000652RetainSummary*
653RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000654 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000655 ArgEffect DefaultEff,
656 bool isEndPath) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000657
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000658 // Generate a profile for the summary.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000659 llvm::FoldingSetNodeID profile;
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000660 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
661 isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000662
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000663 // Look up the uniqued summary, or create one if it doesn't exist.
664 void* InsertPos;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000665 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000666
667 if (Summ)
668 return Summ;
669
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000670 // Create the summary and return it.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000671 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000672 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000673 SummarySet.InsertNode(Summ, InsertPos);
674
675 return Summ;
676}
677
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000678//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000679// Predicates.
680//===----------------------------------------------------------------------===//
681
682bool RetainSummaryManager::isTrackedObjectType(QualType T) {
683 if (!Ctx.isObjCObjectPointerType(T))
684 return false;
685
686 // Does it subclass NSObject?
687 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
688
689 // We assume that id<..>, id, and "Class" all represent tracked objects.
690 if (!OT)
691 return true;
692
693 // Does the object type subclass NSObject?
694 // FIXME: We can memoize here if this gets too expensive.
695 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
696 ObjCInterfaceDecl* ID = OT->getDecl();
697
698 for ( ; ID ; ID = ID->getSuperClass())
699 if (ID->getIdentifier() == NSObjectII)
700 return true;
701
702 return false;
703}
704
705//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000706// Summary creation for functions (largely uses of Core Foundation).
707//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000708
Ted Kremenek12619382009-01-12 21:45:02 +0000709static bool isRetain(FunctionDecl* FD, const char* FName) {
710 const char* loc = strstr(FName, "Retain");
711 return loc && loc[sizeof("Retain")-1] == '\0';
712}
713
714static bool isRelease(FunctionDecl* FD, const char* FName) {
715 const char* loc = strstr(FName, "Release");
716 return loc && loc[sizeof("Release")-1] == '\0';
717}
718
Ted Kremenekab592272008-06-24 03:56:45 +0000719RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000720
721 SourceLocation Loc = FD->getLocation();
722
723 if (!Loc.isFileID())
724 return NULL;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000725
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000726 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000727 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000728
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000729 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000730 return I->second;
731
732 // No summary. Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000733 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000734
Ted Kremenek37d785b2008-07-15 16:50:12 +0000735 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000736 // We generate "stop" summaries for implicitly defined functions.
737 if (FD->isImplicit()) {
738 S = getPersistentStopSummary();
739 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000740 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000741
Ted Kremenek99890652009-01-16 18:40:33 +0000742 // [PR 3337] Use 'getDesugaredType' to strip away any typedefs on the
743 // function's type.
744 FunctionType* FT = cast<FunctionType>(FD->getType()->getDesugaredType());
Ted Kremenek12619382009-01-12 21:45:02 +0000745 const char* FName = FD->getIdentifier()->getName();
746
747 // Inspect the result type.
748 QualType RetTy = FT->getResultType();
749
750 // FIXME: This should all be refactored into a chain of "summary lookup"
751 // filters.
752 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
753 // FIXES: <rdar://problem/6326900>
754 // This should be addressed using a API table. This strcmp is also
755 // a little gross, but there is no need to super optimize here.
756 assert (ScratchArgs.empty());
757 ScratchArgs.push_back(std::make_pair(1, DecRef));
758 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
759 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000760 }
Ted Kremenek12619382009-01-12 21:45:02 +0000761
762 // Handle: id NSMakeCollectable(CFTypeRef)
763 if (strcmp(FName, "NSMakeCollectable") == 0) {
764 S = (RetTy == Ctx.getObjCIdType())
765 ? getUnarySummary(FT, cfmakecollectable)
766 : getPersistentStopSummary();
767
768 break;
769 }
770
771 if (RetTy->isPointerType()) {
772 // For CoreFoundation ('CF') types.
773 if (isRefType(RetTy, "CF", &Ctx, FName)) {
774 if (isRetain(FD, FName))
775 S = getUnarySummary(FT, cfretain);
776 else if (strstr(FName, "MakeCollectable"))
777 S = getUnarySummary(FT, cfmakecollectable);
778 else
779 S = getCFCreateGetRuleSummary(FD, FName);
780
781 break;
782 }
783
784 // For CoreGraphics ('CG') types.
785 if (isRefType(RetTy, "CG", &Ctx, FName)) {
786 if (isRetain(FD, FName))
787 S = getUnarySummary(FT, cfretain);
788 else
789 S = getCFCreateGetRuleSummary(FD, FName);
790
791 break;
792 }
793
794 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
795 if (isRefType(RetTy, "DADisk") ||
796 isRefType(RetTy, "DADissenter") ||
797 isRefType(RetTy, "DASessionRef")) {
798 S = getCFCreateGetRuleSummary(FD, FName);
799 break;
800 }
801
802 break;
803 }
804
805 // Check for release functions, the only kind of functions that we care
806 // about that don't return a pointer type.
807 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
808 if (isRelease(FD, FName+2))
809 S = getUnarySummary(FT, cfrelease);
810 else {
Ted Kremenek68189282009-01-29 22:45:13 +0000811 assert (ScratchArgs.empty());
812 // Remaining CoreFoundation and CoreGraphics functions.
813 // We use to assume that they all strictly followed the ownership idiom
814 // and that ownership cannot be transferred. While this is technically
815 // correct, many methods allow a tracked object to escape. For example:
816 //
817 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
818 // CFDictionaryAddValue(y, key, x);
819 // CFRelease(x);
820 // ... it is okay to use 'x' since 'y' has a reference to it
821 //
822 // We handle this and similar cases with the follow heuristic. If the
823 // function name contains "InsertValue", "SetValue" or "AddValue" then
824 // we assume that arguments may "escape."
825 //
826 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
827 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +0000828 CStrInCStrNoCase(FName, "SetValue") ||
829 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +0000830 ? MayEscape : DoNothing;
831
832 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +0000833 }
834 }
Ted Kremenek37d785b2008-07-15 16:50:12 +0000835 }
836 while (0);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000837
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000838 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000839 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000840}
841
Ted Kremenek37d785b2008-07-15 16:50:12 +0000842RetainSummary*
843RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
844 const char* FName) {
845
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000846 if (strstr(FName, "Create") || strstr(FName, "Copy"))
847 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000848
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000849 if (strstr(FName, "Get"))
850 return getCFSummaryGetRule(FD);
851
852 return 0;
853}
854
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000855RetainSummary*
Ted Kremenek12619382009-01-12 21:45:02 +0000856RetainSummaryManager::getUnarySummary(FunctionType* FT, UnaryFuncKind func) {
857 // Sanity check that this is *really* a unary function. This can
858 // happen if people do weird things.
859 FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FT);
860 if (!FTP || FTP->getNumArgs() != 1)
861 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000862
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000863 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000864
Ted Kremenek377e2302008-04-29 05:33:51 +0000865 switch (func) {
Ted Kremenek12619382009-01-12 21:45:02 +0000866 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000867 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000868 return getPersistentSummary(RetEffect::MakeAlias(0),
869 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000870 }
871
872 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000873 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000874 return getPersistentSummary(RetEffect::MakeNoRet(),
875 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000876 }
877
878 case cfmakecollectable: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000879 if (GCEnabled)
880 ScratchArgs.push_back(std::make_pair(0, DecRef));
881
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000882 return getPersistentSummary(RetEffect::MakeAlias(0),
883 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000884 }
885
886 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000887 assert (false && "Not a supported unary function.");
Ted Kremenek98530452008-08-12 20:41:56 +0000888 return 0;
Ted Kremenek940b1d82008-04-10 23:44:06 +0000889 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000890}
891
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000892RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000893 assert (ScratchArgs.empty());
Ted Kremenek070a8252008-07-09 18:11:16 +0000894
895 if (FD->getIdentifier() == CFDictionaryCreateII) {
896 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
897 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
898 }
899
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000900 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000901}
902
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000903RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000904 assert (ScratchArgs.empty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000905 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
906 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000907}
908
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000909//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000910// Summary creation for Selectors.
911//===----------------------------------------------------------------------===//
912
Ted Kremenek1bffd742008-05-06 15:44:25 +0000913RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +0000914RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000915 assert(ScratchArgs.empty());
916
917 RetainSummary* Summ =
Ted Kremenek9c32d082008-05-06 00:30:21 +0000918 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000919
Ted Kremenek553cf182008-06-25 21:21:56 +0000920 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000921 return Summ;
922}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000923
Ted Kremenek553cf182008-06-25 21:21:56 +0000924
Ted Kremenek1bffd742008-05-06 15:44:25 +0000925RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +0000926RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
927 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000928
929 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000930
Ted Kremenek553cf182008-06-25 21:21:56 +0000931 // Look up a summary in our summary cache.
932 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000933
Ted Kremenek1f180c32008-06-23 22:21:20 +0000934 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000935 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000936
Ted Kremenek234a4c22009-01-07 00:39:56 +0000937 // "initXXX": pass-through for receiver.
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000938 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000939 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +0000940
Ted Kremenek0327f772008-06-02 17:14:13 +0000941 if (strncmp(s, "init", 4) == 0 || strncmp(s, "_init", 5) == 0)
Ted Kremenek234a4c22009-01-07 00:39:56 +0000942 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000943
Ted Kremenek234a4c22009-01-07 00:39:56 +0000944 // Look for methods that return an owned object.
945 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek84060db2008-05-07 04:25:59 +0000946 return 0;
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000947
Ted Kremenek234a4c22009-01-07 00:39:56 +0000948 if (followsFundamentalRule(s)) {
949 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000950 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000951 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek553cf182008-06-25 21:21:56 +0000952 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000953 return Summ;
954 }
Ted Kremenek1bffd742008-05-06 15:44:25 +0000955
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000956 return 0;
957}
958
Ted Kremenekc8395602008-05-06 21:26:51 +0000959RetainSummary*
Ted Kremenek1f180c32008-06-23 22:21:20 +0000960RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
961 Selector S) {
Ted Kremenekc8395602008-05-06 21:26:51 +0000962
Ted Kremenek553cf182008-06-25 21:21:56 +0000963 // FIXME: Eventually we should properly do class method summaries, but
964 // it requires us being able to walk the type hierarchy. Unfortunately,
965 // we cannot do this with just an IdentifierInfo* for the class name.
966
Ted Kremenekc8395602008-05-06 21:26:51 +0000967 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +0000968 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +0000969
Ted Kremenek1f180c32008-06-23 22:21:20 +0000970 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +0000971 return I->second;
972
Ted Kremeneka22cc2f2008-05-06 23:07:13 +0000973 return 0;
Ted Kremenekc8395602008-05-06 21:26:51 +0000974}
975
Ted Kremenek1f180c32008-06-23 22:21:20 +0000976void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +0000977
978 assert (ScratchArgs.empty());
979
Ted Kremeneka7344702008-06-23 18:02:52 +0000980 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000981 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +0000982
Ted Kremenek9c32d082008-05-06 00:30:21 +0000983 RetainSummary* Summ = getPersistentSummary(E);
984
Ted Kremenek553cf182008-06-25 21:21:56 +0000985 // Create the summaries for "alloc", "new", and "allocWithZone:" for
986 // NSObject and its derivatives.
987 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
988 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
989 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +0000990
991 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +0000992 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000993 GetNullarySelector("currentHandler", Ctx),
994 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +0000995
996 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekabf43972009-01-28 21:44:40 +0000997 ScratchArgs.push_back(std::make_pair(0, Autorelease));
998 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
999 GetUnarySelector("addObject", Ctx),
1000 getPersistentSummary(RetEffect::MakeNoRet(),
1001 DoNothing, DoNothing));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001002}
1003
Ted Kremenek1f180c32008-06-23 22:21:20 +00001004void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001005
1006 assert (ScratchArgs.empty());
1007
Ted Kremenekc8395602008-05-06 21:26:51 +00001008 // Create the "init" selector. It just acts as a pass-through for the
1009 // receiver.
Ted Kremenek179064e2008-07-01 17:21:27 +00001010 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
1011 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001012
1013 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +00001014 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001015 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001016
Ted Kremenek179064e2008-07-01 17:21:27 +00001017 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +00001018
1019 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001020 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1021
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001022 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001023 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001024
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001025 // Create the "retain" selector.
1026 E = RetEffect::MakeReceiverAlias();
1027 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : IncRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001028 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001029
1030 // Create the "release" selector.
1031 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001032 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001033
1034 // Create the "drain" selector.
1035 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001036 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001037
1038 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001039 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001040 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001041
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001042 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek179064e2008-07-01 17:21:27 +00001043 RetainSummary *NSWindowSumm =
1044 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001045
1046 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1047 "styleMask", "backing", "defer", NULL);
1048
1049 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1050 "styleMask", "backing", "defer", "screen", NULL);
1051
1052 // For NSPanel (which subclasses NSWindow), allocated objects are not
1053 // self-owned.
1054 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1055 "styleMask", "backing", "defer", NULL);
1056
1057 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1058 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001059
Ted Kremenek70a733e2008-07-18 17:24:20 +00001060 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001061 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1062 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001063
Ted Kremenek9e476de2008-08-12 18:30:56 +00001064 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1065 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001066}
1067
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001068//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001069// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001070//===----------------------------------------------------------------------===//
1071
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001072namespace {
1073
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001074class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001075public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001076 enum Kind {
1077 Owned = 0, // Owning reference.
1078 NotOwned, // Reference is not owned by still valid (not freed).
1079 Released, // Object has been released.
1080 ReturnedOwned, // Returned object passes ownership to caller.
1081 ReturnedNotOwned, // Return object does not pass ownership to caller.
1082 ErrorUseAfterRelease, // Object used after released.
1083 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001084 ErrorLeak, // A memory leak due to excessive reference counts.
1085 ErrorLeakReturned // A memory leak due to the returning method not having
1086 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001087 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001088
1089private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001090 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001091 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001092 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001093 QualType T;
1094
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001095 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1096 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001097
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001098 RefVal(Kind k, unsigned cnt = 0)
1099 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1100
1101public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001102 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001103
1104 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001105
Ted Kremenek553cf182008-06-25 21:21:56 +00001106 unsigned getCount() const { return Cnt; }
1107 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001108
1109 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001110
Ted Kremenek73c750b2008-03-11 18:14:09 +00001111 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1112
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001113 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001114
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001115 bool isOwned() const {
1116 return getKind() == Owned;
1117 }
1118
Ted Kremenekdb863712008-04-16 22:32:20 +00001119 bool isNotOwned() const {
1120 return getKind() == NotOwned;
1121 }
1122
Ted Kremenek4fd88972008-04-17 18:12:53 +00001123 bool isReturnedOwned() const {
1124 return getKind() == ReturnedOwned;
1125 }
1126
1127 bool isReturnedNotOwned() const {
1128 return getKind() == ReturnedNotOwned;
1129 }
1130
1131 bool isNonLeakError() const {
1132 Kind k = getKind();
1133 return isError(k) && !isLeak(k);
1134 }
1135
1136 // State creation: normal state.
1137
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001138 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1139 unsigned Count = 1) {
1140 return RefVal(Owned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001141 }
1142
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001143 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1144 unsigned Count = 0) {
1145 return RefVal(NotOwned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001146 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001147
1148 static RefVal makeReturnedOwned(unsigned Count) {
1149 return RefVal(ReturnedOwned, Count);
1150 }
1151
1152 static RefVal makeReturnedNotOwned() {
1153 return RefVal(ReturnedNotOwned);
1154 }
1155
Ted Kremenek4fd88972008-04-17 18:12:53 +00001156 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001157
Ted Kremenek4fd88972008-04-17 18:12:53 +00001158 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001159 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001160 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001161
Ted Kremenek553cf182008-06-25 21:21:56 +00001162 RefVal operator-(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001163 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001164 }
1165
1166 RefVal operator+(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001167 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001168 }
1169
1170 RefVal operator^(Kind k) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001171 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001172 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001173
Ted Kremenek4fd88972008-04-17 18:12:53 +00001174 void Profile(llvm::FoldingSetNodeID& ID) const {
1175 ID.AddInteger((unsigned) kind);
1176 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001177 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001178 }
1179
Ted Kremenekf3948042008-03-11 19:44:10 +00001180 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001181};
Ted Kremenekf3948042008-03-11 19:44:10 +00001182
1183void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001184 if (!T.isNull())
1185 Out << "Tracked Type:" << T.getAsString() << '\n';
1186
Ted Kremenekf3948042008-03-11 19:44:10 +00001187 switch (getKind()) {
1188 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001189 case Owned: {
1190 Out << "Owned";
1191 unsigned cnt = getCount();
1192 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001193 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001194 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001195
Ted Kremenek61b9f872008-04-10 23:09:18 +00001196 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001197 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001198 unsigned cnt = getCount();
1199 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001200 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001201 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001202
Ted Kremenek4fd88972008-04-17 18:12:53 +00001203 case ReturnedOwned: {
1204 Out << "ReturnedOwned";
1205 unsigned cnt = getCount();
1206 if (cnt) Out << " (+ " << cnt << ")";
1207 break;
1208 }
1209
1210 case ReturnedNotOwned: {
1211 Out << "ReturnedNotOwned";
1212 unsigned cnt = getCount();
1213 if (cnt) Out << " (+ " << cnt << ")";
1214 break;
1215 }
1216
Ted Kremenekf3948042008-03-11 19:44:10 +00001217 case Released:
1218 Out << "Released";
1219 break;
1220
Ted Kremenekdb863712008-04-16 22:32:20 +00001221 case ErrorLeak:
1222 Out << "Leaked";
1223 break;
1224
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001225 case ErrorLeakReturned:
1226 Out << "Leaked (Bad naming)";
1227 break;
1228
Ted Kremenekf3948042008-03-11 19:44:10 +00001229 case ErrorUseAfterRelease:
1230 Out << "Use-After-Release [ERROR]";
1231 break;
1232
1233 case ErrorReleaseNotOwned:
1234 Out << "Release of Not-Owned [ERROR]";
1235 break;
1236 }
1237}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001238
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001239} // end anonymous namespace
1240
1241//===----------------------------------------------------------------------===//
1242// RefBindings - State used to track object reference counts.
1243//===----------------------------------------------------------------------===//
1244
Ted Kremenek2dabd432008-12-05 02:27:51 +00001245typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001246static int RefBIndex = 0;
1247
1248namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001249 template<>
1250 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1251 static inline void* GDMIndex() { return &RefBIndex; }
1252 };
1253}
Ted Kremenek6d348932008-10-21 15:53:15 +00001254
1255//===----------------------------------------------------------------------===//
1256// ARBindings - State used to track objects in autorelease pools.
1257//===----------------------------------------------------------------------===//
1258
Ted Kremenek2dabd432008-12-05 02:27:51 +00001259typedef llvm::ImmutableSet<SymbolRef> ARPoolContents;
1260typedef llvm::ImmutableList< std::pair<SymbolRef, ARPoolContents*> > ARBindings;
Ted Kremenek6d348932008-10-21 15:53:15 +00001261static int AutoRBIndex = 0;
1262
1263namespace clang {
1264 template<>
1265 struct GRStateTrait<ARBindings> : public GRStatePartialTrait<ARBindings> {
1266 static inline void* GDMIndex() { return &AutoRBIndex; }
1267 };
1268}
1269
Ted Kremenek13922612008-04-16 20:40:59 +00001270//===----------------------------------------------------------------------===//
1271// Transfer functions.
1272//===----------------------------------------------------------------------===//
1273
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001274namespace {
1275
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001276class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001277public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001278 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001279 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001280 virtual void Print(std::ostream& Out, const GRState* state,
1281 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001282 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001283
1284private:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001285 RetainSummaryManager Summaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001286 const LangOptions& LOpts;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001287
Ted Kremenekcf701772009-02-05 06:50:21 +00001288 BugType *useAfterRelease, *releaseNotOwned;
1289 BugType *leakWithinFunction, *leakAtReturn;
1290 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001291
Ted Kremenek2dabd432008-12-05 02:27:51 +00001292 RefBindings Update(RefBindings B, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001293 RefVal::Kind& hasErr, RefBindings::Factory& RefBFactory);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001294
Ted Kremenek2dabd432008-12-05 02:27:51 +00001295 RefVal::Kind& Update(GRStateRef& state, SymbolRef sym, RefVal V,
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001296 ArgEffect E, RefVal::Kind& hasErr) {
1297
1298 state = state.set<RefBindings>(Update(state.get<RefBindings>(), sym, V,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001299 E, hasErr,
1300 state.get_context<RefBindings>()));
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001301 return hasErr;
1302 }
1303
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001304 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1305 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001306 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001307 ExplodedNode<GRState>* Pred,
1308 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001309 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001310
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001311 std::pair<GRStateRef, bool>
1312 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001313 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenekdb863712008-04-16 22:32:20 +00001314
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001315public:
Ted Kremenek13922612008-04-16 20:40:59 +00001316
Ted Kremenek78d46242008-07-22 16:21:24 +00001317 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001318 : Summaries(Ctx, gcenabled),
Ted Kremenekcf701772009-02-05 06:50:21 +00001319 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1320 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001321
Ted Kremenekcf701772009-02-05 06:50:21 +00001322 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001323
Ted Kremenekcf118d42009-02-04 23:49:09 +00001324 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001325
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001326 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1327 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001328 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001329
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001330 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001331 const LangOptions& getLangOptions() const { return LOpts; }
1332
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001333 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001334
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001335 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001336 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001337 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001338 Expr* Ex,
1339 Expr* Receiver,
1340 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001341 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001342 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001343
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001344 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001345 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001346 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001347 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001348 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001349
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001350
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001351 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001352 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001353 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001354 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001355 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001356
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001357 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001358 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001359 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001360 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001361 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001362
Ted Kremenek13922612008-04-16 20:40:59 +00001363 // Stores.
1364
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001365 virtual void EvalStore(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek13922612008-04-16 20:40:59 +00001366 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001367 GRStmtNodeBuilder<GRState>& Builder,
1368 Expr* E, ExplodedNode<GRState>* Pred,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001369 const GRState* St, SVal TargetLV, SVal Val);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001370 // End-of-path.
1371
1372 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001373 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001374
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001375 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001376 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001377 GRStmtNodeBuilder<GRState>& Builder,
1378 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001379 Stmt* S, const GRState* state,
1380 SymbolReaper& SymReaper);
1381
Ted Kremenek4fd88972008-04-17 18:12:53 +00001382 // Return statements.
1383
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001384 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001385 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001386 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001387 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001388 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001389
1390 // Assumptions.
1391
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001392 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001393 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001394 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001395};
1396
1397} // end anonymous namespace
1398
Ted Kremenek8dd56462008-04-18 03:39:05 +00001399
Ted Kremenekae6814e2008-08-13 21:24:49 +00001400void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1401 const char* nl, const char* sep) {
1402
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001403 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001404
Ted Kremenekae6814e2008-08-13 21:24:49 +00001405 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001406 Out << sep << nl;
1407
1408 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1409 Out << (*I).first << " : ";
1410 (*I).second.print(Out);
1411 Out << nl;
1412 }
1413}
1414
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001415static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001416 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001417}
1418
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001419static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1420 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001421}
1422
Ted Kremenek14993892008-05-06 02:41:27 +00001423static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1424 return Summ ? Summ->getReceiverEffect() : DoNothing;
1425}
1426
Ted Kremenek70a733e2008-07-18 17:24:20 +00001427static inline bool IsEndPath(RetainSummary* Summ) {
1428 return Summ ? Summ->isEndPath() : false;
1429}
1430
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001431
Ted Kremenek553cf182008-06-25 21:21:56 +00001432/// GetReturnType - Used to get the return type of a message expression or
1433/// function call with the intention of affixing that type to a tracked symbol.
1434/// While the the return type can be queried directly from RetEx, when
1435/// invoking class methods we augment to the return type to be that of
1436/// a pointer to the class (as opposed it just being id).
1437static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1438
1439 QualType RetTy = RetE->getType();
1440
1441 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00001442 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001443 if (!PT)
1444 return RetTy;
1445
1446 // If RetEx is not a message expression just return its type.
1447 // If RetEx is a message expression, return its types if it is something
1448 /// more specific than id.
1449
1450 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1451
1452 if (!ME || !Ctx.isObjCIdType(PT->getPointeeType()))
1453 return RetTy;
1454
1455 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1456
1457 // At this point we know the return type of the message expression is id.
1458 // If we have an ObjCInterceDecl, we know this is a call to a class method
1459 // whose type we can resolve. In such cases, promote the return type to
1460 // Class*.
1461 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1462}
1463
1464
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001465void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001466 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001467 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001468 Expr* Ex,
1469 Expr* Receiver,
1470 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001471 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001472 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001473
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001474 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001475 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001476 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00001477
1478 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001479 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001480 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001481 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00001482 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001483
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001484 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001485 SVal V = state.GetSVal(*I);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001486
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001487 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001488 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001489 if (RefBindings::data_type* T = state.get<RefBindings>(Sym))
1490 if (Update(state, Sym, *T, GetArgE(Summ, idx), hasErr)) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001491 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001492 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001493 break;
1494 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001495 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001496 else if (isa<Loc>(V)) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001497 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek070a8252008-07-09 18:11:16 +00001498
1499 if (GetArgE(Summ, idx) == DoNothingByRef)
1500 continue;
1501
1502 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001503
1504 // FIXME: Either this logic should also be replicated in GRSimpleVals
1505 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00001506
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001507 // FIXME: We can have collisions on the conjured symbol if the
1508 // expression *I also creates conjured symbols. We probably want
1509 // to identify conjured symbols by an expression pair: the enclosing
1510 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00001511 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00001512
Ted Kremenek993f1c72008-10-17 20:28:54 +00001513 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek90b32362008-12-17 19:42:34 +00001514
1515 // Blast through AnonTypedRegions to get the original region type.
1516 while (R) {
1517 const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R);
1518 if (!ATR) break;
1519 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1520 }
1521
Ted Kremenek9e240492008-10-04 05:50:14 +00001522 if (R) {
Ted Kremenek40e86d92008-12-18 23:34:57 +00001523
1524 // Is the invalidated variable something that we were tracking?
1525 SVal X = state.GetSVal(Loc::MakeVal(R));
1526
1527 if (isa<loc::SymbolVal>(X)) {
1528 SymbolRef Sym = cast<loc::SymbolVal>(X).getSymbol();
1529 state = state.remove<RefBindings>(Sym);
1530 }
1531
Ted Kremenek9e240492008-10-04 05:50:14 +00001532 // Set the value of the variable to be a conjured symbol.
1533 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek6eddeb12008-12-13 21:49:13 +00001534 QualType T = R->getRValueType(Ctx);
Ted Kremenek9e240492008-10-04 05:50:14 +00001535
Ted Kremenekfd301942008-10-17 22:23:12 +00001536 // FIXME: handle structs.
Ted Kremenek062e2f92008-11-13 06:10:40 +00001537 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001538 SymbolRef NewSym =
Ted Kremenekfd301942008-10-17 22:23:12 +00001539 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1540
Ted Kremenek90b32362008-12-17 19:42:34 +00001541 state = state.BindLoc(Loc::MakeVal(R),
Ted Kremenekfd301942008-10-17 22:23:12 +00001542 Loc::IsLocType(T)
1543 ? cast<SVal>(loc::SymbolVal(NewSym))
1544 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1545 }
1546 else {
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001547 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenekfd301942008-10-17 22:23:12 +00001548 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001549 }
1550 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001551 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001552 }
1553 else {
1554 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001555 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001556 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001557 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001558 else if (isa<nonloc::LocAsInteger>(V))
1559 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001560 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001561
Ted Kremenek553cf182008-06-25 21:21:56 +00001562 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001563 if (!ErrorExpr && Receiver) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001564 SVal V = state.GetSVal(Receiver);
1565 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001566 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001567 if (const RefVal* T = state.get<RefBindings>(Sym))
1568 if (Update(state, Sym, *T, GetReceiverE(Summ), hasErr)) {
Ted Kremenek14993892008-05-06 02:41:27 +00001569 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001570 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00001571 }
Ted Kremenek14993892008-05-06 02:41:27 +00001572 }
1573 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001574
Ted Kremenek553cf182008-06-25 21:21:56 +00001575 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001576 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001577 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001578 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001579 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001580 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001581
Ted Kremenek70a733e2008-07-18 17:24:20 +00001582 // Consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001583 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001584
1585 switch (RE.getKind()) {
1586 default:
1587 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001588
Ted Kremenekfd301942008-10-17 22:23:12 +00001589 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001590
Ted Kremenekf9561e52008-04-11 20:23:24 +00001591 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001592 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1593 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001594
Ted Kremenekfd301942008-10-17 22:23:12 +00001595 // FIXME: We eventually should handle structs and other compound types
1596 // that are returned by value.
1597
1598 QualType T = Ex->getType();
1599
Ted Kremenek062e2f92008-11-13 06:10:40 +00001600 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001601 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001602 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001603
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001604 SVal X = Loc::IsLocType(Ex->getType())
1605 ? cast<SVal>(loc::SymbolVal(Sym))
1606 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenekf9561e52008-04-11 20:23:24 +00001607
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001608 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001609 }
1610
Ted Kremenek940b1d82008-04-10 23:44:06 +00001611 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00001612 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001613
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001614 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001615 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001616 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001617 assert (idx < (unsigned) (arg_end - arg_beg));
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001618 SVal V = state.GetSVal(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001619 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001620 break;
1621 }
1622
Ted Kremenek14993892008-05-06 02:41:27 +00001623 case RetEffect::ReceiverAlias: {
1624 assert (Receiver);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001625 SVal V = state.GetSVal(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001626 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00001627 break;
1628 }
1629
Ted Kremeneka7344702008-06-23 18:02:52 +00001630 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001631 case RetEffect::OwnedSymbol: {
1632 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001633 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001634 QualType RetT = GetReturnType(Ex, Eng.getContext());
1635 state =
1636 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001637 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001638
Ted Kremeneka7344702008-06-23 18:02:52 +00001639 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00001640 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1641 bool isFeasible;
1642 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1643 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1644 }
Ted Kremeneka7344702008-06-23 18:02:52 +00001645
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001646 break;
1647 }
1648
1649 case RetEffect::NotOwnedSymbol: {
1650 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001651 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek553cf182008-06-25 21:21:56 +00001652 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001653
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001654 state =
1655 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001656 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001657 break;
1658 }
1659 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001660
Ted Kremenek70a733e2008-07-18 17:24:20 +00001661 // Is this a sink?
1662 if (IsEndPath(Summ))
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001663 Builder.MakeSinkNode(Dst, Ex, Pred, state);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001664 else
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001665 Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001666}
1667
1668
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001669void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001670 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001671 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001672 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001673 ExplodedNode<GRState>* Pred) {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001674
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001675 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1676 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001677
1678 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1679 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001680}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001681
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001682void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001683 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001684 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001685 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001686 ExplodedNode<GRState>* Pred) {
Ted Kremenekb3095252008-05-06 04:20:12 +00001687 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001688
Ted Kremenek553cf182008-06-25 21:21:56 +00001689 if (Expr* Receiver = ME->getReceiver()) {
1690 // We need the type-information of the tracked receiver object
1691 // Retrieve it from the state.
1692 ObjCInterfaceDecl* ID = 0;
1693
1694 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1695 // a chain of lookups.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001696 const GRState* St = Builder.GetState(Pred);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001697 SVal V = Eng.getStateManager().GetSVal(St, Receiver );
Ted Kremenek553cf182008-06-25 21:21:56 +00001698
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001699 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001700 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek553cf182008-06-25 21:21:56 +00001701
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001702 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001703 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001704
1705 if (const PointerType* PT = Ty->getAsPointerType()) {
1706 QualType PointeeTy = PT->getPointeeType();
1707
1708 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1709 ID = IT->getDecl();
1710 }
1711 }
1712 }
1713
1714 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001715
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001716 // Special-case: are we sending a mesage to "self"?
1717 // This is a hack. When we have full-IP this should be removed.
1718 if (!Summ) {
1719 ObjCMethodDecl* MD =
1720 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1721
1722 if (MD) {
1723 if (Expr* Receiver = ME->getReceiver()) {
1724 SVal X = Eng.getStateManager().GetSVal(St, Receiver);
1725 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001726 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1727 // Create a summmary where all of the arguments "StopTracking".
1728 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1729 DoNothing,
1730 StopTracking);
1731 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001732 }
1733 }
1734 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001735 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001736 else
Ted Kremenek1f180c32008-06-23 22:21:20 +00001737 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1738 ME->getSelector());
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001739
Ted Kremenekb3095252008-05-06 04:20:12 +00001740 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1741 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001742}
Ted Kremenekb3095252008-05-06 04:20:12 +00001743
Ted Kremenek13922612008-04-16 20:40:59 +00001744// Stores.
1745
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001746void CFRefCount::EvalStore(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek13922612008-04-16 20:40:59 +00001747 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001748 GRStmtNodeBuilder<GRState>& Builder,
1749 Expr* E, ExplodedNode<GRState>* Pred,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001750 const GRState* St, SVal TargetLV, SVal Val) {
Ted Kremenek13922612008-04-16 20:40:59 +00001751
1752 // Check if we have a binding for "Val" and if we are storing it to something
1753 // we don't understand or otherwise the value "escapes" the function.
1754
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001755 if (!isa<loc::SymbolVal>(Val))
Ted Kremenek13922612008-04-16 20:40:59 +00001756 return;
1757
1758 // Are we storing to something that causes the value to "escape"?
1759
1760 bool escapes = false;
1761
Ted Kremeneka496d162008-10-18 03:49:51 +00001762 // A value escapes in three possible cases (this may change):
1763 //
1764 // (1) we are binding to something that is not a memory region.
1765 // (2) we are binding to a memregion that does not have stack storage
1766 // (3) we are binding to a memregion with stack storage that the store
1767 // does not understand.
1768
Ted Kremenek2dabd432008-12-05 02:27:51 +00001769 SymbolRef Sym = cast<loc::SymbolVal>(Val).getSymbol();
Ted Kremeneka496d162008-10-18 03:49:51 +00001770 GRStateRef state(St, Eng.getStateManager());
1771
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001772 if (!isa<loc::MemRegionVal>(TargetLV))
Ted Kremenek13922612008-04-16 20:40:59 +00001773 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00001774 else {
Ted Kremenek993f1c72008-10-17 20:28:54 +00001775 const MemRegion* R = cast<loc::MemRegionVal>(TargetLV).getRegion();
Ted Kremenek9e240492008-10-04 05:50:14 +00001776 escapes = !Eng.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00001777
1778 if (!escapes) {
1779 // To test (3), generate a new state with the binding removed. If it is
1780 // the same state, then it escapes (since the store cannot represent
1781 // the binding).
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001782 GRStateRef stateNew = state.BindLoc(cast<Loc>(TargetLV), Val);
Ted Kremeneka496d162008-10-18 03:49:51 +00001783 escapes = (stateNew == state);
1784 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001785 }
Ted Kremenek13922612008-04-16 20:40:59 +00001786
1787 if (!escapes)
1788 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00001789
1790 // Do we have a reference count binding?
1791 // FIXME: Is this step even needed? We do blow away the binding anyway.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001792 if (!state.get<RefBindings>(Sym))
Ted Kremenek13922612008-04-16 20:40:59 +00001793 return;
1794
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001795 // Nuke the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001796 state = state.remove<RefBindings>(Sym);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001797
Ted Kremenek13922612008-04-16 20:40:59 +00001798 // Hand of the remaining logic to the parent implementation.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001799 GRSimpleVals::EvalStore(Dst, Eng, Builder, E, Pred, state, TargetLV, Val);
Ted Kremenekdb863712008-04-16 22:32:20 +00001800}
1801
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001802// End-of-path.
1803
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001804
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001805std::pair<GRStateRef,bool>
1806CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1807 const GRState* St, const Decl* CD,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001808 SymbolRef sid,
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001809 RefVal V, bool& hasLeak) {
Ted Kremenekdb863712008-04-16 22:32:20 +00001810
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001811 GRStateRef state(St, VMgr);
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001812 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001813 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001814
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001815 if (V.isReturnedOwned() && V.getCount() == 0)
1816 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00001817 std::string s = MD->getSelector().getAsString();
Ted Kremenek4c79e552008-11-05 16:54:44 +00001818 if (!followsReturnRule(s.c_str())) {
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001819 hasLeak = true;
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001820 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
1821 return std::make_pair(state, true);
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001822 }
1823 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001824
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001825 // All other cases.
1826
1827 hasLeak = V.isOwned() ||
1828 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001829
Ted Kremenekdb863712008-04-16 22:32:20 +00001830 if (!hasLeak)
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001831 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001832
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001833 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
1834 false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001835}
1836
Ted Kremenek652adc62008-04-24 23:57:27 +00001837
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001838
Ted Kremenek652adc62008-04-24 23:57:27 +00001839// Dead symbols.
1840
Ted Kremenekcf701772009-02-05 06:50:21 +00001841
Ted Kremenek652adc62008-04-24 23:57:27 +00001842
Ted Kremenek4fd88972008-04-17 18:12:53 +00001843 // Return statements.
1844
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001845void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001846 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001847 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001848 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001849 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001850
1851 Expr* RetE = S->getRetValue();
1852 if (!RetE) return;
1853
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001854 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001855 SVal V = state.GetSVal(RetE);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001856
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001857 if (!isa<loc::SymbolVal>(V))
Ted Kremenek4fd88972008-04-17 18:12:53 +00001858 return;
1859
1860 // Get the reference count binding (if any).
Ted Kremenek2dabd432008-12-05 02:27:51 +00001861 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001862 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001863
1864 if (!T)
1865 return;
1866
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001867 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001868 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001869
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001870 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001871 case RefVal::Owned: {
1872 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001873 assert (cnt > 0);
1874 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001875 break;
1876 }
1877
1878 case RefVal::NotOwned: {
1879 unsigned cnt = X.getCount();
1880 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1881 : RefVal::makeReturnedNotOwned();
1882 break;
1883 }
1884
1885 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001886 return;
1887 }
1888
1889 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001890 state = state.set<RefBindings>(Sym, X);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001891 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001892}
1893
Ted Kremenekcb612922008-04-18 19:23:43 +00001894// Assumptions.
1895
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001896const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
1897 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001898 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00001899 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00001900
1901 // FIXME: We may add to the interface of EvalAssume the list of symbols
1902 // whose assumptions have changed. For now we just iterate through the
1903 // bindings and check if any of the tracked symbols are NULL. This isn't
1904 // too bad since the number of symbols we will track in practice are
1905 // probably small and EvalAssume is only called at branches and a few
1906 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001907 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00001908
1909 if (B.isEmpty())
1910 return St;
1911
1912 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001913
1914 GRStateRef state(St, VMgr);
1915 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00001916
1917 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00001918 // Check if the symbol is null (or equal to any constant).
1919 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00001920 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00001921 changed = true;
1922 B = RefBFactory.Remove(B, I.getKey());
1923 }
1924 }
1925
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001926 if (changed)
1927 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00001928
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001929 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00001930}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001931
Ted Kremenek2dabd432008-12-05 02:27:51 +00001932RefBindings CFRefCount::Update(RefBindings B, SymbolRef sym,
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001933 RefVal V, ArgEffect E,
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001934 RefVal::Kind& hasErr,
1935 RefBindings::Factory& RefBFactory) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001936
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001937 // FIXME: This dispatch can potentially be sped up by unifiying it into
1938 // a single switch statement. Opt for simplicity for now.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001939
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001940 switch (E) {
1941 default:
1942 assert (false && "Unhandled CFRef transition.");
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001943
1944 case MayEscape:
1945 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00001946 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001947 break;
1948 }
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001949 // Fall-through.
Ted Kremenek070a8252008-07-09 18:11:16 +00001950 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001951 case DoNothing:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001952 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek553cf182008-06-25 21:21:56 +00001953 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001954 hasErr = V.getKind();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001955 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00001956 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001957 return B;
Ted Kremeneke19f4492008-06-30 16:57:41 +00001958
Ted Kremenekabf43972009-01-28 21:44:40 +00001959 case Autorelease:
1960 if (isGCEnabled()) return B;
1961 // Fall-through.
Ted Kremenek14993892008-05-06 02:41:27 +00001962 case StopTracking:
1963 return RefBFactory.Remove(B, sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00001964
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001965 case IncRef:
1966 switch (V.getKind()) {
1967 default:
1968 assert(false);
1969
1970 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001971 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00001972 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00001973 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001974 case RefVal::Released:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001975 if (isGCEnabled())
Ted Kremenek553cf182008-06-25 21:21:56 +00001976 V = V ^ RefVal::Owned;
Ted Kremenek65c91652008-04-29 05:44:10 +00001977 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00001978 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek65c91652008-04-29 05:44:10 +00001979 hasErr = V.getKind();
1980 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001981 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00001982 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001983 break;
1984
Ted Kremenek553cf182008-06-25 21:21:56 +00001985 case SelfOwn:
1986 V = V ^ RefVal::NotOwned;
Ted Kremenek9e476de2008-08-12 18:30:56 +00001987 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001988 case DecRef:
1989 switch (V.getKind()) {
1990 default:
1991 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00001992
Ted Kremenek553cf182008-06-25 21:21:56 +00001993 case RefVal::Owned:
1994 V = V.getCount() > 1 ? V - 1 : V ^ RefVal::Released;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001995 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001996
Ted Kremenek553cf182008-06-25 21:21:56 +00001997 case RefVal::NotOwned:
1998 if (V.getCount() > 0)
1999 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00002000 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002001 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002002 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00002003 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002004 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002005
2006 case RefVal::Released:
Ted Kremenek553cf182008-06-25 21:21:56 +00002007 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002008 hasErr = V.getKind();
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002009 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002010 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002011 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002012 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002013 return RefBFactory.Add(B, sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002014}
2015
Ted Kremenekfa34b332008-04-09 01:10:13 +00002016//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002017// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00002018//===----------------------------------------------------------------------===//
2019
Ted Kremenek8dd56462008-04-18 03:39:05 +00002020namespace {
2021
2022 //===-------------===//
2023 // Bug Descriptions. //
2024 //===-------------===//
2025
Ted Kremenekcf118d42009-02-04 23:49:09 +00002026 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002027 protected:
2028 CFRefCount& TF;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002029
2030 CFRefBug(CFRefCount* tf, const char* name)
2031 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002032 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002033
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002034 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00002035 const CFRefCount& getTF() const { return TF; }
2036
Ted Kremenekcf118d42009-02-04 23:49:09 +00002037 // FIXME: Eventually remove.
2038 virtual const char* getDescription() const = 0;
2039
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002040 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002041 };
2042
2043 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2044 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002045 UseAfterRelease(CFRefCount* tf)
2046 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002047
Ted Kremenekcf118d42009-02-04 23:49:09 +00002048 const char* getDescription() const {
Ted Kremenek9e476de2008-08-12 18:30:56 +00002049 return "Reference-counted object is used after it is released.";
Ted Kremenekcf701772009-02-05 06:50:21 +00002050 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002051 };
2052
2053 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2054 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002055 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2056
2057 const char* getDescription() const {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002058 return "Incorrect decrement of the reference count of a "
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002059 "CoreFoundation object: "
Ted Kremenek8dd56462008-04-18 03:39:05 +00002060 "The object is not owned at this point by the caller.";
2061 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002062 };
2063
2064 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002065 const bool isReturn;
2066 protected:
2067 Leak(CFRefCount* tf, const char* name, bool isRet)
2068 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002069 public:
Ted Kremenek8dd56462008-04-18 03:39:05 +00002070
Ted Kremenekd3057212009-02-07 22:38:00 +00002071 const char* getDescription() const { return ""; }
Ted Kremenek3148eb42009-01-24 00:55:43 +00002072
Ted Kremeneke45e57f2009-02-05 00:38:00 +00002073 bool isLeak() const { return true; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002074 };
Ted Kremenekcf118d42009-02-04 23:49:09 +00002075
2076 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2077 public:
2078 LeakAtReturn(CFRefCount* tf, const char* name)
2079 : Leak(tf, name, true) {}
2080 };
2081
2082 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2083 public:
2084 LeakWithinFunction(CFRefCount* tf, const char* name)
2085 : Leak(tf, name, false) {}
2086 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002087
2088 //===---------===//
2089 // Bug Reports. //
2090 //===---------===//
2091
2092 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek66d97062009-02-07 22:04:05 +00002093 protected:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002094 SymbolRef Sym;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002095 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002096 CFRefReport(CFRefBug& D, ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekcf118d42009-02-04 23:49:09 +00002097 : RangedBugReport(D, D.getDescription(), n), Sym(sym) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002098
2099 virtual ~CFRefReport() {}
2100
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002101 CFRefBug& getBugType() {
2102 return (CFRefBug&) RangedBugReport::getBugType();
2103 }
2104 const CFRefBug& getBugType() const {
2105 return (const CFRefBug&) RangedBugReport::getBugType();
2106 }
2107
2108 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2109 const SourceRange*& end) {
2110
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002111 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002112 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002113 else
2114 beg = end = 0;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002115 }
2116
Ted Kremenek2dabd432008-12-05 02:27:51 +00002117 SymbolRef getSymbol() const { return Sym; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002118
Ted Kremenek3148eb42009-01-24 00:55:43 +00002119 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2120 const ExplodedNode<GRState>* N);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002121
Ted Kremenek3148eb42009-01-24 00:55:43 +00002122 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002123
Ted Kremenek3148eb42009-01-24 00:55:43 +00002124 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2125 const ExplodedNode<GRState>* PrevN,
2126 const ExplodedGraph<GRState>& G,
2127 BugReporter& BR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002128 };
2129
Ted Kremenekcf118d42009-02-04 23:49:09 +00002130 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremeneke469fa02009-02-07 22:19:59 +00002131 SourceLocation AllocSite;
2132 const MemRegion* AllocBinding;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002133 public:
Ted Kremeneke469fa02009-02-07 22:19:59 +00002134 CFRefLeakReport(CFRefBug& D, ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenekd3057212009-02-07 22:38:00 +00002135 GRExprEngine& Eng);
Ted Kremenek66d97062009-02-07 22:04:05 +00002136
2137 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2138 const ExplodedNode<GRState>* N);
2139
Ted Kremeneke469fa02009-02-07 22:19:59 +00002140 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekcf118d42009-02-04 23:49:09 +00002141 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002142} // end anonymous namespace
2143
Ted Kremenekcf118d42009-02-04 23:49:09 +00002144void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenekcf701772009-02-05 06:50:21 +00002145 useAfterRelease = new UseAfterRelease(this);
2146 BR.Register(useAfterRelease);
2147
2148 releaseNotOwned = new BadRelease(this);
2149 BR.Register(releaseNotOwned);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002150
2151 // First register "return" leaks.
2152 const char* name = 0;
2153
2154 if (isGCEnabled())
2155 name = "[naming convention] leak of returned object (GC)";
2156 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2157 name = "[naming convention] leak of returned object (hybrid MM, "
2158 "non-GC)";
2159 else {
2160 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2161 name = "[naming convention] leak of returned object";
2162 }
2163
Ted Kremenekcf701772009-02-05 06:50:21 +00002164 leakAtReturn = new LeakAtReturn(this, name);
2165 BR.Register(leakAtReturn);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002166
Ted Kremenekcf118d42009-02-04 23:49:09 +00002167 // Second, register leaks within a function/method.
2168 if (isGCEnabled())
2169 name = "leak (GC)";
2170 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2171 name = "leak (hybrid MM, non-GC)";
2172 else {
2173 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2174 name = "leak";
2175 }
2176
Ted Kremenekcf701772009-02-05 06:50:21 +00002177 leakWithinFunction = new LeakWithinFunction(this, name);
2178 BR.Register(leakWithinFunction);
2179
2180 // Save the reference to the BugReporter.
2181 this->BR = &BR;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002182}
Ted Kremenek072192b2008-04-30 23:47:44 +00002183
2184static const char* Msgs[] = {
2185 "Code is compiled in garbage collection only mode" // GC only
2186 " (the bug occurs with garbage collection enabled).",
2187
2188 "Code is compiled without garbage collection.", // No GC.
2189
2190 "Code is compiled for use with and without garbage collection (GC)."
2191 " The bug occurs with GC enabled.", // Hybrid, with GC.
2192
2193 "Code is compiled for use with and without garbage collection (GC)."
2194 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2195};
2196
2197std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2198 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2199
2200 switch (TF.getLangOptions().getGCMode()) {
2201 default:
2202 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002203
2204 case LangOptions::GCOnly:
2205 assert (TF.isGCEnabled());
Ted Kremenek9e476de2008-08-12 18:30:56 +00002206 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2207
Ted Kremenek072192b2008-04-30 23:47:44 +00002208 case LangOptions::NonGC:
2209 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002210 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2211
2212 case LangOptions::HybridGC:
2213 if (TF.isGCEnabled())
2214 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2215 else
2216 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2217 }
2218}
2219
Ted Kremenek3148eb42009-01-24 00:55:43 +00002220PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2221 const ExplodedNode<GRState>* PrevN,
2222 const ExplodedGraph<GRState>& G,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002223 BugReporter& BR) {
2224
Ted Kremenek611a15a2009-01-28 05:29:13 +00002225 // Check if the type state has changed.
2226 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2227 GRStateRef PrevSt(PrevN->getState(), StMgr);
2228 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek20982802009-01-28 05:06:46 +00002229
Ted Kremenek611a15a2009-01-28 05:29:13 +00002230 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2231 if (!CurrT) return NULL;
2232
2233 const RefVal& CurrV = *CurrT;
2234 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenekce48e002008-05-05 17:53:17 +00002235
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002236 if (!PrevT) {
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002237 std::string sbuf;
2238 llvm::raw_string_ostream os(sbuf);
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002239
Ted Kremenekce48e002008-05-05 17:53:17 +00002240 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2241
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002242 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2243 // Get the name of the callee (if it is available).
2244 SVal X = CurrSt.GetSVal(CE->getCallee());
2245 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2246 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2247 else
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002248 os << "function call";
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002249 }
2250 else {
2251 assert (isa<ObjCMessageExpr>(S));
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002252 os << "Method";
Ted Kremenekce48e002008-05-05 17:53:17 +00002253 }
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002254
Ted Kremenek961b61d2009-01-28 06:06:36 +00002255 if (CurrV.getObjKind() == RetEffect::CF) {
2256 os << " returns a Core Foundation object with a ";
2257 }
2258 else {
2259 assert (CurrV.getObjKind() == RetEffect::ObjC);
2260 os << " returns an Objective-C object with a ";
2261 }
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002262
Ted Kremenek23b8eaa2009-01-28 06:25:48 +00002263 if (CurrV.isOwned()) {
2264 os << "+1 retain count (owning reference).";
2265
2266 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2267 assert(CurrV.getObjKind() == RetEffect::CF);
2268 os << " "
2269 "Core Foundation objects are not automatically garbage collected.";
2270 }
2271 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002272 else {
2273 assert (CurrV.isNotOwned());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002274 os << "+0 retain count (non-owning reference).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002275 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002276
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002277 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002278 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002279
2280 if (Expr* Exp = dyn_cast<Expr>(S))
2281 P->addRange(Exp->getSourceRange());
2282
2283 return P;
2284 }
2285
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002286 // Determine if the typestate has changed.
Ted Kremenek611a15a2009-01-28 05:29:13 +00002287 RefVal PrevV = *PrevT;
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002288
2289 if (PrevV == CurrV)
2290 return NULL;
2291
2292 // The typestate has changed.
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002293 std::string sbuf;
2294 llvm::raw_string_ostream os(sbuf);
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002295
2296 switch (CurrV.getKind()) {
2297 case RefVal::Owned:
2298 case RefVal::NotOwned:
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002299
2300 if (PrevV.getCount() == CurrV.getCount())
2301 return 0;
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002302
2303 if (PrevV.getCount() > CurrV.getCount())
2304 os << "Reference count decremented.";
2305 else
2306 os << "Reference count incremented.";
2307
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002308 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002309 os << " Object has +" << Count;
Ted Kremenek79c140b2008-04-18 05:32:44 +00002310
Ted Kremenekce48e002008-05-05 17:53:17 +00002311 if (Count > 1)
2312 os << " retain counts.";
Ted Kremenek79c140b2008-04-18 05:32:44 +00002313 else
Ted Kremenekce48e002008-05-05 17:53:17 +00002314 os << " retain count.";
Ted Kremenek79c140b2008-04-18 05:32:44 +00002315 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002316
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002317 break;
2318
2319 case RefVal::Released:
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002320 os << "Object released.";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002321 break;
2322
2323 case RefVal::ReturnedOwned:
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002324 os << "Object returned to caller as an owning reference (single retain "
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002325 "count transferred to caller).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002326 break;
2327
2328 case RefVal::ReturnedNotOwned:
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002329 os << "Object returned to caller with a +0 (non-owning) retain count.";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002330 break;
2331
2332 default:
2333 return NULL;
2334 }
2335
2336 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2337 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002338 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002339
2340 // Add the range by scanning the children of the statement for any bindings
2341 // to Sym.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002342 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2343 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek20982802009-01-28 05:06:46 +00002344 SVal X = CurrSt.GetSVal(Exp);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002345 if (loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&X))
Ted Kremenek20982802009-01-28 05:06:46 +00002346 if (SV->getSymbol() == Sym) P->addRange(Exp->getSourceRange()); break;
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002347 }
2348
2349 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002350}
2351
Ted Kremenek9e240492008-10-04 05:50:14 +00002352namespace {
2353class VISIBILITY_HIDDEN FindUniqueBinding :
2354 public StoreManager::BindingsHandler {
Ted Kremenek2dabd432008-12-05 02:27:51 +00002355 SymbolRef Sym;
Ted Kremenek9e240492008-10-04 05:50:14 +00002356 MemRegion* Binding;
2357 bool First;
2358
2359 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002360 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenek9e240492008-10-04 05:50:14 +00002361
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002362 bool HandleBinding(StoreManager& SMgr, Store store, MemRegion* R, SVal val) {
2363 if (const loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002364 if (SV->getSymbol() != Sym)
2365 return true;
2366 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002367 else if (const nonloc::SymbolVal* SV=dyn_cast<nonloc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002368 if (SV->getSymbol() != Sym)
2369 return true;
2370 }
2371 else
2372 return true;
2373
2374 if (Binding) {
2375 First = false;
2376 return false;
2377 }
2378 else
2379 Binding = R;
2380
2381 return true;
2382 }
2383
2384 operator bool() { return First && Binding; }
2385 MemRegion* getRegion() { return Binding; }
2386};
2387}
2388
Ted Kremenek3148eb42009-01-24 00:55:43 +00002389static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremeneke469fa02009-02-07 22:19:59 +00002390GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002391 SymbolRef Sym) {
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002392
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002393 // Find both first node that referred to the tracked symbol and the
2394 // memory location that value was store to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002395 const ExplodedNode<GRState>* Last = N;
2396 const MemRegion* FirstBinding = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002397
2398 while (N) {
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002399 const GRState* St = N->getState();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002400 RefBindings B = St->get<RefBindings>();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002401
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002402 if (!B.lookup(Sym))
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002403 break;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002404
Ted Kremeneke469fa02009-02-07 22:19:59 +00002405 FindUniqueBinding FB(Sym);
2406 StateMgr.iterBindings(St, FB);
2407 if (FB) FirstBinding = FB.getRegion();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002408
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002409 Last = N;
2410 N = N->pred_empty() ? NULL : *(N->pred_begin());
2411 }
2412
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002413 return std::make_pair(Last, FirstBinding);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002414}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002415
Ted Kremenek3148eb42009-01-24 00:55:43 +00002416PathDiagnosticPiece*
2417CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002418
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002419 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002420 // Tell the BugReporter to report cases when the tracked symbol is
2421 // assigned to different variables, etc.
Ted Kremenekc0959972008-07-02 21:24:01 +00002422 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek66d97062009-02-07 22:04:05 +00002423 return RangedBugReport::getEndPath(BR, EndN);
2424}
2425
2426PathDiagnosticPiece*
2427CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2428
2429 GRBugReporter& BR = cast<GRBugReporter>(br);
2430 // Tell the BugReporter to report cases when the tracked symbol is
2431 // assigned to different variables, etc.
2432 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2433
2434 // We are reporting a leak. Walk up the graph to get to the first node where
2435 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002436 // is stored to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002437 const ExplodedNode<GRState>* AllocNode = 0;
2438 const MemRegion* FirstBinding = 0;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002439
2440 llvm::tie(AllocNode, FirstBinding) =
Ted Kremeneke469fa02009-02-07 22:19:59 +00002441 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002442
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002443 // Get the allocate site.
2444 assert (AllocNode);
2445 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002446
Ted Kremeneke28565b2008-05-05 18:50:19 +00002447 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002448 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002449
Ted Kremeneke28565b2008-05-05 18:50:19 +00002450 // Get the leak site. We may have multiple ExplodedNodes (one with the
2451 // leak) that occur on the same line number; if the node with the leak
2452 // has any immediate predecessor nodes with the same line number, find
2453 // any transitive-successors that have a different statement and use that
2454 // line number instead. This avoids emiting a diagnostic like:
2455 //
2456 // // 'y' is leaked.
2457 // int x = foo(y);
2458 //
2459 // instead we want:
2460 //
2461 // int x = foo(y);
2462 // // 'y' is leaked.
2463
2464 Stmt* S = getStmt(BR); // This is the statement where the leak occured.
2465 assert (S);
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002466 unsigned EndLine = SMgr.getInstantiationLineNumber(S->getLocStart());
Ted Kremeneke28565b2008-05-05 18:50:19 +00002467
2468 // Look in the *trimmed* graph at the immediate predecessor of EndN. Does
2469 // it occur on the same line?
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002470 PathDiagnosticPiece::DisplayHint Hint = PathDiagnosticPiece::Above;
Ted Kremeneke28565b2008-05-05 18:50:19 +00002471
2472 assert (!EndN->pred_empty()); // Not possible to have 0 predecessors.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002473 const ExplodedNode<GRState> *Pred = *(EndN->pred_begin());
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002474 ProgramPoint PredPos = Pred->getLocation();
Ted Kremeneke28565b2008-05-05 18:50:19 +00002475
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002476 if (PostStmt* PredPS = dyn_cast<PostStmt>(&PredPos)) {
Ted Kremeneke28565b2008-05-05 18:50:19 +00002477
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002478 Stmt* SPred = PredPS->getStmt();
Ted Kremeneke28565b2008-05-05 18:50:19 +00002479
2480 // Predecessor at same line?
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002481 if (SMgr.getInstantiationLineNumber(SPred->getLocStart()) != EndLine) {
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002482 Hint = PathDiagnosticPiece::Below;
2483 S = SPred;
2484 }
Ted Kremeneke28565b2008-05-05 18:50:19 +00002485 }
Ted Kremeneke28565b2008-05-05 18:50:19 +00002486
2487 // Generate the diagnostic.
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002488 FullSourceLoc L( S->getLocStart(), SMgr);
Ted Kremenekc9e3d862009-02-07 21:59:45 +00002489 std::string sbuf;
2490 llvm::raw_string_ostream os(sbuf);
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002491
Ted Kremeneke28565b2008-05-05 18:50:19 +00002492 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002493
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002494 if (FirstBinding)
Ted Kremenek9e240492008-10-04 05:50:14 +00002495 os << " and stored into '" << FirstBinding->getString() << '\'';
2496
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002497 // Get the retain count.
2498 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2499
2500 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenek04f9d462008-12-02 01:26:07 +00002501 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2502 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2503 // to the caller for NS objects.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002504 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2505 os << " is returned from a method whose name ('"
Chris Lattner077bf5e2008-11-24 03:33:13 +00002506 << MD.getSelector().getAsString()
Ted Kremenek234a4c22009-01-07 00:39:56 +00002507 << "') does not contain 'copy' or otherwise starts with"
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002508 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002509 " in the Memory Management Guide for Cocoa (object leaked).";
2510 }
2511 else
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002512 os << " is no longer referenced after this point and has a retain count of"
2513 " +"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002514 << RV->getCount() << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002515
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002516 return new PathDiagnosticPiece(L, os.str(), Hint);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002517}
2518
Ted Kremenek989d5192008-04-17 23:43:50 +00002519
Ted Kremeneke469fa02009-02-07 22:19:59 +00002520CFRefLeakReport::CFRefLeakReport(CFRefBug& D, ExplodedNode<GRState> *n,
Ted Kremenekd3057212009-02-07 22:38:00 +00002521 SymbolRef sym, GRExprEngine& Eng)
Ted Kremeneke469fa02009-02-07 22:19:59 +00002522 : CFRefReport(D, n, sym)
2523{
2524
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002525 // Most bug reports are cached at the location where they occured.
2526 // With leaks, we want to unique them by the location where they were
Ted Kremeneke469fa02009-02-07 22:19:59 +00002527 // allocated, and only report a single path. To do this, we need to find
2528 // the allocation site of a piece of tracked memory, which we do via a
2529 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2530 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2531 // that all ancestor nodes that represent the allocation site have the
2532 // same SourceLocation.
2533 const ExplodedNode<GRState>* AllocNode = 0;
2534
2535 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekd3057212009-02-07 22:38:00 +00002536 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremeneke469fa02009-02-07 22:19:59 +00002537
Ted Kremeneke469fa02009-02-07 22:19:59 +00002538 // Get the SourceLocation for the allocation site.
Ted Kremenekd3057212009-02-07 22:38:00 +00002539 ProgramPoint P = AllocNode->getLocation();
Ted Kremeneke469fa02009-02-07 22:19:59 +00002540 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenekd3057212009-02-07 22:38:00 +00002541
2542 // Fill in the description of the bug.
2543 Description.clear();
2544 llvm::raw_string_ostream os(Description);
2545 SourceManager& SMgr = Eng.getContext().getSourceManager();
2546 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
2547 os << "Potential leak of object allocated on line " << AllocLine
2548 << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002549}
2550
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002551//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00002552// Handle dead symbols and end-of-path.
2553//===----------------------------------------------------------------------===//
2554
2555void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2556 GREndPathNodeBuilder<GRState>& Builder) {
2557
2558 const GRState* St = Builder.getState();
2559 RefBindings B = St->get<RefBindings>();
2560
2561 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2562 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2563
2564 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2565 bool hasLeak = false;
2566
2567 std::pair<GRStateRef, bool> X =
2568 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2569 (*I).first, (*I).second, hasLeak);
2570
2571 St = X.first;
2572 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2573 }
2574
2575 if (Leaked.empty())
2576 return;
2577
2578 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2579
2580 if (!N)
2581 return;
2582
2583 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2584 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2585
2586 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2587 : leakWithinFunction);
2588 assert(BT && "BugType not initialized.");
Ted Kremenekd3057212009-02-07 22:38:00 +00002589 CFRefLeakReport* report = new CFRefLeakReport(*BT, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00002590 BR->EmitReport(report);
2591 }
2592}
2593
2594void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2595 GRExprEngine& Eng,
2596 GRStmtNodeBuilder<GRState>& Builder,
2597 ExplodedNode<GRState>* Pred,
2598 Stmt* S,
2599 const GRState* St,
2600 SymbolReaper& SymReaper) {
2601
2602 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
2603
2604 RefBindings B = St->get<RefBindings>();
2605 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2606
2607 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2608 E = SymReaper.dead_end(); I != E; ++I) {
2609
2610 const RefVal* T = B.lookup(*I);
2611 if (!T) continue;
2612
2613 bool hasLeak = false;
2614
2615 std::pair<GRStateRef, bool> X
2616 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
2617
2618 St = X.first;
2619
2620 if (hasLeak)
2621 Leaked.push_back(std::make_pair(*I,X.second));
2622 }
2623
2624 if (Leaked.empty())
2625 return;
2626
2627 ExplodedNode<GRState>* N = Builder.MakeNode(Dst, S, Pred, St);
2628
2629 if (!N)
2630 return;
2631
2632 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2633 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2634
2635 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2636 : leakWithinFunction);
2637 assert(BT && "BugType not initialized.");
Ted Kremenekd3057212009-02-07 22:38:00 +00002638 CFRefLeakReport* report = new CFRefLeakReport(*BT, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00002639 BR->EmitReport(report);
2640 }
2641}
2642
2643void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2644 GRStmtNodeBuilder<GRState>& Builder,
2645 Expr* NodeExpr, Expr* ErrorExpr,
2646 ExplodedNode<GRState>* Pred,
2647 const GRState* St,
2648 RefVal::Kind hasErr, SymbolRef Sym) {
2649 Builder.BuildSinks = true;
2650 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2651
2652 if (!N) return;
2653
2654 CFRefBug *BT = 0;
2655
2656 if (hasErr == RefVal::ErrorUseAfterRelease)
2657 BT = static_cast<CFRefBug*>(useAfterRelease);
2658 else {
2659 assert(hasErr == RefVal::ErrorReleaseNotOwned);
2660 BT = static_cast<CFRefBug*>(releaseNotOwned);
2661 }
2662
2663 CFRefReport *report = new CFRefReport(*BT, N, Sym);
2664 report->addRange(ErrorExpr->getSourceRange());
2665 BR->EmitReport(report);
2666}
2667
2668//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00002669// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002670//===----------------------------------------------------------------------===//
2671
Ted Kremenek072192b2008-04-30 23:47:44 +00002672GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2673 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00002674 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00002675}