blob: 0e4c1b1a01759f809e06962b33e2750da391bf1d [file] [log] [blame]
Chris Lattner7a513132008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenekea6507f2008-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 Greif3a8edd82008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenekea6507f2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekb0f87c42008-04-30 23:47:44 +000015#include "clang/Basic/LangOptions.h"
Ted Kremenek1097b4c2008-05-01 23:13:35 +000016#include "clang/Basic/SourceManager.h"
Ted Kremeneke68c0fc2009-02-14 01:43:44 +000017#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek87aab6c2008-08-17 03:20:02 +000018#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekc27815c2008-03-31 18:26:32 +000019#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenekea6507f2008-03-06 00:08:09 +000020#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekce8e8812008-04-09 01:10:13 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek4e9d4b52009-02-14 03:16:10 +000023#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenek1642bda2009-06-26 00:05:51 +000024#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
Ted Kremenek70a87882009-11-25 22:17:44 +000025#include "clang/Analysis/PathSensitive/CheckerVisitor.h"
Mike Stump11289f42009-09-09 15:08:12 +000026#include "clang/AST/DeclObjC.h"
Ted Kremenekf89dcda2009-11-26 02:38:19 +000027#include "clang/AST/StmtVisitor.h"
Ted Kremenek819e9b62008-03-11 06:39:11 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek0747e7e2008-10-21 15:53:15 +000031#include "llvm/ADT/ImmutableList.h"
Ted Kremenekb6cbf282008-05-07 18:36:45 +000032#include "llvm/ADT/StringExtras.h"
Ted Kremenekc812b232008-05-16 18:33:44 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenek9551ab62008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenekea6507f2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenek01acb622008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenek01acb622008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
Mike Stump11289f42009-09-09 15:08:12 +000048// begins with "alloc" or "new" or contains "copy" (for example, alloc,
Ted Kremenek01acb622008-10-24 21:18:08 +000049// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek8a73c712009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenek97ad7b62009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek8a73c712009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
Mike Stump11289f42009-09-09 15:08:12 +000066
67static inline const char* parseWord(const char* s) {
Ted Kremenek8a73c712009-02-21 05:13:43 +000068 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
Ted Kremenek32819772009-05-15 15:49:00 +000079static NamingConvention deriveNamingConvention(Selector S) {
80 IdentifierInfo *II = S.getIdentifierInfoForSlot(0);
Mike Stump11289f42009-09-09 15:08:12 +000081
Ted Kremenek32819772009-05-15 15:49:00 +000082 if (!II)
83 return NoConvention;
Mike Stump11289f42009-09-09 15:08:12 +000084
Daniel Dunbar9d9aa162009-10-17 18:12:45 +000085 const char *s = II->getNameStart();
Mike Stump11289f42009-09-09 15:08:12 +000086
Ted Kremenek8a73c712009-02-21 05:13:43 +000087 // A method/function name may contain a prefix. We don't know it is there,
88 // however, until we encounter the first '_'.
89 bool InPossiblePrefix = true;
90 bool AtBeginning = true;
91 NamingConvention C = NoConvention;
Mike Stump11289f42009-09-09 15:08:12 +000092
Ted Kremenek8a73c712009-02-21 05:13:43 +000093 while (*s != '\0') {
94 // Skip '_'.
95 if (*s == '_') {
96 if (InPossiblePrefix) {
Ted Kremenek90c953e2009-10-20 00:13:00 +000097 // If we already have a convention, return it. Otherwise, skip
98 // the prefix as if it wasn't there.
99 if (C != NoConvention)
100 break;
101
Ted Kremenek8a73c712009-02-21 05:13:43 +0000102 InPossiblePrefix = false;
103 AtBeginning = true;
Ted Kremenek90c953e2009-10-20 00:13:00 +0000104 assert(C == NoConvention);
Ted Kremenek8a73c712009-02-21 05:13:43 +0000105 }
106 ++s;
107 continue;
108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Ted Kremenek8a73c712009-02-21 05:13:43 +0000110 // Skip numbers, ':', etc.
111 if (!isalpha(*s)) {
112 ++s;
113 continue;
114 }
Mike Stump11289f42009-09-09 15:08:12 +0000115
Ted Kremenek8a73c712009-02-21 05:13:43 +0000116 const char *wordEnd = parseWord(s);
117 assert(wordEnd > s);
118 unsigned len = wordEnd - s;
Mike Stump11289f42009-09-09 15:08:12 +0000119
Ted Kremenek8a73c712009-02-21 05:13:43 +0000120 switch (len) {
121 default:
122 break;
123 case 3:
124 // Methods starting with 'new' follow the create rule.
Ted Kremenek97ad7b62009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("new", s, len))
Mike Stump11289f42009-09-09 15:08:12 +0000126 C = CreateRule;
Ted Kremenek8a73c712009-02-21 05:13:43 +0000127 break;
128 case 4:
129 // Methods starting with 'alloc' or contain 'copy' follow the
130 // create rule
Ted Kremenek340fd2d2009-03-13 20:27:06 +0000131 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek8a73c712009-02-21 05:13:43 +0000132 C = CreateRule;
133 else // Methods starting with 'init' follow the init rule.
Ted Kremenek97ad7b62009-02-21 18:26:02 +0000134 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek340fd2d2009-03-13 20:27:06 +0000135 C = InitRule;
136 break;
137 case 5:
138 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
139 C = CreateRule;
Ted Kremenek8a73c712009-02-21 05:13:43 +0000140 break;
141 }
Mike Stump11289f42009-09-09 15:08:12 +0000142
Ted Kremenek8a73c712009-02-21 05:13:43 +0000143 // If we aren't in the prefix and have a derived convention then just
144 // return it now.
145 if (!InPossiblePrefix && C != NoConvention)
146 return C;
147
148 AtBeginning = false;
149 s = wordEnd;
150 }
151
152 // We will get here if there wasn't more than one word
153 // after the prefix.
154 return C;
155}
156
Ted Kremenek32819772009-05-15 15:49:00 +0000157static bool followsFundamentalRule(Selector S) {
158 return deriveNamingConvention(S) == CreateRule;
Ted Kremenek2855a932008-11-05 16:54:44 +0000159}
160
Ted Kremenek223a7d52009-04-29 23:03:22 +0000161static const ObjCMethodDecl*
Mike Stump11289f42009-09-09 15:08:12 +0000162ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD) {
Ted Kremenek223a7d52009-04-29 23:03:22 +0000163 ObjCInterfaceDecl *ID =
164 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000165
Ted Kremenek223a7d52009-04-29 23:03:22 +0000166 return MD->isInstanceMethod()
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000167 ? ID->lookupInstanceMethod(MD->getSelector())
168 : ID->lookupClassMethod(MD->getSelector());
Ted Kremenek2855a932008-11-05 16:54:44 +0000169}
Ted Kremenek01acb622008-10-24 21:18:08 +0000170
Ted Kremenek884a8992009-05-08 23:09:42 +0000171namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000172class GenericNodeBuilder {
Zhongxing Xu107f7592009-08-06 12:48:26 +0000173 GRStmtNodeBuilder *SNB;
Ted Kremenek884a8992009-05-08 23:09:42 +0000174 Stmt *S;
175 const void *tag;
Zhongxing Xu107f7592009-08-06 12:48:26 +0000176 GREndPathNodeBuilder *ENB;
Ted Kremenek884a8992009-05-08 23:09:42 +0000177public:
Zhongxing Xu107f7592009-08-06 12:48:26 +0000178 GenericNodeBuilder(GRStmtNodeBuilder &snb, Stmt *s,
Ted Kremenek884a8992009-05-08 23:09:42 +0000179 const void *t)
180 : SNB(&snb), S(s), tag(t), ENB(0) {}
Zhongxing Xu107f7592009-08-06 12:48:26 +0000181
182 GenericNodeBuilder(GREndPathNodeBuilder &enb)
Ted Kremenek884a8992009-05-08 23:09:42 +0000183 : SNB(0), S(0), tag(0), ENB(&enb) {}
Mike Stump11289f42009-09-09 15:08:12 +0000184
Zhongxing Xu107f7592009-08-06 12:48:26 +0000185 ExplodedNode *MakeNode(const GRState *state, ExplodedNode *Pred) {
Ted Kremenek884a8992009-05-08 23:09:42 +0000186 if (SNB)
Mike Stump11289f42009-09-09 15:08:12 +0000187 return SNB->generateNode(PostStmt(S, Pred->getLocationContext(), tag),
Zhongxing Xue1190f72009-08-15 03:17:38 +0000188 state, Pred);
Mike Stump11289f42009-09-09 15:08:12 +0000189
Ted Kremenek884a8992009-05-08 23:09:42 +0000190 assert(ENB);
Ted Kremenek9ec08aa2009-05-09 00:44:07 +0000191 return ENB->generateNode(state, Pred);
Ted Kremenek884a8992009-05-08 23:09:42 +0000192 }
193};
194} // end anonymous namespace
195
Ted Kremenekc8bef6a2008-04-09 23:49:11 +0000196//===----------------------------------------------------------------------===//
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000197// Type querying functions.
198//===----------------------------------------------------------------------===//
199
Ted Kremenek7e904222009-01-12 21:45:02 +0000200static bool isRefType(QualType RetTy, const char* prefix,
201 ASTContext* Ctx = 0, const char* name = 0) {
Mike Stump11289f42009-09-09 15:08:12 +0000202
Ted Kremenek95d18192009-05-12 04:53:03 +0000203 // Recursively walk the typedef stack, allowing typedefs of reference types.
Daniel Dunbaracb5a4b2009-10-17 18:12:53 +0000204 while (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
Daniel Dunbar07d07852009-10-18 21:17:35 +0000205 llvm::StringRef TDName = TD->getDecl()->getIdentifier()->getName();
Daniel Dunbaracb5a4b2009-10-17 18:12:53 +0000206 if (TDName.startswith(prefix) && TDName.endswith("Ref"))
207 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000208
Daniel Dunbaracb5a4b2009-10-17 18:12:53 +0000209 RetTy = TD->getDecl()->getUnderlyingType();
Ted Kremenek7e904222009-01-12 21:45:02 +0000210 }
211
212 if (!Ctx || !name)
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000213 return false;
Ted Kremenek7e904222009-01-12 21:45:02 +0000214
215 // Is the type void*?
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000216 const PointerType* PT = RetTy->getAs<PointerType>();
Ted Kremenek7e904222009-01-12 21:45:02 +0000217 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000218 return false;
Ted Kremenek7e904222009-01-12 21:45:02 +0000219
220 // Does the name start with the prefix?
Daniel Dunbar9d9aa162009-10-17 18:12:45 +0000221 return llvm::StringRef(name).startswith(prefix);
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000222}
223
Ted Kremeneka506fec2008-04-17 18:12:53 +0000224//===----------------------------------------------------------------------===//
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000225// Primitives used for constructing summaries for function/method calls.
Ted Kremenekc8bef6a2008-04-09 23:49:11 +0000226//===----------------------------------------------------------------------===//
227
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000228/// ArgEffect is used to summarize a function/method call's effect on a
229/// particular argument.
Ted Kremenekea072e32009-03-17 19:42:23 +0000230enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
231 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
232 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000233
Ted Kremenek819e9b62008-03-11 06:39:11 +0000234namespace llvm {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000235template <> struct FoldingSetTrait<ArgEffect> {
236static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
237 ID.AddInteger((unsigned) X);
238}
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000239};
Ted Kremenek819e9b62008-03-11 06:39:11 +0000240} // end llvm namespace
241
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000242/// ArgEffects summarizes the effects of a function/method call on all of
243/// its arguments.
244typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
245
Ted Kremenek819e9b62008-03-11 06:39:11 +0000246namespace {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000247
248/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump11289f42009-09-09 15:08:12 +0000249/// respect to its return value.
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000250class RetEffect {
Ted Kremenek819e9b62008-03-11 06:39:11 +0000251public:
Ted Kremenekab4a8b52008-06-23 18:02:52 +0000252 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek1272f702009-05-12 20:06:54 +0000253 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
254 OwnedWhenTrackedReceiver };
Mike Stump11289f42009-09-09 15:08:12 +0000255
256 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000257
Ted Kremenek819e9b62008-03-11 06:39:11 +0000258private:
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000259 Kind K;
260 ObjKind O;
261 unsigned index;
262
263 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
264 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000265
Ted Kremenek819e9b62008-03-11 06:39:11 +0000266public:
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000267 Kind getKind() const { return K; }
268
269 ObjKind getObjKind() const { return O; }
Mike Stump11289f42009-09-09 15:08:12 +0000270
271 unsigned getIndex() const {
Ted Kremenek819e9b62008-03-11 06:39:11 +0000272 assert(getKind() == Alias);
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000273 return index;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000274 }
Mike Stump11289f42009-09-09 15:08:12 +0000275
Ted Kremenek223a7d52009-04-29 23:03:22 +0000276 bool isOwned() const {
Ted Kremenek1272f702009-05-12 20:06:54 +0000277 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
278 K == OwnedWhenTrackedReceiver;
Ted Kremenek223a7d52009-04-29 23:03:22 +0000279 }
Mike Stump11289f42009-09-09 15:08:12 +0000280
Ted Kremenek1272f702009-05-12 20:06:54 +0000281 static RetEffect MakeOwnedWhenTrackedReceiver() {
282 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
283 }
Mike Stump11289f42009-09-09 15:08:12 +0000284
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000285 static RetEffect MakeAlias(unsigned Idx) {
286 return RetEffect(Alias, Idx);
287 }
288 static RetEffect MakeReceiverAlias() {
289 return RetEffect(ReceiverAlias);
Mike Stump11289f42009-09-09 15:08:12 +0000290 }
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000291 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
292 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump11289f42009-09-09 15:08:12 +0000293 }
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000294 static RetEffect MakeNotOwned(ObjKind o) {
295 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke6633562009-04-27 19:14:45 +0000296 }
297 static RetEffect MakeGCNotOwned() {
298 return RetEffect(GCNotOwnedSymbol, ObjC);
299 }
Mike Stump11289f42009-09-09 15:08:12 +0000300
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000301 static RetEffect MakeNoRet() {
302 return RetEffect(NoRet);
Ted Kremenekab4a8b52008-06-23 18:02:52 +0000303 }
Mike Stump11289f42009-09-09 15:08:12 +0000304
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000305 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000306 ID.AddInteger((unsigned)K);
307 ID.AddInteger((unsigned)O);
308 ID.AddInteger(index);
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000309 }
Ted Kremenek819e9b62008-03-11 06:39:11 +0000310};
Mike Stump11289f42009-09-09 15:08:12 +0000311
Ted Kremeneka2968e52009-11-13 01:54:21 +0000312//===----------------------------------------------------------------------===//
313// Reference-counting logic (typestate + counts).
314//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000315
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000316class RefVal {
Ted Kremeneka2968e52009-11-13 01:54:21 +0000317public:
318 enum Kind {
319 Owned = 0, // Owning reference.
320 NotOwned, // Reference is not owned by still valid (not freed).
321 Released, // Object has been released.
322 ReturnedOwned, // Returned object passes ownership to caller.
323 ReturnedNotOwned, // Return object does not pass ownership to caller.
324 ERROR_START,
325 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
326 ErrorDeallocGC, // Calling -dealloc with GC enabled.
327 ErrorUseAfterRelease, // Object used after released.
328 ErrorReleaseNotOwned, // Release of an object that was not owned.
329 ERROR_LEAK_START,
330 ErrorLeak, // A memory leak due to excessive reference counts.
331 ErrorLeakReturned, // A memory leak due to the returning method not having
332 // the correct naming conventions.
333 ErrorGCLeakReturned,
334 ErrorOverAutorelease,
335 ErrorReturnedNotOwned
336 };
337
338private:
339 Kind kind;
340 RetEffect::ObjKind okind;
341 unsigned Cnt;
342 unsigned ACnt;
343 QualType T;
344
345 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
346 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
347
348 RefVal(Kind k, unsigned cnt = 0)
349 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
350
351public:
352 Kind getKind() const { return kind; }
353
354 RetEffect::ObjKind getObjKind() const { return okind; }
355
356 unsigned getCount() const { return Cnt; }
357 unsigned getAutoreleaseCount() const { return ACnt; }
358 unsigned getCombinedCounts() const { return Cnt + ACnt; }
359 void clearCounts() { Cnt = 0; ACnt = 0; }
360 void setCount(unsigned i) { Cnt = i; }
361 void setAutoreleaseCount(unsigned i) { ACnt = i; }
362
363 QualType getType() const { return T; }
364
365 // Useful predicates.
366
367 static bool isError(Kind k) { return k >= ERROR_START; }
368
369 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
370
371 bool isOwned() const {
372 return getKind() == Owned;
373 }
374
375 bool isNotOwned() const {
376 return getKind() == NotOwned;
377 }
378
379 bool isReturnedOwned() const {
380 return getKind() == ReturnedOwned;
381 }
382
383 bool isReturnedNotOwned() const {
384 return getKind() == ReturnedNotOwned;
385 }
386
387 bool isNonLeakError() const {
388 Kind k = getKind();
389 return isError(k) && !isLeak(k);
390 }
391
392 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
393 unsigned Count = 1) {
394 return RefVal(Owned, o, Count, 0, t);
395 }
396
397 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
398 unsigned Count = 0) {
399 return RefVal(NotOwned, o, Count, 0, t);
400 }
401
402 // Comparison, profiling, and pretty-printing.
403
404 bool operator==(const RefVal& X) const {
405 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
406 }
407
408 RefVal operator-(size_t i) const {
409 return RefVal(getKind(), getObjKind(), getCount() - i,
410 getAutoreleaseCount(), getType());
411 }
412
413 RefVal operator+(size_t i) const {
414 return RefVal(getKind(), getObjKind(), getCount() + i,
415 getAutoreleaseCount(), getType());
416 }
417
418 RefVal operator^(Kind k) const {
419 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
420 getType());
421 }
422
423 RefVal autorelease() const {
424 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
425 getType());
426 }
427
428 void Profile(llvm::FoldingSetNodeID& ID) const {
429 ID.AddInteger((unsigned) kind);
430 ID.AddInteger(Cnt);
431 ID.AddInteger(ACnt);
432 ID.Add(T);
433 }
434
435 void print(llvm::raw_ostream& Out) const;
436};
437
438void RefVal::print(llvm::raw_ostream& Out) const {
439 if (!T.isNull())
440 Out << "Tracked Type:" << T.getAsString() << '\n';
441
442 switch (getKind()) {
443 default: assert(false);
444 case Owned: {
445 Out << "Owned";
446 unsigned cnt = getCount();
447 if (cnt) Out << " (+ " << cnt << ")";
448 break;
449 }
450
451 case NotOwned: {
452 Out << "NotOwned";
453 unsigned cnt = getCount();
454 if (cnt) Out << " (+ " << cnt << ")";
455 break;
456 }
457
458 case ReturnedOwned: {
459 Out << "ReturnedOwned";
460 unsigned cnt = getCount();
461 if (cnt) Out << " (+ " << cnt << ")";
462 break;
463 }
464
465 case ReturnedNotOwned: {
466 Out << "ReturnedNotOwned";
467 unsigned cnt = getCount();
468 if (cnt) Out << " (+ " << cnt << ")";
469 break;
470 }
471
472 case Released:
473 Out << "Released";
474 break;
475
476 case ErrorDeallocGC:
477 Out << "-dealloc (GC)";
478 break;
479
480 case ErrorDeallocNotOwned:
481 Out << "-dealloc (not-owned)";
482 break;
483
484 case ErrorLeak:
485 Out << "Leaked";
486 break;
487
488 case ErrorLeakReturned:
489 Out << "Leaked (Bad naming)";
490 break;
491
492 case ErrorGCLeakReturned:
493 Out << "Leaked (GC-ed at return)";
494 break;
495
496 case ErrorUseAfterRelease:
497 Out << "Use-After-Release [ERROR]";
498 break;
499
500 case ErrorReleaseNotOwned:
501 Out << "Release of Not-Owned [ERROR]";
502 break;
503
504 case RefVal::ErrorOverAutorelease:
505 Out << "Over autoreleased";
506 break;
507
508 case RefVal::ErrorReturnedNotOwned:
509 Out << "Non-owned object returned instead of owned";
510 break;
511 }
512
513 if (ACnt) {
514 Out << " [ARC +" << ACnt << ']';
515 }
516}
517} //end anonymous namespace
518
519//===----------------------------------------------------------------------===//
520// RefBindings - State used to track object reference counts.
521//===----------------------------------------------------------------------===//
522
523typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremeneka2968e52009-11-13 01:54:21 +0000524
525namespace clang {
526 template<>
527 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
Ted Kremenek3c557182009-11-13 01:58:01 +0000528 static void* GDMIndex() {
529 static int RefBIndex = 0;
530 return &RefBIndex;
531 }
Ted Kremeneka2968e52009-11-13 01:54:21 +0000532 };
533}
534
535//===----------------------------------------------------------------------===//
536// Summaries
537//===----------------------------------------------------------------------===//
538
539namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000540class RetainSummary {
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000541 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
542 /// specifies the argument (starting from 0). This can be sparsely
543 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000544 ArgEffects Args;
Mike Stump11289f42009-09-09 15:08:12 +0000545
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000546 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
547 /// do not have an entry in Args.
548 ArgEffect DefaultArgEffect;
Mike Stump11289f42009-09-09 15:08:12 +0000549
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000550 /// Receiver - If this summary applies to an Objective-C message expression,
551 /// this is the effect applied to the state of the receiver.
Ted Kremenekb0862dc2008-05-06 02:26:56 +0000552 ArgEffect Receiver;
Mike Stump11289f42009-09-09 15:08:12 +0000553
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000554 /// Ret - The effect on the return value. Used to indicate if the
555 /// function/method call returns a new tracked symbol, returns an
556 /// alias of one of the arguments in the call, and so on.
Ted Kremenek819e9b62008-03-11 06:39:11 +0000557 RetEffect Ret;
Mike Stump11289f42009-09-09 15:08:12 +0000558
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000559 /// EndPath - Indicates that execution of this method/function should
560 /// terminate the simulation of a path.
561 bool EndPath;
Mike Stump11289f42009-09-09 15:08:12 +0000562
Ted Kremenek819e9b62008-03-11 06:39:11 +0000563public:
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000564 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000565 ArgEffect ReceiverEff, bool endpath = false)
566 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
Mike Stump11289f42009-09-09 15:08:12 +0000567 EndPath(endpath) {}
568
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000569 /// getArg - Return the argument effect on the argument specified by
570 /// idx (starting from 0).
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000571 ArgEffect getArg(unsigned idx) const {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000572 if (const ArgEffect *AE = Args.lookup(idx))
573 return *AE;
Mike Stump11289f42009-09-09 15:08:12 +0000574
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000575 return DefaultArgEffect;
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000576 }
Mike Stump11289f42009-09-09 15:08:12 +0000577
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000578 /// setDefaultArgEffect - Set the default argument effect.
579 void setDefaultArgEffect(ArgEffect E) {
580 DefaultArgEffect = E;
581 }
Mike Stump11289f42009-09-09 15:08:12 +0000582
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000583 /// setArg - Set the argument effect on the argument specified by idx.
584 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
585 Args = AF.Add(Args, idx, E);
586 }
Mike Stump11289f42009-09-09 15:08:12 +0000587
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000588 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000589 RetEffect getRetEffect() const { return Ret; }
Mike Stump11289f42009-09-09 15:08:12 +0000590
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000591 /// setRetEffect - Set the effect of the return value of the call.
592 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000593
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000594 /// isEndPath - Returns true if executing the given method/function should
595 /// terminate the path.
596 bool isEndPath() const { return EndPath; }
Mike Stump11289f42009-09-09 15:08:12 +0000597
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000598 /// getReceiverEffect - Returns the effect on the receiver of the call.
599 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000600 ArgEffect getReceiverEffect() const { return Receiver; }
Mike Stump11289f42009-09-09 15:08:12 +0000601
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000602 /// setReceiverEffect - Set the effect on the receiver of the call.
603 void setReceiverEffect(ArgEffect E) { Receiver = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000604
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000605 typedef ArgEffects::iterator ExprIterator;
Mike Stump11289f42009-09-09 15:08:12 +0000606
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000607 ExprIterator begin_args() const { return Args.begin(); }
608 ExprIterator end_args() const { return Args.end(); }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000610 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000611 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenekf7faa422008-07-18 17:39:56 +0000612 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000613 ID.Add(A);
Ted Kremenekb0862dc2008-05-06 02:26:56 +0000614 ID.Add(RetEff);
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000615 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenekb0862dc2008-05-06 02:26:56 +0000616 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenekf7faa422008-07-18 17:39:56 +0000617 ID.AddInteger((unsigned) EndPath);
Ted Kremenek819e9b62008-03-11 06:39:11 +0000618 }
Mike Stump11289f42009-09-09 15:08:12 +0000619
Ted Kremenek819e9b62008-03-11 06:39:11 +0000620 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenekf7faa422008-07-18 17:39:56 +0000621 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek819e9b62008-03-11 06:39:11 +0000622 }
623};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000624} // end anonymous namespace
Ted Kremenek819e9b62008-03-11 06:39:11 +0000625
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000626//===----------------------------------------------------------------------===//
627// Data structures for constructing summaries.
628//===----------------------------------------------------------------------===//
Ted Kremenekb1d13292008-06-24 03:49:48 +0000629
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000630namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000631class ObjCSummaryKey {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000632 IdentifierInfo* II;
633 Selector S;
Mike Stump11289f42009-09-09 15:08:12 +0000634public:
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000635 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
636 : II(ii), S(s) {}
637
Ted Kremenek223a7d52009-04-29 23:03:22 +0000638 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000639 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek5801f652009-05-13 18:16:01 +0000640
641 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
642 : II(d ? d->getIdentifier() : ii), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000643
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000644 ObjCSummaryKey(Selector s)
645 : II(0), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000646
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000647 IdentifierInfo* getIdentifier() const { return II; }
648 Selector getSelector() const { return S; }
649};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000650}
651
652namespace llvm {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000653template <> struct DenseMapInfo<ObjCSummaryKey> {
654 static inline ObjCSummaryKey getEmptyKey() {
655 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
656 DenseMapInfo<Selector>::getEmptyKey());
657 }
Mike Stump11289f42009-09-09 15:08:12 +0000658
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000659 static inline ObjCSummaryKey getTombstoneKey() {
660 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump11289f42009-09-09 15:08:12 +0000661 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000662 }
Mike Stump11289f42009-09-09 15:08:12 +0000663
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000664 static unsigned getHashValue(const ObjCSummaryKey &V) {
665 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000666 & 0x88888888)
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000667 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
668 & 0x55555555);
669 }
Mike Stump11289f42009-09-09 15:08:12 +0000670
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000671 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
672 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
673 RHS.getIdentifier()) &&
674 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
675 RHS.getSelector());
676 }
Mike Stump11289f42009-09-09 15:08:12 +0000677
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000678 static bool isPod() {
679 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
680 DenseMapInfo<Selector>::isPod();
681 }
682};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000683} // end llvm namespace
Mike Stump11289f42009-09-09 15:08:12 +0000684
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000685namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000686class ObjCSummaryCache {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000687 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
688 MapTy M;
689public:
690 ObjCSummaryCache() {}
Mike Stump11289f42009-09-09 15:08:12 +0000691
Ted Kremenek8be51382009-07-21 23:27:57 +0000692 RetainSummary* find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +0000693 Selector S) {
Ted Kremenek0b50fb12009-04-29 05:04:30 +0000694 // Lookup the method using the decl for the class @interface. If we
695 // have no decl, lookup using the class name.
696 return D ? find(D, S) : find(ClsName, S);
697 }
Mike Stump11289f42009-09-09 15:08:12 +0000698
699 RetainSummary* find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000700 // Do a lookup with the (D,S) pair. If we find a match return
701 // the iterator.
702 ObjCSummaryKey K(D, S);
703 MapTy::iterator I = M.find(K);
Mike Stump11289f42009-09-09 15:08:12 +0000704
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000705 if (I != M.end() || !D)
Ted Kremenek8be51382009-07-21 23:27:57 +0000706 return I->second;
Mike Stump11289f42009-09-09 15:08:12 +0000707
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000708 // Walk the super chain. If we find a hit with a parent, we'll end
709 // up returning that summary. We actually allow that key (null,S), as
710 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
711 // generate initial summaries without having to worry about NSObject
712 // being declared.
713 // FIXME: We may change this at some point.
714 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
715 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
716 break;
Mike Stump11289f42009-09-09 15:08:12 +0000717
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000718 if (!C)
Ted Kremenek8be51382009-07-21 23:27:57 +0000719 return NULL;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000720 }
Mike Stump11289f42009-09-09 15:08:12 +0000721
722 // Cache the summary with original key to make the next lookup faster
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000723 // and return the iterator.
Ted Kremenek8be51382009-07-21 23:27:57 +0000724 RetainSummary *Summ = I->second;
725 M[K] = Summ;
726 return Summ;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000727 }
Mike Stump11289f42009-09-09 15:08:12 +0000728
Ted Kremenek9551ab62008-08-12 20:41:56 +0000729
Ted Kremenek8be51382009-07-21 23:27:57 +0000730 RetainSummary* find(Expr* Receiver, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000731 return find(getReceiverDecl(Receiver), S);
732 }
Mike Stump11289f42009-09-09 15:08:12 +0000733
Ted Kremenek8be51382009-07-21 23:27:57 +0000734 RetainSummary* find(IdentifierInfo* II, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000735 // FIXME: Class method lookup. Right now we dont' have a good way
736 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek8be51382009-07-21 23:27:57 +0000737 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump11289f42009-09-09 15:08:12 +0000738
Ted Kremenek8be51382009-07-21 23:27:57 +0000739 if (I == M.end())
740 I = M.find(ObjCSummaryKey(S));
Mike Stump11289f42009-09-09 15:08:12 +0000741
Ted Kremenek8be51382009-07-21 23:27:57 +0000742 return I == M.end() ? NULL : I->second;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
745 const ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
Steve Naroff7cae42b2009-07-10 23:34:53 +0000746 if (const ObjCObjectPointerType* PT =
John McCall9dd450b2009-09-21 23:43:11 +0000747 E->getType()->getAs<ObjCObjectPointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +0000748 return PT->getInterfaceDecl();
749
750 return NULL;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000751 }
Mike Stump11289f42009-09-09 15:08:12 +0000752
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000753 RetainSummary*& operator[](ObjCMessageExpr* ME) {
Mike Stump11289f42009-09-09 15:08:12 +0000754
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000755 Selector S = ME->getSelector();
Mike Stump11289f42009-09-09 15:08:12 +0000756
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000757 if (Expr* Receiver = ME->getReceiver()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +0000758 const ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000759 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000762 return M[ObjCSummaryKey(ME->getClassName(), S)];
763 }
Mike Stump11289f42009-09-09 15:08:12 +0000764
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000765 RetainSummary*& operator[](ObjCSummaryKey K) {
766 return M[K];
767 }
Mike Stump11289f42009-09-09 15:08:12 +0000768
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000769 RetainSummary*& operator[](Selector S) {
770 return M[ ObjCSummaryKey(S) ];
771 }
Mike Stump11289f42009-09-09 15:08:12 +0000772};
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000773} // end anonymous namespace
774
775//===----------------------------------------------------------------------===//
776// Data structures for managing collections of summaries.
777//===----------------------------------------------------------------------===//
778
779namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000780class RetainSummaryManager {
Ted Kremenek00daccd2008-05-05 22:11:16 +0000781
782 //==-----------------------------------------------------------------==//
783 // Typedefs.
784 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000785
Ted Kremenek00daccd2008-05-05 22:11:16 +0000786 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
787 FuncSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000788
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000789 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000790
Ted Kremenek00daccd2008-05-05 22:11:16 +0000791 //==-----------------------------------------------------------------==//
792 // Data.
793 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000794
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000795 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000796 ASTContext& Ctx;
Ted Kremenekab54e512008-07-01 17:21:27 +0000797
Ted Kremenekae529272008-07-09 18:11:16 +0000798 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
799 /// "CFDictionaryCreate".
800 IdentifierInfo* CFDictionaryCreateII;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000802 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000803 const bool GCEnabled;
Mike Stump11289f42009-09-09 15:08:12 +0000804
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000805 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump11289f42009-09-09 15:08:12 +0000806 FuncSummariesTy FuncSummaries;
807
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000808 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
809 /// to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000810 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000811
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000812 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000813 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000814
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000815 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
816 /// and all other data used by the checker.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000817 llvm::BumpPtrAllocator BPAlloc;
Mike Stump11289f42009-09-09 15:08:12 +0000818
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000819 /// AF - A factory for ArgEffects objects.
Mike Stump11289f42009-09-09 15:08:12 +0000820 ArgEffects::Factory AF;
821
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000822 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000823 ArgEffects ScratchArgs;
Mike Stump11289f42009-09-09 15:08:12 +0000824
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000825 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
826 /// objects.
827 RetEffect ObjCAllocRetE;
Ted Kremeneka03705c2009-06-05 23:18:01 +0000828
Mike Stump11289f42009-09-09 15:08:12 +0000829 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenek815fbb62009-08-20 05:13:36 +0000830 /// Objective-C objects.
Ted Kremeneka03705c2009-06-05 23:18:01 +0000831 RetEffect ObjCInitRetE;
Mike Stump11289f42009-09-09 15:08:12 +0000832
Ted Kremenekff606a12009-05-04 04:57:00 +0000833 RetainSummary DefaultSummary;
Ted Kremenek10427bd2008-05-06 18:11:36 +0000834 RetainSummary* StopSummary;
Mike Stump11289f42009-09-09 15:08:12 +0000835
Ted Kremenek00daccd2008-05-05 22:11:16 +0000836 //==-----------------------------------------------------------------==//
837 // Methods.
838 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000839
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000840 /// getArgEffects - Returns a persistent ArgEffects object based on the
841 /// data in ScratchArgs.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000842 ArgEffects getArgEffects();
Ted Kremenek819e9b62008-03-11 06:39:11 +0000843
Mike Stump11289f42009-09-09 15:08:12 +0000844 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
845
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000846public:
Ted Kremenek1272f702009-05-12 20:06:54 +0000847 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
848
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000849 RetainSummary *getDefaultSummary() {
850 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
851 return new (Summ) RetainSummary(DefaultSummary);
852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Ted Kremenek82157a12009-02-23 16:51:39 +0000854 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Mike Stump11289f42009-09-09 15:08:12 +0000855
Ted Kremenek00daccd2008-05-05 22:11:16 +0000856 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
Mike Stump11289f42009-09-09 15:08:12 +0000857 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek7e904222009-01-12 21:45:02 +0000858 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Mike Stump11289f42009-09-09 15:08:12 +0000859
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000860 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000861 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000862 ArgEffect DefaultEff = MayEscape,
863 bool isEndPath = false);
Ted Kremenek3700b762008-10-29 04:07:07 +0000864
Ted Kremenekb0862dc2008-05-06 02:26:56 +0000865 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000866 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek1df2f3a2008-05-22 17:31:13 +0000867 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000868 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0806f912008-05-06 00:30:21 +0000869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
Ted Kremenek0b50fb12009-04-29 05:04:30 +0000871 RetainSummary *getPersistentStopSummary() {
Ted Kremenek10427bd2008-05-06 18:11:36 +0000872 if (StopSummary)
873 return StopSummary;
Mike Stump11289f42009-09-09 15:08:12 +0000874
Ted Kremenek10427bd2008-05-06 18:11:36 +0000875 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
876 StopTracking, StopTracking);
Ted Kremenek3700b762008-10-29 04:07:07 +0000877
Ted Kremenek10427bd2008-05-06 18:11:36 +0000878 return StopSummary;
Mike Stump11289f42009-09-09 15:08:12 +0000879 }
Ted Kremenek015c3562008-05-06 04:20:12 +0000880
Ted Kremenek0b50fb12009-04-29 05:04:30 +0000881 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek3d1e9722008-05-05 23:55:01 +0000882
Ted Kremenekea736c52008-06-23 22:21:20 +0000883 void InitializeClassMethodSummaries();
884 void InitializeMethodSummaries();
Mike Stump11289f42009-09-09 15:08:12 +0000885
Ted Kremenekb4cf4a52009-05-03 04:42:10 +0000886 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek4b59ccb2009-05-03 06:08:32 +0000887 bool isTrackedCFObjectType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000888
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000889private:
Mike Stump11289f42009-09-09 15:08:12 +0000890
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000891 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
892 RetainSummary* Summ) {
893 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
894 }
Mike Stump11289f42009-09-09 15:08:12 +0000895
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000896 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
897 ObjCClassMethodSummaries[S] = Summ;
898 }
Mike Stump11289f42009-09-09 15:08:12 +0000899
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000900 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
901 ObjCMethodSummaries[S] = Summ;
902 }
Ted Kremenek00dfe302009-03-04 23:30:42 +0000903
904 void addClassMethSummary(const char* Cls, const char* nullaryName,
905 RetainSummary *Summ) {
906 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
907 Selector S = GetNullarySelector(nullaryName, Ctx);
908 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
909 }
Mike Stump11289f42009-09-09 15:08:12 +0000910
Ted Kremenekdce78462009-02-25 02:54:57 +0000911 void addInstMethSummary(const char* Cls, const char* nullaryName,
912 RetainSummary *Summ) {
913 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
914 Selector S = GetNullarySelector(nullaryName, Ctx);
915 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
916 }
Mike Stump11289f42009-09-09 15:08:12 +0000917
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000918 Selector generateSelector(va_list argp) {
Ted Kremenek050b91c2008-08-12 18:30:56 +0000919 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000920
Ted Kremenek050b91c2008-08-12 18:30:56 +0000921 while (const char* s = va_arg(argp, const char*))
922 II.push_back(&Ctx.Idents.get(s));
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000923
Mike Stump11289f42009-09-09 15:08:12 +0000924 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000925 }
Mike Stump11289f42009-09-09 15:08:12 +0000926
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000927 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
928 RetainSummary* Summ, va_list argp) {
929 Selector S = generateSelector(argp);
930 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000931 }
Mike Stump11289f42009-09-09 15:08:12 +0000932
Ted Kremenek3f13f592008-08-12 18:48:50 +0000933 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
934 va_list argp;
935 va_start(argp, Summ);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000936 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump11289f42009-09-09 15:08:12 +0000937 va_end(argp);
Ted Kremenek3f13f592008-08-12 18:48:50 +0000938 }
Mike Stump11289f42009-09-09 15:08:12 +0000939
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000940 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
941 va_list argp;
942 va_start(argp, Summ);
943 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
944 va_end(argp);
945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000947 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
948 va_list argp;
949 va_start(argp, Summ);
950 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
951 va_end(argp);
952 }
953
Ted Kremenek050b91c2008-08-12 18:30:56 +0000954 void addPanicSummary(const char* Cls, ...) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000955 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
956 RetEffect::MakeNoRet(),
Ted Kremenek050b91c2008-08-12 18:30:56 +0000957 DoNothing, DoNothing, true);
958 va_list argp;
959 va_start (argp, Cls);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000960 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek050b91c2008-08-12 18:30:56 +0000961 va_end(argp);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000962 }
Mike Stump11289f42009-09-09 15:08:12 +0000963
Ted Kremenek819e9b62008-03-11 06:39:11 +0000964public:
Mike Stump11289f42009-09-09 15:08:12 +0000965
Ted Kremenek00daccd2008-05-05 22:11:16 +0000966 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenekab54e512008-07-01 17:21:27 +0000967 : Ctx(ctx),
Ted Kremenekae529272008-07-09 18:11:16 +0000968 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000969 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000970 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
971 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenekea675cf2009-06-11 18:17:24 +0000972 ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned()
973 : RetEffect::MakeOwnedWhenTrackedReceiver()),
Ted Kremenekff606a12009-05-04 04:57:00 +0000974 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
975 RetEffect::MakeNoRet() /* return effect */,
Ted Kremenekd0e3ab22009-05-11 18:30:24 +0000976 MayEscape, /* default argument effect */
977 DoNothing /* receiver effect */),
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000978 StopSummary(0) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000979
980 InitializeClassMethodSummaries();
981 InitializeMethodSummaries();
982 }
Mike Stump11289f42009-09-09 15:08:12 +0000983
Ted Kremenek00daccd2008-05-05 22:11:16 +0000984 ~RetainSummaryManager();
Mike Stump11289f42009-09-09 15:08:12 +0000985
986 RetainSummary* getSummary(FunctionDecl* FD);
987
Ted Kremeneka2968e52009-11-13 01:54:21 +0000988 RetainSummary *getInstanceMethodSummary(const ObjCMessageExpr *ME,
989 const GRState *state,
990 const LocationContext *LC);
991
992 RetainSummary* getInstanceMethodSummary(const ObjCMessageExpr* ME,
Ted Kremenek223a7d52009-04-29 23:03:22 +0000993 const ObjCInterfaceDecl* ID) {
Ted Kremenek38724302009-04-29 17:09:14 +0000994 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Mike Stump11289f42009-09-09 15:08:12 +0000995 ID, ME->getMethodDecl(), ME->getType());
Ted Kremenek0b50fb12009-04-29 05:04:30 +0000996 }
Mike Stump11289f42009-09-09 15:08:12 +0000997
Ted Kremenek38724302009-04-29 17:09:14 +0000998 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +0000999 const ObjCInterfaceDecl* ID,
1000 const ObjCMethodDecl *MD,
1001 QualType RetTy);
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001002
1003 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +00001004 const ObjCInterfaceDecl *ID,
1005 const ObjCMethodDecl *MD,
1006 QualType RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001007
Ted Kremeneka2968e52009-11-13 01:54:21 +00001008 RetainSummary *getClassMethodSummary(const ObjCMessageExpr *ME) {
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001009 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
1010 ME->getClassInfo().first,
1011 ME->getMethodDecl(), ME->getType());
1012 }
Ted Kremenek99fe1692009-04-29 17:17:48 +00001013
1014 /// getMethodSummary - This version of getMethodSummary is used to query
1015 /// the summary for the current method being analyzed.
Ted Kremenek223a7d52009-04-29 23:03:22 +00001016 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
1017 // FIXME: Eventually this should be unneeded.
Ted Kremenek223a7d52009-04-29 23:03:22 +00001018 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenekb2a143f2009-04-30 05:41:14 +00001019 Selector S = MD->getSelector();
Ted Kremenek99fe1692009-04-29 17:17:48 +00001020 IdentifierInfo *ClsName = ID->getIdentifier();
1021 QualType ResultTy = MD->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001022
1023 // Resolve the method decl last.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001024 if (const ObjCMethodDecl *InterfaceMD = ResolveToInterfaceMethodDecl(MD))
Ted Kremenek497df912009-04-30 05:47:23 +00001025 MD = InterfaceMD;
Mike Stump11289f42009-09-09 15:08:12 +00001026
Ted Kremenek99fe1692009-04-29 17:17:48 +00001027 if (MD->isInstanceMethod())
1028 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
1029 else
1030 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
1031 }
Mike Stump11289f42009-09-09 15:08:12 +00001032
Ted Kremenek223a7d52009-04-29 23:03:22 +00001033 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
1034 Selector S, QualType RetTy);
1035
Ted Kremenekc2de7272009-05-09 02:58:13 +00001036 void updateSummaryFromAnnotations(RetainSummary &Summ,
1037 const ObjCMethodDecl *MD);
1038
1039 void updateSummaryFromAnnotations(RetainSummary &Summ,
1040 const FunctionDecl *FD);
1041
Ted Kremenek00daccd2008-05-05 22:11:16 +00001042 bool isGCEnabled() const { return GCEnabled; }
Mike Stump11289f42009-09-09 15:08:12 +00001043
Ted Kremenek1d9a2672009-05-04 05:31:22 +00001044 RetainSummary *copySummary(RetainSummary *OldSumm) {
1045 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
1046 new (Summ) RetainSummary(*OldSumm);
1047 return Summ;
Mike Stump11289f42009-09-09 15:08:12 +00001048 }
Ted Kremenek819e9b62008-03-11 06:39:11 +00001049};
Mike Stump11289f42009-09-09 15:08:12 +00001050
Ted Kremenek819e9b62008-03-11 06:39:11 +00001051} // end anonymous namespace
1052
1053//===----------------------------------------------------------------------===//
1054// Implementation of checker data structures.
1055//===----------------------------------------------------------------------===//
1056
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001057RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek819e9b62008-03-11 06:39:11 +00001058
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001059ArgEffects RetainSummaryManager::getArgEffects() {
1060 ArgEffects AE = ScratchArgs;
1061 ScratchArgs = AF.GetEmptyMap();
1062 return AE;
Ted Kremenek68d73d12008-03-12 01:21:45 +00001063}
1064
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001065RetainSummary*
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001066RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001067 ArgEffect ReceiverEff,
Ted Kremenek3b2294c2008-07-18 17:24:20 +00001068 ArgEffect DefaultEff,
Mike Stump11289f42009-09-09 15:08:12 +00001069 bool isEndPath) {
Ted Kremenekf7141592008-04-24 17:22:33 +00001070 // Create the summary and return it.
Ted Kremenek1bff64e2009-05-04 04:30:18 +00001071 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek3b2294c2008-07-18 17:24:20 +00001072 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001073 return Summ;
1074}
1075
Ted Kremenek00daccd2008-05-05 22:11:16 +00001076//===----------------------------------------------------------------------===//
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001077// Predicates.
1078//===----------------------------------------------------------------------===//
1079
Ted Kremenekb4cf4a52009-05-03 04:42:10 +00001080bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Steve Naroff79d12152009-07-16 15:41:00 +00001081 if (!Ty->isObjCObjectPointerType())
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001082 return false;
1083
John McCall9dd450b2009-09-21 23:43:11 +00001084 const ObjCObjectPointerType *PT = Ty->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001085
Steve Naroff7cae42b2009-07-10 23:34:53 +00001086 // Can be true for objects with the 'NSObject' attribute.
1087 if (!PT)
Ted Kremenek37467812009-04-23 22:11:07 +00001088 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001089
Steve Naroff7cae42b2009-07-10 23:34:53 +00001090 // We assume that id<..>, id, and "Class" all represent tracked objects.
1091 if (PT->isObjCIdType() || PT->isObjCQualifiedIdType() ||
1092 PT->isObjCClassType())
1093 return true;
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001094
Mike Stump11289f42009-09-09 15:08:12 +00001095 // Does the interface subclass NSObject?
1096 // FIXME: We can memoize here if this gets too expensive.
1097 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001098
Ted Kremeneke4302ee2009-05-16 01:38:01 +00001099 // Assume that anything declared with a forward declaration and no
1100 // @interface subclasses NSObject.
1101 if (ID->isForwardDecl())
1102 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001103
Ted Kremeneke4302ee2009-05-16 01:38:01 +00001104 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
1105
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001106 for ( ; ID ; ID = ID->getSuperClass())
1107 if (ID->getIdentifier() == NSObjectII)
1108 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001109
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001110 return false;
1111}
1112
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001113bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
1114 return isRefType(T, "CF") || // Core Foundation.
1115 isRefType(T, "CG") || // Core Graphics.
1116 isRefType(T, "DADisk") || // Disk Arbitration API.
1117 isRefType(T, "DADissenter") ||
1118 isRefType(T, "DASessionRef");
1119}
1120
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001121//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001122// Summary creation for functions (largely uses of Core Foundation).
1123//===----------------------------------------------------------------------===//
Ted Kremenek68d73d12008-03-12 01:21:45 +00001124
Ted Kremenek7e904222009-01-12 21:45:02 +00001125static bool isRetain(FunctionDecl* FD, const char* FName) {
1126 const char* loc = strstr(FName, "Retain");
1127 return loc && loc[sizeof("Retain")-1] == '\0';
1128}
1129
1130static bool isRelease(FunctionDecl* FD, const char* FName) {
1131 const char* loc = strstr(FName, "Release");
1132 return loc && loc[sizeof("Release")-1] == '\0';
1133}
1134
Ted Kremenekf890bfe2008-06-24 03:56:45 +00001135RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekf7141592008-04-24 17:22:33 +00001136 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenek00daccd2008-05-05 22:11:16 +00001137 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek00daccd2008-05-05 22:11:16 +00001138 if (I != FuncSummaries.end())
Ted Kremenekf7141592008-04-24 17:22:33 +00001139 return I->second;
1140
Ted Kremenekdf76e6d2009-05-04 15:34:07 +00001141 // No summary? Generate one.
Ted Kremenek7e904222009-01-12 21:45:02 +00001142 RetainSummary *S = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001143
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001144 do {
Ted Kremenek7e904222009-01-12 21:45:02 +00001145 // We generate "stop" summaries for implicitly defined functions.
1146 if (FD->isImplicit()) {
1147 S = getPersistentStopSummary();
1148 break;
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001149 }
Mike Stump11289f42009-09-09 15:08:12 +00001150
John McCall9dd450b2009-09-21 23:43:11 +00001151 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek86afde32009-01-16 18:40:33 +00001152 // function's type.
John McCall9dd450b2009-09-21 23:43:11 +00001153 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001154 const char* FName = FD->getIdentifier()->getNameStart();
Mike Stump11289f42009-09-09 15:08:12 +00001155
Ted Kremenek5f968932009-03-05 22:11:14 +00001156 // Strip away preceding '_'. Doing this here will effect all the checks
1157 // down below.
1158 while (*FName == '_') ++FName;
Mike Stump11289f42009-09-09 15:08:12 +00001159
Ted Kremenek7e904222009-01-12 21:45:02 +00001160 // Inspect the result type.
1161 QualType RetTy = FT->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001162
Ted Kremenek7e904222009-01-12 21:45:02 +00001163 // FIXME: This should all be refactored into a chain of "summary lookup"
1164 // filters.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001165 assert(ScratchArgs.isEmpty());
1166
Ted Kremenekea675cf2009-06-11 18:17:24 +00001167 switch (strlen(FName)) {
1168 default: break;
Ted Kremenek80816ac2009-10-13 22:55:33 +00001169 case 14:
1170 if (!memcmp(FName, "pthread_create", 14)) {
1171 // Part of: <rdar://problem/7299394>. This will be addressed
1172 // better with IPA.
1173 S = getPersistentStopSummary();
1174 }
1175 break;
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001176
Ted Kremenekea675cf2009-06-11 18:17:24 +00001177 case 17:
1178 // Handle: id NSMakeCollectable(CFTypeRef)
1179 if (!memcmp(FName, "NSMakeCollectable", 17)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001180 S = (RetTy->isObjCIdType())
Ted Kremenekea675cf2009-06-11 18:17:24 +00001181 ? getUnarySummary(FT, cfmakecollectable)
1182 : getPersistentStopSummary();
1183 }
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001184 else if (!memcmp(FName, "IOBSDNameMatching", 17) ||
1185 !memcmp(FName, "IOServiceMatching", 17)) {
1186 // Part of <rdar://problem/6961230>. (IOKit)
1187 // This should be addressed using a API table.
1188 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1189 DoNothing, DoNothing);
1190 }
Ted Kremenekea675cf2009-06-11 18:17:24 +00001191 break;
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001192
1193 case 21:
1194 if (!memcmp(FName, "IOServiceNameMatching", 21)) {
1195 // Part of <rdar://problem/6961230>. (IOKit)
1196 // This should be addressed using a API table.
1197 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1198 DoNothing, DoNothing);
1199 }
1200 break;
1201
1202 case 24:
1203 if (!memcmp(FName, "IOServiceAddNotification", 24)) {
1204 // Part of <rdar://problem/6961230>. (IOKit)
1205 // This should be addressed using a API table.
1206 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
Ted Kremenek55adb822009-10-15 22:25:12 +00001207 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,DoNothing);
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001208 }
1209 break;
Mike Stump11289f42009-09-09 15:08:12 +00001210
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001211 case 25:
1212 if (!memcmp(FName, "IORegistryEntryIDMatching", 25)) {
1213 // Part of <rdar://problem/6961230>. (IOKit)
1214 // This should be addressed using a API table.
1215 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1216 DoNothing, DoNothing);
1217 }
1218 break;
Mike Stump11289f42009-09-09 15:08:12 +00001219
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001220 case 26:
1221 if (!memcmp(FName, "IOOpenFirmwarePathMatching", 26)) {
1222 // Part of <rdar://problem/6961230>. (IOKit)
1223 // This should be addressed using a API table.
1224 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
Mike Stump11289f42009-09-09 15:08:12 +00001225 DoNothing, DoNothing);
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001226 }
1227 break;
1228
Ted Kremenekea675cf2009-06-11 18:17:24 +00001229 case 27:
1230 if (!memcmp(FName, "IOServiceGetMatchingService", 27)) {
1231 // Part of <rdar://problem/6961230>.
1232 // This should be addressed using a API table.
Ted Kremenekea675cf2009-06-11 18:17:24 +00001233 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Mike Stump11289f42009-09-09 15:08:12 +00001234 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001235 }
1236 break;
1237
1238 case 28:
1239 if (!memcmp(FName, "IOServiceGetMatchingServices", 28)) {
1240 // FIXES: <rdar://problem/6326900>
1241 // This should be addressed using a API table. This strcmp is also
1242 // a little gross, but there is no need to super optimize here.
Ted Kremenekea675cf2009-06-11 18:17:24 +00001243 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001244 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1245 DoNothing);
1246 }
1247 else if (!memcmp(FName, "CVPixelBufferCreateWithBytes", 28)) {
1248 // FIXES: <rdar://problem/7283567>
1249 // Eventually this can be improved by recognizing that the pixel
1250 // buffer passed to CVPixelBufferCreateWithBytes is released via
1251 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek43edaa82009-11-03 05:39:12 +00001252 // FIXME: This function has an out parameter that returns an
1253 // allocated object.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001254 ScratchArgs = AF.Add(ScratchArgs, 7, StopTracking);
1255 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1256 DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001257 }
1258 break;
Ted Kremenekd1b67db2009-11-03 05:34:07 +00001259
1260 case 29:
1261 if (!memcmp(FName, "CGBitmapContextCreateWithData", 29)) {
1262 // FIXES: <rdar://problem/7358899>
1263 // Eventually this can be improved by recognizing that 'releaseInfo'
1264 // passed to CGBitmapContextCreateWithData is released via
1265 // a callback and doing full IPA to make sure this is done correctly.
1266 ScratchArgs = AF.Add(ScratchArgs, 8, StopTracking);
Ted Kremenek43edaa82009-11-03 05:39:12 +00001267 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1268 DoNothing,DoNothing);
Ted Kremenekd1b67db2009-11-03 05:34:07 +00001269 }
1270 break;
Mike Stump11289f42009-09-09 15:08:12 +00001271
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001272 case 32:
1273 if (!memcmp(FName, "IOServiceAddMatchingNotification", 32)) {
1274 // Part of <rdar://problem/6961230>.
1275 // This should be addressed using a API table.
1276 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
Mike Stump11289f42009-09-09 15:08:12 +00001277 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001278 }
1279 break;
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001280
1281 case 34:
1282 if (!memcmp(FName, "CVPixelBufferCreateWithPlanarBytes", 34)) {
1283 // FIXES: <rdar://problem/7283567>
1284 // Eventually this can be improved by recognizing that the pixel
1285 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1286 // via a callback and doing full IPA to make sure this is done
1287 // correctly.
1288 ScratchArgs = AF.Add(ScratchArgs, 12, StopTracking);
1289 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1290 DoNothing);
1291 }
1292 break;
Ted Kremenekea675cf2009-06-11 18:17:24 +00001293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Ted Kremenekea675cf2009-06-11 18:17:24 +00001295 // Did we get a summary?
1296 if (S)
1297 break;
Ted Kremenek211094d2009-03-17 22:43:44 +00001298
1299 // Enable this code once the semantics of NSDeallocateObject are resolved
1300 // for GC. <rdar://problem/6619988>
1301#if 0
1302 // Handle: NSDeallocateObject(id anObject);
1303 // This method does allow 'nil' (although we don't check it now).
Mike Stump11289f42009-09-09 15:08:12 +00001304 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek211094d2009-03-17 22:43:44 +00001305 return RetTy == Ctx.VoidTy
1306 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1307 : getPersistentStopSummary();
1308 }
1309#endif
Ted Kremenek7e904222009-01-12 21:45:02 +00001310
1311 if (RetTy->isPointerType()) {
1312 // For CoreFoundation ('CF') types.
1313 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1314 if (isRetain(FD, FName))
1315 S = getUnarySummary(FT, cfretain);
1316 else if (strstr(FName, "MakeCollectable"))
1317 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump11289f42009-09-09 15:08:12 +00001318 else
Ted Kremenek7e904222009-01-12 21:45:02 +00001319 S = getCFCreateGetRuleSummary(FD, FName);
1320
1321 break;
1322 }
1323
1324 // For CoreGraphics ('CG') types.
1325 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1326 if (isRetain(FD, FName))
1327 S = getUnarySummary(FT, cfretain);
1328 else
1329 S = getCFCreateGetRuleSummary(FD, FName);
1330
1331 break;
1332 }
1333
1334 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1335 if (isRefType(RetTy, "DADisk") ||
1336 isRefType(RetTy, "DADissenter") ||
1337 isRefType(RetTy, "DASessionRef")) {
1338 S = getCFCreateGetRuleSummary(FD, FName);
1339 break;
1340 }
Mike Stump11289f42009-09-09 15:08:12 +00001341
Ted Kremenek7e904222009-01-12 21:45:02 +00001342 break;
1343 }
1344
1345 // Check for release functions, the only kind of functions that we care
1346 // about that don't return a pointer type.
1347 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek5f968932009-03-05 22:11:14 +00001348 // Test for 'CGCF'.
1349 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1350 FName += 4;
1351 else
1352 FName += 2;
Mike Stump11289f42009-09-09 15:08:12 +00001353
Ted Kremenek5f968932009-03-05 22:11:14 +00001354 if (isRelease(FD, FName))
Ted Kremenek7e904222009-01-12 21:45:02 +00001355 S = getUnarySummary(FT, cfrelease);
1356 else {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001357 assert (ScratchArgs.isEmpty());
Ted Kremeneked90de42009-01-29 22:45:13 +00001358 // Remaining CoreFoundation and CoreGraphics functions.
1359 // We use to assume that they all strictly followed the ownership idiom
1360 // and that ownership cannot be transferred. While this is technically
1361 // correct, many methods allow a tracked object to escape. For example:
1362 //
Mike Stump11289f42009-09-09 15:08:12 +00001363 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremeneked90de42009-01-29 22:45:13 +00001364 // CFDictionaryAddValue(y, key, x);
Mike Stump11289f42009-09-09 15:08:12 +00001365 // CFRelease(x);
Ted Kremeneked90de42009-01-29 22:45:13 +00001366 // ... it is okay to use 'x' since 'y' has a reference to it
1367 //
1368 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekd982f002009-08-20 00:57:22 +00001369 // function name contains "InsertValue", "SetValue", "AddValue",
1370 // "AppendValue", or "SetAttribute", then we assume that arguments may
1371 // "escape." This means that something else holds on to the object,
1372 // allowing it be used even after its local retain count drops to 0.
Ted Kremeneked90de42009-01-29 22:45:13 +00001373 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1374 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenek0ca23d32009-02-05 22:34:53 +00001375 CStrInCStrNoCase(FName, "SetValue") ||
Ted Kremenekd982f002009-08-20 00:57:22 +00001376 CStrInCStrNoCase(FName, "AppendValue") ||
1377 CStrInCStrNoCase(FName, "SetAttribute"))
Ted Kremeneked90de42009-01-29 22:45:13 +00001378 ? MayEscape : DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001379
Ted Kremeneked90de42009-01-29 22:45:13 +00001380 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek7e904222009-01-12 21:45:02 +00001381 }
1382 }
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001383 }
1384 while (0);
Mike Stump11289f42009-09-09 15:08:12 +00001385
Ted Kremenek1d9a2672009-05-04 05:31:22 +00001386 if (!S)
1387 S = getDefaultSummary();
Ted Kremenekf7141592008-04-24 17:22:33 +00001388
Ted Kremenekc2de7272009-05-09 02:58:13 +00001389 // Annotations override defaults.
1390 assert(S);
1391 updateSummaryFromAnnotations(*S, FD);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Ted Kremenek00daccd2008-05-05 22:11:16 +00001393 FuncSummaries[FD] = S;
Mike Stump11289f42009-09-09 15:08:12 +00001394 return S;
Ted Kremenekea6507f2008-03-06 00:08:09 +00001395}
1396
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001397RetainSummary*
1398RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1399 const char* FName) {
Mike Stump11289f42009-09-09 15:08:12 +00001400
Ted Kremenek875db812008-05-05 16:51:50 +00001401 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1402 return getCFSummaryCreateRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001403
Ted Kremenek875db812008-05-05 16:51:50 +00001404 if (strstr(FName, "Get"))
1405 return getCFSummaryGetRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001406
Ted Kremenekff606a12009-05-04 04:57:00 +00001407 return getDefaultSummary();
Ted Kremenek875db812008-05-05 16:51:50 +00001408}
1409
Ted Kremenek00daccd2008-05-05 22:11:16 +00001410RetainSummary*
Ted Kremenek82157a12009-02-23 16:51:39 +00001411RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1412 UnaryFuncKind func) {
1413
Ted Kremenek7e904222009-01-12 21:45:02 +00001414 // Sanity check that this is *really* a unary function. This can
1415 // happen if people do weird things.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001416 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek7e904222009-01-12 21:45:02 +00001417 if (!FTP || FTP->getNumArgs() != 1)
1418 return getPersistentStopSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001419
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001420 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001421
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001422 switch (func) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001423 case cfretain: {
1424 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00001425 return getPersistentSummary(RetEffect::MakeAlias(0),
1426 DoNothing, DoNothing);
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001427 }
Mike Stump11289f42009-09-09 15:08:12 +00001428
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001429 case cfrelease: {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001430 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00001431 return getPersistentSummary(RetEffect::MakeNoRet(),
1432 DoNothing, DoNothing);
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001433 }
Mike Stump11289f42009-09-09 15:08:12 +00001434
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001435 case cfmakecollectable: {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001436 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Mike Stump11289f42009-09-09 15:08:12 +00001437 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001438 }
Mike Stump11289f42009-09-09 15:08:12 +00001439
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001440 default:
Ted Kremenek875db812008-05-05 16:51:50 +00001441 assert (false && "Not a supported unary function.");
Ted Kremenekff606a12009-05-04 04:57:00 +00001442 return getDefaultSummary();
Ted Kremenek4b772092008-04-10 23:44:06 +00001443 }
Ted Kremenek68d73d12008-03-12 01:21:45 +00001444}
1445
Ted Kremenek00daccd2008-05-05 22:11:16 +00001446RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001447 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001448
Ted Kremenekae529272008-07-09 18:11:16 +00001449 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001450 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1451 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekae529272008-07-09 18:11:16 +00001452 }
Mike Stump11289f42009-09-09 15:08:12 +00001453
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001454 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek68d73d12008-03-12 01:21:45 +00001455}
1456
Ted Kremenek00daccd2008-05-05 22:11:16 +00001457RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Mike Stump11289f42009-09-09 15:08:12 +00001458 assert (ScratchArgs.isEmpty());
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001459 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1460 DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001461}
1462
Ted Kremenek819e9b62008-03-11 06:39:11 +00001463//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001464// Summary creation for Selectors.
1465//===----------------------------------------------------------------------===//
1466
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001467RetainSummary*
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001468RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Mike Stump11289f42009-09-09 15:08:12 +00001469 assert(ScratchArgs.isEmpty());
Ted Kremenek1272f702009-05-12 20:06:54 +00001470 // 'init' methods conceptually return a newly allocated object and claim
Mike Stump11289f42009-09-09 15:08:12 +00001471 // the receiver.
Ted Kremenek1272f702009-05-12 20:06:54 +00001472 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
Ted Kremeneka03705c2009-06-05 23:18:01 +00001473 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
Mike Stump11289f42009-09-09 15:08:12 +00001474
Ted Kremenek1272f702009-05-12 20:06:54 +00001475 return getDefaultSummary();
Ted Kremenek3d1e9722008-05-05 23:55:01 +00001476}
Ted Kremenekc2de7272009-05-09 02:58:13 +00001477
1478void
1479RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1480 const FunctionDecl *FD) {
1481 if (!FD)
1482 return;
1483
Ted Kremenekea675cf2009-06-11 18:17:24 +00001484 QualType RetTy = FD->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001485
Ted Kremenekc2de7272009-05-09 02:58:13 +00001486 // Determine if there is a special return effect for this method.
Ted Kremenekea1c2212009-06-05 23:00:33 +00001487 if (isTrackedObjCObjectType(RetTy)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001488 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001489 Summ.setRetEffect(ObjCAllocRetE);
1490 }
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001491 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenekea1c2212009-06-05 23:00:33 +00001492 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekea675cf2009-06-11 18:17:24 +00001493 }
1494 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001495 else if (RetTy->getAs<PointerType>()) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001496 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001497 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1498 }
1499 }
1500}
1501
1502void
1503RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1504 const ObjCMethodDecl *MD) {
1505 if (!MD)
1506 return;
1507
Ted Kremenek0578e432009-07-06 18:30:43 +00001508 bool isTrackedLoc = false;
Mike Stump11289f42009-09-09 15:08:12 +00001509
Ted Kremenekc2de7272009-05-09 02:58:13 +00001510 // Determine if there is a special return effect for this method.
1511 if (isTrackedObjCObjectType(MD->getResultType())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001512 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001513 Summ.setRetEffect(ObjCAllocRetE);
Ted Kremenek0578e432009-07-06 18:30:43 +00001514 return;
Ted Kremenekc2de7272009-05-09 02:58:13 +00001515 }
Mike Stump11289f42009-09-09 15:08:12 +00001516
Ted Kremenek0578e432009-07-06 18:30:43 +00001517 isTrackedLoc = true;
Ted Kremenekc2de7272009-05-09 02:58:13 +00001518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Ted Kremenek0578e432009-07-06 18:30:43 +00001520 if (!isTrackedLoc)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001521 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001522
Ted Kremenek0578e432009-07-06 18:30:43 +00001523 if (isTrackedLoc && MD->getAttr<CFReturnsRetainedAttr>())
1524 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekc2de7272009-05-09 02:58:13 +00001525}
1526
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001527RetainSummary*
Ted Kremenek223a7d52009-04-29 23:03:22 +00001528RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1529 Selector S, QualType RetTy) {
Ted Kremenek6a966b22009-04-24 21:56:17 +00001530
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001531 if (MD) {
Ted Kremenek6e86caf2009-04-24 18:00:17 +00001532 // Scan the method decl for 'void*' arguments. These should be treated
1533 // as 'StopTracking' because they are often used with delegates.
1534 // Delegates are a frequent form of false positives with the retain
1535 // count checker.
1536 unsigned i = 0;
1537 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1538 E = MD->param_end(); I != E; ++I, ++i)
1539 if (ParmVarDecl *PD = *I) {
1540 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001541 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001542 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek6e86caf2009-04-24 18:00:17 +00001543 }
1544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
Ted Kremenek6a966b22009-04-24 21:56:17 +00001546 // Any special effect for the receiver?
1547 ArgEffect ReceiverEff = DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001548
Ted Kremenek6a966b22009-04-24 21:56:17 +00001549 // If one of the arguments in the selector has the keyword 'delegate' we
1550 // should stop tracking the reference count for the receiver. This is
1551 // because the reference count is quite possibly handled by a delegate
1552 // method.
1553 if (S.isKeywordSelector()) {
1554 const std::string &str = S.getAsString();
1555 assert(!str.empty());
1556 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1557 }
Mike Stump11289f42009-09-09 15:08:12 +00001558
Ted Kremenek60746a02009-04-23 23:08:22 +00001559 // Look for methods that return an owned object.
Mike Stump11289f42009-09-09 15:08:12 +00001560 if (isTrackedObjCObjectType(RetTy)) {
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001561 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1562 // by instance methods.
Ted Kremenek32819772009-05-15 15:49:00 +00001563 RetEffect E = followsFundamentalRule(S)
1564 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Mike Stump11289f42009-09-09 15:08:12 +00001565
1566 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek6e86caf2009-04-24 18:00:17 +00001567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001569 // Look for methods that return an owned core foundation object.
1570 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek32819772009-05-15 15:49:00 +00001571 RetEffect E = followsFundamentalRule(S)
1572 ? RetEffect::MakeOwned(RetEffect::CF, true)
1573 : RetEffect::MakeNotOwned(RetEffect::CF);
Mike Stump11289f42009-09-09 15:08:12 +00001574
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001575 return getPersistentSummary(E, ReceiverEff, MayEscape);
1576 }
Mike Stump11289f42009-09-09 15:08:12 +00001577
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001578 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenekff606a12009-05-04 04:57:00 +00001579 return getDefaultSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001580
Ted Kremenek1d9a2672009-05-04 05:31:22 +00001581 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek60746a02009-04-23 23:08:22 +00001582}
1583
1584RetainSummary*
Ted Kremeneka2968e52009-11-13 01:54:21 +00001585RetainSummaryManager::getInstanceMethodSummary(const ObjCMessageExpr *ME,
1586 const GRState *state,
1587 const LocationContext *LC) {
1588
1589 // We need the type-information of the tracked receiver object
1590 // Retrieve it from the state.
1591 const Expr *Receiver = ME->getReceiver();
1592 const ObjCInterfaceDecl* ID = 0;
1593
1594 // FIXME: Is this really working as expected? There are cases where
1595 // we just use the 'ID' from the message expression.
1596 SVal receiverV = state->getSValAsScalarOrLoc(Receiver);
1597
1598 // FIXME: Eventually replace the use of state->get<RefBindings> with
1599 // a generic API for reasoning about the Objective-C types of symbolic
1600 // objects.
1601 if (SymbolRef Sym = receiverV.getAsLocSymbol())
1602 if (const RefVal *T = state->get<RefBindings>(Sym))
1603 if (const ObjCObjectPointerType* PT =
1604 T->getType()->getAs<ObjCObjectPointerType>())
1605 ID = PT->getInterfaceDecl();
1606
1607 // FIXME: this is a hack. This may or may not be the actual method
1608 // that is called.
1609 if (!ID) {
1610 if (const ObjCObjectPointerType *PT =
1611 Receiver->getType()->getAs<ObjCObjectPointerType>())
1612 ID = PT->getInterfaceDecl();
1613 }
1614
1615 // FIXME: The receiver could be a reference to a class, meaning that
1616 // we should use the class method.
1617 RetainSummary *Summ = getInstanceMethodSummary(ME, ID);
1618
1619 // Special-case: are we sending a mesage to "self"?
1620 // This is a hack. When we have full-IP this should be removed.
1621 if (isa<ObjCMethodDecl>(LC->getDecl())) {
1622 if (const loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&receiverV)) {
1623 // Get the region associated with 'self'.
1624 if (const ImplicitParamDecl *SelfDecl = LC->getSelfDecl()) {
1625 SVal SelfVal = state->getSVal(state->getRegion(SelfDecl, LC));
1626 if (L->StripCasts() == SelfVal.getAsRegion()) {
1627 // Update the summary to make the default argument effect
1628 // 'StopTracking'.
1629 Summ = copySummary(Summ);
1630 Summ->setDefaultArgEffect(StopTracking);
1631 }
1632 }
1633 }
1634 }
1635
1636 return Summ ? Summ : getDefaultSummary();
1637}
1638
1639RetainSummary*
Ted Kremenek38724302009-04-29 17:09:14 +00001640RetainSummaryManager::getInstanceMethodSummary(Selector S,
1641 IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +00001642 const ObjCInterfaceDecl* ID,
1643 const ObjCMethodDecl *MD,
Ted Kremenek38724302009-04-29 17:09:14 +00001644 QualType RetTy) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001645
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001646 // Look up a summary in our summary cache.
Ted Kremenek8be51382009-07-21 23:27:57 +00001647 RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S);
Mike Stump11289f42009-09-09 15:08:12 +00001648
Ted Kremenek8be51382009-07-21 23:27:57 +00001649 if (!Summ) {
1650 assert(ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001651
Ted Kremenek8be51382009-07-21 23:27:57 +00001652 // "initXXX": pass-through for receiver.
1653 if (deriveNamingConvention(S) == InitRule)
1654 Summ = getInitMethodSummary(RetTy);
1655 else
1656 Summ = getCommonMethodSummary(MD, S, RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001657
Ted Kremenek8be51382009-07-21 23:27:57 +00001658 // Annotations override defaults.
1659 updateSummaryFromAnnotations(*Summ, MD);
Mike Stump11289f42009-09-09 15:08:12 +00001660
Ted Kremenek8be51382009-07-21 23:27:57 +00001661 // Memoize the summary.
1662 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1663 }
Mike Stump11289f42009-09-09 15:08:12 +00001664
Ted Kremenekf27110f2009-04-23 19:11:35 +00001665 return Summ;
Ted Kremenek3d1e9722008-05-05 23:55:01 +00001666}
1667
Ted Kremenek767d0742008-05-06 21:26:51 +00001668RetainSummary*
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001669RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +00001670 const ObjCInterfaceDecl *ID,
1671 const ObjCMethodDecl *MD,
1672 QualType RetTy) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +00001673
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001674 assert(ClsName && "Class name must be specified.");
Mike Stump11289f42009-09-09 15:08:12 +00001675 RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S);
1676
Ted Kremenek8be51382009-07-21 23:27:57 +00001677 if (!Summ) {
1678 Summ = getCommonMethodSummary(MD, S, RetTy);
1679 // Annotations override defaults.
1680 updateSummaryFromAnnotations(*Summ, MD);
1681 // Memoize the summary.
1682 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Ted Kremenekf27110f2009-04-23 19:11:35 +00001685 return Summ;
Ted Kremenek767d0742008-05-06 21:26:51 +00001686}
1687
Mike Stump11289f42009-09-09 15:08:12 +00001688void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001689 assert(ScratchArgs.isEmpty());
1690 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001692 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1693 // NSObject and its derivatives.
1694 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1695 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1696 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001697
1698 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek55adb822009-10-15 22:25:12 +00001699 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001700 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump11289f42009-09-09 15:08:12 +00001701
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001702 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001703 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek55adb822009-10-15 22:25:12 +00001704 addClassMethSummary("NSAutoreleasePool", "addObject",
1705 getPersistentSummary(RetEffect::MakeNoRet(),
1706 DoNothing, Autorelease));
Mike Stump11289f42009-09-09 15:08:12 +00001707
Ted Kremenek4e45d802009-10-15 22:26:21 +00001708 // Create a summary for [NSCursor dragCopyCursor].
1709 addClassMethSummary("NSCursor", "dragCopyCursor",
1710 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1711 DoNothing));
1712
Ted Kremenek8a5ad392009-04-24 17:50:11 +00001713 // Create the summaries for [NSObject performSelector...]. We treat
1714 // these as 'stop tracking' for the arguments because they are often
1715 // used for delegates that can release the object. When we have better
1716 // inter-procedural analysis we can potentially do something better. This
1717 // workaround is to remove false positives.
1718 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1719 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1720 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1721 "afterDelay", NULL);
1722 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1723 "afterDelay", "inModes", NULL);
1724 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1725 "withObject", "waitUntilDone", NULL);
1726 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1727 "withObject", "waitUntilDone", "modes", NULL);
1728 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1729 "withObject", "waitUntilDone", NULL);
1730 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1731 "withObject", "waitUntilDone", "modes", NULL);
1732 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1733 "withObject", NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001734
Ted Kremenekf9fa3cb2009-05-14 21:29:16 +00001735 // Specially handle NSData.
1736 RetainSummary *dataWithBytesNoCopySumm =
1737 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1738 DoNothing);
1739 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1740 "dataWithBytesNoCopy", "length", NULL);
1741 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1742 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0806f912008-05-06 00:30:21 +00001743}
1744
Ted Kremenekea736c52008-06-23 22:21:20 +00001745void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump11289f42009-09-09 15:08:12 +00001746
1747 assert (ScratchArgs.isEmpty());
1748
Ted Kremenek767d0742008-05-06 21:26:51 +00001749 // Create the "init" selector. It just acts as a pass-through for the
1750 // receiver.
Mike Stump11289f42009-09-09 15:08:12 +00001751 RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek815fbb62009-08-20 05:13:36 +00001752 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1753
1754 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1755 // claims the receiver and returns a retained object.
1756 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1757 InitSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001758
Ted Kremenek767d0742008-05-06 21:26:51 +00001759 // The next methods are allocators.
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001760 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Mike Stump11289f42009-09-09 15:08:12 +00001761 RetainSummary *CFAllocSumm =
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001762 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump11289f42009-09-09 15:08:12 +00001763
1764 // Create the "copy" selector.
1765 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek9551ab62008-08-12 20:41:56 +00001766
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001767 // Create the "mutableCopy" selector.
Ted Kremenek10369122009-05-20 22:39:57 +00001768 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001769
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001770 // Create the "retain" selector.
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001771 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek10369122009-05-20 22:39:57 +00001772 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001773 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001774
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001775 // Create the "release" selector.
Ted Kremenekf68490a2009-02-18 18:54:33 +00001776 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001777 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001778
Ted Kremenekbcdb4682008-05-07 21:17:39 +00001779 // Create the "drain" selector.
1780 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001781 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001782
Ted Kremenekea072e32009-03-17 19:42:23 +00001783 // Create the -dealloc summary.
1784 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1785 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001786
1787 // Create the "autorelease" selector.
Ted Kremenekc7832092009-01-28 21:44:40 +00001788 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001789 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001790
Ted Kremenek50db3d02009-02-23 17:45:03 +00001791 // Specially handle NSAutoreleasePool.
Ted Kremenekdce78462009-02-25 02:54:57 +00001792 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenek50db3d02009-02-23 17:45:03 +00001793 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenekdce78462009-02-25 02:54:57 +00001794 NewAutoreleasePool));
Mike Stump11289f42009-09-09 15:08:12 +00001795
1796 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke73f2822009-02-23 02:51:29 +00001797 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1798 // self-own themselves. However, they only do this once they are displayed.
1799 // Thus, we need to track an NSWindow's display status.
1800 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek00dfe302009-03-04 23:30:42 +00001801 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek1272f702009-05-12 20:06:54 +00001802 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1803 StopTracking,
1804 StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +00001805
Ted Kremenek751e7e32009-04-03 19:02:51 +00001806 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1807
Ted Kremenek00dfe302009-03-04 23:30:42 +00001808#if 0
Ted Kremenek1272f702009-05-12 20:06:54 +00001809 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek3f13f592008-08-12 18:48:50 +00001810 "styleMask", "backing", "defer", NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001811
Ted Kremenek1272f702009-05-12 20:06:54 +00001812 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek3f13f592008-08-12 18:48:50 +00001813 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek00dfe302009-03-04 23:30:42 +00001814#endif
Mike Stump11289f42009-09-09 15:08:12 +00001815
Ted Kremenek3f13f592008-08-12 18:48:50 +00001816 // For NSPanel (which subclasses NSWindow), allocated objects are not
1817 // self-owned.
Ted Kremenek751e7e32009-04-03 19:02:51 +00001818 // FIXME: For now we don't track NSPanels. object for the same reason
1819 // as for NSWindow objects.
1820 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump11289f42009-09-09 15:08:12 +00001821
Ted Kremenek1272f702009-05-12 20:06:54 +00001822#if 0
1823 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek3f13f592008-08-12 18:48:50 +00001824 "styleMask", "backing", "defer", NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001825
Ted Kremenek1272f702009-05-12 20:06:54 +00001826 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek3f13f592008-08-12 18:48:50 +00001827 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek1272f702009-05-12 20:06:54 +00001828#endif
Mike Stump11289f42009-09-09 15:08:12 +00001829
Ted Kremenek501ba032009-05-18 23:14:34 +00001830 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1831 // exit a method.
1832 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001833
Ted Kremenek3b2294c2008-07-18 17:24:20 +00001834 // Create NSAssertionHandler summaries.
Ted Kremenek050b91c2008-08-12 18:30:56 +00001835 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
Mike Stump11289f42009-09-09 15:08:12 +00001836 "lineNumber", "description", NULL);
1837
Ted Kremenek050b91c2008-08-12 18:30:56 +00001838 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1839 "file", "lineNumber", "description", NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001840
Ted Kremenek10369122009-05-20 22:39:57 +00001841 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1842 addInstMethSummary("QCRenderer", AllocSumm,
1843 "createSnapshotImageOfType", NULL);
1844 addInstMethSummary("QCView", AllocSumm,
1845 "createSnapshotImageOfType", NULL);
1846
Ted Kremenek96aa1462009-06-15 20:58:58 +00001847 // Create summaries for CIContext, 'createCGImage' and
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001848 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1849 // automatically garbage collected.
1850 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek10369122009-05-20 22:39:57 +00001851 "createCGImage", "fromRect", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001852 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump11289f42009-09-09 15:08:12 +00001853 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001854 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek96aa1462009-06-15 20:58:58 +00001855 "info", NULL);
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001856}
1857
Ted Kremenek00daccd2008-05-05 22:11:16 +00001858//===----------------------------------------------------------------------===//
Ted Kremenekc52f9392009-02-24 19:15:11 +00001859// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001860//===----------------------------------------------------------------------===//
1861
Ted Kremenekc52f9392009-02-24 19:15:11 +00001862typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1863typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1864typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenek50db3d02009-02-23 17:45:03 +00001865
Ted Kremenekc52f9392009-02-24 19:15:11 +00001866static int AutoRCIndex = 0;
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001867static int AutoRBIndex = 0;
1868
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001869namespace { class AutoreleasePoolContents {}; }
1870namespace { class AutoreleaseStack {}; }
Ted Kremenekc52f9392009-02-24 19:15:11 +00001871
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001872namespace clang {
Ted Kremenekdce78462009-02-25 02:54:57 +00001873template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekc52f9392009-02-24 19:15:11 +00001874 : public GRStatePartialTrait<ARStack> {
Mike Stump11289f42009-09-09 15:08:12 +00001875 static inline void* GDMIndex() { return &AutoRBIndex; }
Ted Kremenekc52f9392009-02-24 19:15:11 +00001876};
1877
1878template<> struct GRStateTrait<AutoreleasePoolContents>
1879 : public GRStatePartialTrait<ARPoolContents> {
Mike Stump11289f42009-09-09 15:08:12 +00001880 static inline void* GDMIndex() { return &AutoRCIndex; }
Ted Kremenekc52f9392009-02-24 19:15:11 +00001881};
1882} // end clang namespace
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001883
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001884static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1885 ARStack stack = state->get<AutoreleaseStack>();
1886 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1887}
1888
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001889static const GRState * SendAutorelease(const GRState *state,
1890 ARCounts::Factory &F, SymbolRef sym) {
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001891
1892 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001893 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001894 ARCounts newCnts(0);
Mike Stump11289f42009-09-09 15:08:12 +00001895
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001896 if (cnts) {
1897 const unsigned *cnt = (*cnts).lookup(sym);
1898 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1899 }
1900 else
1901 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001902
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001903 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001904}
1905
Ted Kremenek71454892008-04-16 20:40:59 +00001906//===----------------------------------------------------------------------===//
1907// Transfer functions.
1908//===----------------------------------------------------------------------===//
1909
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00001910namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001911
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001912class CFRefCount : public GRTransferFuncs {
Ted Kremenek396f4362008-04-18 03:39:05 +00001913public:
Ted Kremenek16306102008-08-13 21:24:49 +00001914 class BindingsPrinter : public GRState::Printer {
Ted Kremenek2a723e62008-03-11 19:44:10 +00001915 public:
Ted Kremenek799bb6e2009-06-24 23:06:47 +00001916 virtual void Print(llvm::raw_ostream& Out, const GRState* state,
Ted Kremenek16306102008-08-13 21:24:49 +00001917 const char* nl, const char* sep);
Ted Kremenek2a723e62008-03-11 19:44:10 +00001918 };
Ted Kremenek396f4362008-04-18 03:39:05 +00001919
1920private:
Zhongxing Xu107f7592009-08-06 12:48:26 +00001921 typedef llvm::DenseMap<const ExplodedNode*, const RetainSummary*>
Mike Stump11289f42009-09-09 15:08:12 +00001922 SummaryLogTy;
Ted Kremenek48d16452009-02-18 03:48:14 +00001923
Mike Stump11289f42009-09-09 15:08:12 +00001924 RetainSummaryManager Summaries;
Ted Kremenek48d16452009-02-18 03:48:14 +00001925 SummaryLogTy SummaryLog;
Ted Kremenek00daccd2008-05-05 22:11:16 +00001926 const LangOptions& LOpts;
Ted Kremenekc52f9392009-02-24 19:15:11 +00001927 ARCounts::Factory ARCountFactory;
Ted Kremenek87aab6c2008-08-17 03:20:02 +00001928
Ted Kremenek400aae72009-02-05 06:50:21 +00001929 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekea072e32009-03-17 19:42:23 +00001930 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek400aae72009-02-05 06:50:21 +00001931 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenekd35272f2009-05-09 00:10:05 +00001932 BugType *overAutorelease;
Ted Kremenekdee56e32009-05-10 06:25:57 +00001933 BugType *returnNotOwnedForOwned;
Ted Kremenek400aae72009-02-05 06:50:21 +00001934 BugReporter *BR;
Mike Stump11289f42009-09-09 15:08:12 +00001935
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001936 const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenekc52f9392009-02-24 19:15:11 +00001937 RefVal::Kind& hasErr);
1938
Zhongxing Xu20227f72009-08-06 01:32:16 +00001939 void ProcessNonLeakError(ExplodedNodeSet& Dst,
Zhongxing Xu107f7592009-08-06 12:48:26 +00001940 GRStmtNodeBuilder& Builder,
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00001941 Expr* NodeExpr, Expr* ErrorExpr,
Zhongxing Xu20227f72009-08-06 01:32:16 +00001942 ExplodedNode* Pred,
Ted Kremenek5ab5a1b2008-08-13 04:27:00 +00001943 const GRState* St,
Ted Kremenekd8242f12008-12-05 02:27:51 +00001944 RefVal::Kind hasErr, SymbolRef Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001946 const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek884a8992009-05-08 23:09:42 +00001947 llvm::SmallVectorImpl<SymbolRef> &Leaked);
Mike Stump11289f42009-09-09 15:08:12 +00001948
Zhongxing Xu20227f72009-08-06 01:32:16 +00001949 ExplodedNode* ProcessLeaks(const GRState * state,
Ted Kremenek884a8992009-05-08 23:09:42 +00001950 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1951 GenericNodeBuilder &Builder,
1952 GRExprEngine &Eng,
Zhongxing Xu20227f72009-08-06 01:32:16 +00001953 ExplodedNode *Pred = 0);
Mike Stump11289f42009-09-09 15:08:12 +00001954
1955public:
Ted Kremenek1f352db2008-07-22 16:21:24 +00001956 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001957 : Summaries(Ctx, gcenabled),
Ted Kremenekea072e32009-03-17 19:42:23 +00001958 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1959 deallocGC(0), deallocNotOwned(0),
Ted Kremenekdee56e32009-05-10 06:25:57 +00001960 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1961 returnNotOwnedForOwned(0), BR(0) {}
Mike Stump11289f42009-09-09 15:08:12 +00001962
Ted Kremenek400aae72009-02-05 06:50:21 +00001963 virtual ~CFRefCount() {}
Mike Stump11289f42009-09-09 15:08:12 +00001964
Ted Kremenek0fbbb082009-11-03 23:30:34 +00001965 void RegisterChecks(GRExprEngine &Eng);
Mike Stump11289f42009-09-09 15:08:12 +00001966
Ted Kremenekceba6ea2008-08-16 00:49:49 +00001967 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1968 Printers.push_back(new BindingsPrinter());
Ted Kremenek2a723e62008-03-11 19:44:10 +00001969 }
Mike Stump11289f42009-09-09 15:08:12 +00001970
Ted Kremenek00daccd2008-05-05 22:11:16 +00001971 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekb0f87c42008-04-30 23:47:44 +00001972 const LangOptions& getLangOptions() const { return LOpts; }
Mike Stump11289f42009-09-09 15:08:12 +00001973
Zhongxing Xu20227f72009-08-06 01:32:16 +00001974 const RetainSummary *getSummaryOfNode(const ExplodedNode *N) const {
Ted Kremenek48d16452009-02-18 03:48:14 +00001975 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1976 return I == SummaryLog.end() ? 0 : I->second;
1977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Ted Kremenek819e9b62008-03-11 06:39:11 +00001979 // Calls.
Ted Kremenek00daccd2008-05-05 22:11:16 +00001980
Zhongxing Xu20227f72009-08-06 01:32:16 +00001981 void EvalSummary(ExplodedNodeSet& Dst,
Ted Kremenek00daccd2008-05-05 22:11:16 +00001982 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00001983 GRStmtNodeBuilder& Builder,
Ted Kremenek00daccd2008-05-05 22:11:16 +00001984 Expr* Ex,
1985 Expr* Receiver,
Ted Kremenekff606a12009-05-04 04:57:00 +00001986 const RetainSummary& Summ,
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00001987 ExprIterator arg_beg, ExprIterator arg_end,
Zhongxing Xuaf353292009-12-02 05:49:12 +00001988 ExplodedNode* Pred, const GRState *state);
Mike Stump11289f42009-09-09 15:08:12 +00001989
Zhongxing Xu20227f72009-08-06 01:32:16 +00001990 virtual void EvalCall(ExplodedNodeSet& Dst,
Ted Kremenek626bd2d2008-03-12 21:06:49 +00001991 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00001992 GRStmtNodeBuilder& Builder,
Zhongxing Xu27f17422008-10-17 05:57:07 +00001993 CallExpr* CE, SVal L,
Mike Stump11289f42009-09-09 15:08:12 +00001994 ExplodedNode* Pred);
1995
1996
Zhongxing Xu20227f72009-08-06 01:32:16 +00001997 virtual void EvalObjCMessageExpr(ExplodedNodeSet& Dst,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00001998 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00001999 GRStmtNodeBuilder& Builder,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002000 ObjCMessageExpr* ME,
Zhongxing Xuaf353292009-12-02 05:49:12 +00002001 ExplodedNode* Pred,
2002 const GRState *state);
Mike Stump11289f42009-09-09 15:08:12 +00002003
Zhongxing Xu20227f72009-08-06 01:32:16 +00002004 bool EvalObjCMessageExprAux(ExplodedNodeSet& Dst,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002005 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002006 GRStmtNodeBuilder& Builder,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002007 ObjCMessageExpr* ME,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002008 ExplodedNode* Pred);
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002009
Mike Stump11289f42009-09-09 15:08:12 +00002010 // Stores.
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00002011 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
2012
Ted Kremenek8784a7c2008-04-11 22:25:11 +00002013 // End-of-path.
Mike Stump11289f42009-09-09 15:08:12 +00002014
Ted Kremenek8784a7c2008-04-11 22:25:11 +00002015 virtual void EvalEndPath(GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002016 GREndPathNodeBuilder& Builder);
Mike Stump11289f42009-09-09 15:08:12 +00002017
Zhongxing Xu20227f72009-08-06 01:32:16 +00002018 virtual void EvalDeadSymbols(ExplodedNodeSet& Dst,
Ted Kremenekb0daf2f2008-04-24 23:57:27 +00002019 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002020 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002021 ExplodedNode* Pred,
Ted Kremenek16fbfe62009-01-21 22:26:05 +00002022 Stmt* S, const GRState* state,
2023 SymbolReaper& SymReaper);
Mike Stump11289f42009-09-09 15:08:12 +00002024
Zhongxing Xu20227f72009-08-06 01:32:16 +00002025 std::pair<ExplodedNode*, const GRState *>
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002026 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002027 ExplodedNode* Pred, GRExprEngine &Eng,
Ted Kremenekd35272f2009-05-09 00:10:05 +00002028 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremeneka506fec2008-04-17 18:12:53 +00002029 // Return statements.
Mike Stump11289f42009-09-09 15:08:12 +00002030
Zhongxing Xu20227f72009-08-06 01:32:16 +00002031 virtual void EvalReturn(ExplodedNodeSet& Dst,
Ted Kremeneka506fec2008-04-17 18:12:53 +00002032 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002033 GRStmtNodeBuilder& Builder,
Ted Kremeneka506fec2008-04-17 18:12:53 +00002034 ReturnStmt* S,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002035 ExplodedNode* Pred);
Ted Kremenek4d837282008-04-18 19:23:43 +00002036
2037 // Assumptions.
2038
Ted Kremenekf9906842009-06-18 22:57:13 +00002039 virtual const GRState *EvalAssume(const GRState* state, SVal condition,
2040 bool assumption);
Ted Kremenek819e9b62008-03-11 06:39:11 +00002041};
2042
2043} // end anonymous namespace
2044
Ted Kremenek799bb6e2009-06-24 23:06:47 +00002045static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym,
2046 const GRState *state) {
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002047 Out << ' ';
Ted Kremenek3e31c262009-03-26 03:35:11 +00002048 if (Sym)
2049 Out << Sym->getSymbolID();
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002050 else
2051 Out << "<pool>";
2052 Out << ":{";
Mike Stump11289f42009-09-09 15:08:12 +00002053
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002054 // Get the contents of the pool.
2055 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
2056 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
2057 Out << '(' << J.getKey() << ',' << J.getData() << ')';
2058
Mike Stump11289f42009-09-09 15:08:12 +00002059 Out << '}';
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002060}
Ted Kremenek396f4362008-04-18 03:39:05 +00002061
Ted Kremenek799bb6e2009-06-24 23:06:47 +00002062void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out,
2063 const GRState* state,
Ted Kremenek16306102008-08-13 21:24:49 +00002064 const char* nl, const char* sep) {
Mike Stump11289f42009-09-09 15:08:12 +00002065
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00002066 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00002067
Ted Kremenek16306102008-08-13 21:24:49 +00002068 if (!B.isEmpty())
Ted Kremenek2a723e62008-03-11 19:44:10 +00002069 Out << sep << nl;
Mike Stump11289f42009-09-09 15:08:12 +00002070
Ted Kremenek2a723e62008-03-11 19:44:10 +00002071 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
2072 Out << (*I).first << " : ";
2073 (*I).second.print(Out);
2074 Out << nl;
2075 }
Mike Stump11289f42009-09-09 15:08:12 +00002076
Ted Kremenekdce78462009-02-25 02:54:57 +00002077 // Print the autorelease stack.
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002078 Out << sep << nl << "AR pool stack:";
Ted Kremenekdce78462009-02-25 02:54:57 +00002079 ARStack stack = state->get<AutoreleaseStack>();
Mike Stump11289f42009-09-09 15:08:12 +00002080
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002081 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
2082 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
2083 PrintPool(Out, *I, state);
2084
2085 Out << nl;
Ted Kremenek2a723e62008-03-11 19:44:10 +00002086}
2087
Ted Kremenek6bd78702009-04-29 18:50:19 +00002088//===----------------------------------------------------------------------===//
2089// Error reporting.
2090//===----------------------------------------------------------------------===//
2091
2092namespace {
Mike Stump11289f42009-09-09 15:08:12 +00002093
Ted Kremenek6bd78702009-04-29 18:50:19 +00002094 //===-------------===//
2095 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00002096 //===-------------===//
2097
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002098 class CFRefBug : public BugType {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002099 protected:
2100 CFRefCount& TF;
Mike Stump11289f42009-09-09 15:08:12 +00002101
Benjamin Kramer63415532009-11-29 18:27:55 +00002102 CFRefBug(CFRefCount* tf, llvm::StringRef name)
Mike Stump11289f42009-09-09 15:08:12 +00002103 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek6bd78702009-04-29 18:50:19 +00002104 public:
Mike Stump11289f42009-09-09 15:08:12 +00002105
Ted Kremenek6bd78702009-04-29 18:50:19 +00002106 CFRefCount& getTF() { return TF; }
2107 const CFRefCount& getTF() const { return TF; }
Mike Stump11289f42009-09-09 15:08:12 +00002108
Ted Kremenek6bd78702009-04-29 18:50:19 +00002109 // FIXME: Eventually remove.
2110 virtual const char* getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002111
Ted Kremenek6bd78702009-04-29 18:50:19 +00002112 virtual bool isLeak() const { return false; }
2113 };
Mike Stump11289f42009-09-09 15:08:12 +00002114
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002115 class UseAfterRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002116 public:
2117 UseAfterRelease(CFRefCount* tf)
2118 : CFRefBug(tf, "Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00002119
Ted Kremenek6bd78702009-04-29 18:50:19 +00002120 const char* getDescription() const {
2121 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00002122 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002123 };
Mike Stump11289f42009-09-09 15:08:12 +00002124
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002125 class BadRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002126 public:
2127 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00002128
Ted Kremenek6bd78702009-04-29 18:50:19 +00002129 const char* getDescription() const {
Ted Kremenek5c22e112009-10-01 17:31:50 +00002130 return "Incorrect decrement of the reference count of an object that is "
2131 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002132 }
2133 };
Mike Stump11289f42009-09-09 15:08:12 +00002134
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002135 class DeallocGC : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002136 public:
Ted Kremenekd35272f2009-05-09 00:10:05 +00002137 DeallocGC(CFRefCount *tf)
2138 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00002139
Ted Kremenek6bd78702009-04-29 18:50:19 +00002140 const char *getDescription() const {
Ted Kremenekd35272f2009-05-09 00:10:05 +00002141 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002142 }
2143 };
Mike Stump11289f42009-09-09 15:08:12 +00002144
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002145 class DeallocNotOwned : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002146 public:
Ted Kremenekd35272f2009-05-09 00:10:05 +00002147 DeallocNotOwned(CFRefCount *tf)
2148 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00002149
Ted Kremenek6bd78702009-04-29 18:50:19 +00002150 const char *getDescription() const {
2151 return "-dealloc sent to object that may be referenced elsewhere";
2152 }
Mike Stump11289f42009-09-09 15:08:12 +00002153 };
2154
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002155 class OverAutorelease : public CFRefBug {
Ted Kremenekd35272f2009-05-09 00:10:05 +00002156 public:
Mike Stump11289f42009-09-09 15:08:12 +00002157 OverAutorelease(CFRefCount *tf) :
Ted Kremenekd35272f2009-05-09 00:10:05 +00002158 CFRefBug(tf, "Object sent -autorelease too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00002159
Ted Kremenekd35272f2009-05-09 00:10:05 +00002160 const char *getDescription() const {
Ted Kremenek3978f792009-05-10 05:11:21 +00002161 return "Object sent -autorelease too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00002162 }
2163 };
Mike Stump11289f42009-09-09 15:08:12 +00002164
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002165 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremenekdee56e32009-05-10 06:25:57 +00002166 public:
2167 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2168 CFRefBug(tf, "Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00002169
Ted Kremenekdee56e32009-05-10 06:25:57 +00002170 const char *getDescription() const {
2171 return "Object with +0 retain counts returned to caller where a +1 "
2172 "(owning) retain count is expected";
2173 }
2174 };
Mike Stump11289f42009-09-09 15:08:12 +00002175
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002176 class Leak : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002177 const bool isReturn;
2178 protected:
Benjamin Kramer63415532009-11-29 18:27:55 +00002179 Leak(CFRefCount* tf, llvm::StringRef name, bool isRet)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002180 : CFRefBug(tf, name), isReturn(isRet) {}
2181 public:
Mike Stump11289f42009-09-09 15:08:12 +00002182
Ted Kremenek6bd78702009-04-29 18:50:19 +00002183 const char* getDescription() const { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00002184
Ted Kremenek6bd78702009-04-29 18:50:19 +00002185 bool isLeak() const { return true; }
2186 };
Mike Stump11289f42009-09-09 15:08:12 +00002187
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002188 class LeakAtReturn : public Leak {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002189 public:
Benjamin Kramer63415532009-11-29 18:27:55 +00002190 LeakAtReturn(CFRefCount* tf, llvm::StringRef name)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002191 : Leak(tf, name, true) {}
2192 };
Mike Stump11289f42009-09-09 15:08:12 +00002193
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002194 class LeakWithinFunction : public Leak {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002195 public:
Benjamin Kramer63415532009-11-29 18:27:55 +00002196 LeakWithinFunction(CFRefCount* tf, llvm::StringRef name)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002197 : Leak(tf, name, false) {}
Mike Stump11289f42009-09-09 15:08:12 +00002198 };
2199
Ted Kremenek6bd78702009-04-29 18:50:19 +00002200 //===---------===//
2201 // Bug Reports. //
2202 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00002203
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002204 class CFRefReport : public RangedBugReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002205 protected:
2206 SymbolRef Sym;
2207 const CFRefCount &TF;
2208 public:
2209 CFRefReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002210 ExplodedNode *n, SymbolRef sym)
Ted Kremenek3978f792009-05-10 05:11:21 +00002211 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2212
2213 CFRefReport(CFRefBug& D, const CFRefCount &tf,
Benjamin Kramer63415532009-11-29 18:27:55 +00002214 ExplodedNode *n, SymbolRef sym, llvm::StringRef endText)
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002215 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Mike Stump11289f42009-09-09 15:08:12 +00002216
Ted Kremenek6bd78702009-04-29 18:50:19 +00002217 virtual ~CFRefReport() {}
Mike Stump11289f42009-09-09 15:08:12 +00002218
Ted Kremenek6bd78702009-04-29 18:50:19 +00002219 CFRefBug& getBugType() {
2220 return (CFRefBug&) RangedBugReport::getBugType();
2221 }
2222 const CFRefBug& getBugType() const {
2223 return (const CFRefBug&) RangedBugReport::getBugType();
2224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225
Zhongxing Xu7864b9ea2009-08-18 08:58:41 +00002226 virtual void getRanges(const SourceRange*& beg, const SourceRange*& end) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002227 if (!getBugType().isLeak())
Zhongxing Xu7864b9ea2009-08-18 08:58:41 +00002228 RangedBugReport::getRanges(beg, end);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002229 else
2230 beg = end = 0;
2231 }
Mike Stump11289f42009-09-09 15:08:12 +00002232
Ted Kremenek6bd78702009-04-29 18:50:19 +00002233 SymbolRef getSymbol() const { return Sym; }
Mike Stump11289f42009-09-09 15:08:12 +00002234
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002235 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002236 const ExplodedNode* N);
Mike Stump11289f42009-09-09 15:08:12 +00002237
Ted Kremenek6bd78702009-04-29 18:50:19 +00002238 std::pair<const char**,const char**> getExtraDescriptiveText();
Mike Stump11289f42009-09-09 15:08:12 +00002239
Zhongxing Xu20227f72009-08-06 01:32:16 +00002240 PathDiagnosticPiece* VisitNode(const ExplodedNode* N,
2241 const ExplodedNode* PrevN,
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002242 BugReporterContext& BRC);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002243 };
Ted Kremenek3978f792009-05-10 05:11:21 +00002244
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002245 class CFRefLeakReport : public CFRefReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002246 SourceLocation AllocSite;
2247 const MemRegion* AllocBinding;
2248 public:
2249 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002250 ExplodedNode *n, SymbolRef sym,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002251 GRExprEngine& Eng);
Mike Stump11289f42009-09-09 15:08:12 +00002252
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002253 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002254 const ExplodedNode* N);
Mike Stump11289f42009-09-09 15:08:12 +00002255
Ted Kremenek6bd78702009-04-29 18:50:19 +00002256 SourceLocation getLocation() const { return AllocSite; }
Mike Stump11289f42009-09-09 15:08:12 +00002257 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00002258} // end anonymous namespace
2259
Mike Stump11289f42009-09-09 15:08:12 +00002260
Ted Kremenek6bd78702009-04-29 18:50:19 +00002261
2262static const char* Msgs[] = {
2263 // GC only
Mike Stump11289f42009-09-09 15:08:12 +00002264 "Code is compiled to only use garbage collection",
Ted Kremenek6bd78702009-04-29 18:50:19 +00002265 // No GC.
2266 "Code is compiled to use reference counts",
2267 // Hybrid, with GC.
2268 "Code is compiled to use either garbage collection (GC) or reference counts"
Mike Stump11289f42009-09-09 15:08:12 +00002269 " (non-GC). The bug occurs with GC enabled",
Ted Kremenek6bd78702009-04-29 18:50:19 +00002270 // Hybrid, without GC
2271 "Code is compiled to use either garbage collection (GC) or reference counts"
2272 " (non-GC). The bug occurs in non-GC mode"
2273};
2274
2275std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2276 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
Mike Stump11289f42009-09-09 15:08:12 +00002277
Ted Kremenek6bd78702009-04-29 18:50:19 +00002278 switch (TF.getLangOptions().getGCMode()) {
2279 default:
2280 assert(false);
Mike Stump11289f42009-09-09 15:08:12 +00002281
Ted Kremenek6bd78702009-04-29 18:50:19 +00002282 case LangOptions::GCOnly:
2283 assert (TF.isGCEnabled());
Mike Stump11289f42009-09-09 15:08:12 +00002284 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2285
Ted Kremenek6bd78702009-04-29 18:50:19 +00002286 case LangOptions::NonGC:
2287 assert (!TF.isGCEnabled());
2288 return std::make_pair(&Msgs[1], &Msgs[1]+1);
Mike Stump11289f42009-09-09 15:08:12 +00002289
Ted Kremenek6bd78702009-04-29 18:50:19 +00002290 case LangOptions::HybridGC:
2291 if (TF.isGCEnabled())
2292 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2293 else
2294 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2295 }
2296}
2297
2298static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2299 ArgEffect X) {
2300 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2301 I!=E; ++I)
2302 if (*I == X) return true;
Mike Stump11289f42009-09-09 15:08:12 +00002303
Ted Kremenek6bd78702009-04-29 18:50:19 +00002304 return false;
2305}
2306
Zhongxing Xu20227f72009-08-06 01:32:16 +00002307PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N,
2308 const ExplodedNode* PrevN,
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002309 BugReporterContext& BRC) {
Mike Stump11289f42009-09-09 15:08:12 +00002310
Ted Kremenek051a03d2009-05-13 07:12:33 +00002311 if (!isa<PostStmt>(N->getLocation()))
2312 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002313
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002314 // Check if the type state has changed.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002315 const GRState *PrevSt = PrevN->getState();
2316 const GRState *CurrSt = N->getState();
Mike Stump11289f42009-09-09 15:08:12 +00002317
2318 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002319 if (!CurrT) return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002320
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002321 const RefVal &CurrV = *CurrT;
2322 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002323
Ted Kremenek6bd78702009-04-29 18:50:19 +00002324 // Create a string buffer to constain all the useful things we want
2325 // to tell the user.
2326 std::string sbuf;
2327 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002328
Ted Kremenek6bd78702009-04-29 18:50:19 +00002329 // This is the allocation site since the previous node had no bindings
2330 // for this symbol.
2331 if (!PrevT) {
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002332 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002333
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002334 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002335 // Get the name of the callee (if it is available).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002336 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002337 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2338 os << "Call to function '" << FD->getNameAsString() <<'\'';
2339 else
Mike Stump11289f42009-09-09 15:08:12 +00002340 os << "function call";
2341 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002342 else {
2343 assert (isa<ObjCMessageExpr>(S));
2344 os << "Method";
2345 }
Mike Stump11289f42009-09-09 15:08:12 +00002346
Ted Kremenek6bd78702009-04-29 18:50:19 +00002347 if (CurrV.getObjKind() == RetEffect::CF) {
2348 os << " returns a Core Foundation object with a ";
2349 }
2350 else {
2351 assert (CurrV.getObjKind() == RetEffect::ObjC);
2352 os << " returns an Objective-C object with a ";
2353 }
Mike Stump11289f42009-09-09 15:08:12 +00002354
Ted Kremenek6bd78702009-04-29 18:50:19 +00002355 if (CurrV.isOwned()) {
2356 os << "+1 retain count (owning reference).";
Mike Stump11289f42009-09-09 15:08:12 +00002357
Ted Kremenek6bd78702009-04-29 18:50:19 +00002358 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2359 assert(CurrV.getObjKind() == RetEffect::CF);
2360 os << " "
2361 "Core Foundation objects are not automatically garbage collected.";
2362 }
2363 }
2364 else {
2365 assert (CurrV.isNotOwned());
2366 os << "+0 retain count (non-owning reference).";
2367 }
Mike Stump11289f42009-09-09 15:08:12 +00002368
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002369 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002370 return new PathDiagnosticEventPiece(Pos, os.str());
2371 }
Mike Stump11289f42009-09-09 15:08:12 +00002372
Ted Kremenek6bd78702009-04-29 18:50:19 +00002373 // Gather up the effects that were performed on the object at this
2374 // program point
2375 llvm::SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00002376
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002377 if (const RetainSummary *Summ =
2378 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002379 // We only have summaries attached to nodes after evaluating CallExpr and
2380 // ObjCMessageExprs.
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002381 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002382
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002383 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002384 // Iterate through the parameter expressions and see if the symbol
2385 // was ever passed as an argument.
2386 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002387
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002388 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002389 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002390
Ted Kremenek6bd78702009-04-29 18:50:19 +00002391 // Retrieve the value of the argument. Is it the symbol
2392 // we are interested in?
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002393 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002394 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002395
Ted Kremenek6bd78702009-04-29 18:50:19 +00002396 // We have an argument. Get the effect!
2397 AEffects.push_back(Summ->getArg(i));
2398 }
2399 }
Mike Stump11289f42009-09-09 15:08:12 +00002400 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002401 if (const Expr *receiver = ME->getReceiver())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002402 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002403 // The symbol we are tracking is the receiver.
2404 AEffects.push_back(Summ->getReceiverEffect());
2405 }
2406 }
2407 }
Mike Stump11289f42009-09-09 15:08:12 +00002408
Ted Kremenek6bd78702009-04-29 18:50:19 +00002409 do {
2410 // Get the previous type state.
2411 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Ted Kremenek6bd78702009-04-29 18:50:19 +00002413 // Specially handle -dealloc.
2414 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2415 // Determine if the object's reference count was pushed to zero.
2416 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2417 // We may not have transitioned to 'release' if we hit an error.
2418 // This case is handled elsewhere.
2419 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002420 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002421 os << "Object released by directly sending the '-dealloc' message";
2422 break;
2423 }
2424 }
Mike Stump11289f42009-09-09 15:08:12 +00002425
Ted Kremenek6bd78702009-04-29 18:50:19 +00002426 // Specially handle CFMakeCollectable and friends.
2427 if (contains(AEffects, MakeCollectable)) {
2428 // Get the name of the function.
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002429 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002430 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002431 const FunctionDecl* FD = X.getAsFunctionDecl();
2432 const std::string& FName = FD->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00002433
Ted Kremenek6bd78702009-04-29 18:50:19 +00002434 if (TF.isGCEnabled()) {
2435 // Determine if the object's reference count was pushed to zero.
2436 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00002437
Ted Kremenek6bd78702009-04-29 18:50:19 +00002438 os << "In GC mode a call to '" << FName
2439 << "' decrements an object's retain count and registers the "
2440 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00002441
Ted Kremenek6bd78702009-04-29 18:50:19 +00002442 if (CurrV.getKind() == RefVal::Released) {
2443 assert(CurrV.getCount() == 0);
2444 os << "Since it now has a 0 retain count the object can be "
2445 "automatically collected by the garbage collector.";
2446 }
2447 else
2448 os << "An object must have a 0 retain count to be garbage collected. "
2449 "After this call its retain count is +" << CurrV.getCount()
2450 << '.';
2451 }
Mike Stump11289f42009-09-09 15:08:12 +00002452 else
Ted Kremenek6bd78702009-04-29 18:50:19 +00002453 os << "When GC is not enabled a call to '" << FName
2454 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00002455
Ted Kremenek6bd78702009-04-29 18:50:19 +00002456 // Nothing more to say.
2457 break;
2458 }
Mike Stump11289f42009-09-09 15:08:12 +00002459
2460 // Determine if the typestate has changed.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002461 if (!(PrevV == CurrV))
2462 switch (CurrV.getKind()) {
2463 case RefVal::Owned:
2464 case RefVal::NotOwned:
Mike Stump11289f42009-09-09 15:08:12 +00002465
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002466 if (PrevV.getCount() == CurrV.getCount()) {
2467 // Did an autorelease message get sent?
2468 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2469 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002470
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002471 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenek3978f792009-05-10 05:11:21 +00002472 os << "Object sent -autorelease message";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002473 break;
2474 }
Mike Stump11289f42009-09-09 15:08:12 +00002475
Ted Kremenek6bd78702009-04-29 18:50:19 +00002476 if (PrevV.getCount() > CurrV.getCount())
2477 os << "Reference count decremented.";
2478 else
2479 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00002480
Ted Kremenek6bd78702009-04-29 18:50:19 +00002481 if (unsigned Count = CurrV.getCount())
2482 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00002483
Ted Kremenek6bd78702009-04-29 18:50:19 +00002484 if (PrevV.getKind() == RefVal::Released) {
2485 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2486 os << " The object is not eligible for garbage collection until the "
2487 "retain count reaches 0 again.";
2488 }
Mike Stump11289f42009-09-09 15:08:12 +00002489
Ted Kremenek6bd78702009-04-29 18:50:19 +00002490 break;
Mike Stump11289f42009-09-09 15:08:12 +00002491
Ted Kremenek6bd78702009-04-29 18:50:19 +00002492 case RefVal::Released:
2493 os << "Object released.";
2494 break;
Mike Stump11289f42009-09-09 15:08:12 +00002495
Ted Kremenek6bd78702009-04-29 18:50:19 +00002496 case RefVal::ReturnedOwned:
2497 os << "Object returned to caller as an owning reference (single retain "
2498 "count transferred to caller).";
2499 break;
Mike Stump11289f42009-09-09 15:08:12 +00002500
Ted Kremenek6bd78702009-04-29 18:50:19 +00002501 case RefVal::ReturnedNotOwned:
2502 os << "Object returned to caller with a +0 (non-owning) retain count.";
2503 break;
Mike Stump11289f42009-09-09 15:08:12 +00002504
Ted Kremenek6bd78702009-04-29 18:50:19 +00002505 default:
2506 return NULL;
2507 }
Mike Stump11289f42009-09-09 15:08:12 +00002508
Ted Kremenek6bd78702009-04-29 18:50:19 +00002509 // Emit any remaining diagnostics for the argument effects (if any).
2510 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2511 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002512
Ted Kremenek6bd78702009-04-29 18:50:19 +00002513 // A bunch of things have alternate behavior under GC.
2514 if (TF.isGCEnabled())
2515 switch (*I) {
2516 default: break;
2517 case Autorelease:
2518 os << "In GC mode an 'autorelease' has no effect.";
2519 continue;
2520 case IncRefMsg:
2521 os << "In GC mode the 'retain' message has no effect.";
2522 continue;
2523 case DecRefMsg:
2524 os << "In GC mode the 'release' message has no effect.";
2525 continue;
2526 }
2527 }
Mike Stump11289f42009-09-09 15:08:12 +00002528 } while (0);
2529
Ted Kremenek6bd78702009-04-29 18:50:19 +00002530 if (os.str().empty())
2531 return 0; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002532
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002533 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002534 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002535 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002536
Ted Kremenek6bd78702009-04-29 18:50:19 +00002537 // Add the range by scanning the children of the statement for any bindings
2538 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002539 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002540 I!=E; ++I)
2541 if (const Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002542 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002543 P->addRange(Exp->getSourceRange());
2544 break;
2545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Ted Kremenek6bd78702009-04-29 18:50:19 +00002547 return P;
2548}
2549
2550namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00002551 class FindUniqueBinding :
Ted Kremenek6bd78702009-04-29 18:50:19 +00002552 public StoreManager::BindingsHandler {
2553 SymbolRef Sym;
2554 const MemRegion* Binding;
2555 bool First;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Ted Kremenek6bd78702009-04-29 18:50:19 +00002557 public:
2558 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Mike Stump11289f42009-09-09 15:08:12 +00002559
Ted Kremenek6bd78702009-04-29 18:50:19 +00002560 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2561 SVal val) {
Mike Stump11289f42009-09-09 15:08:12 +00002562
2563 SymbolRef SymV = val.getAsSymbol();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002564 if (!SymV || SymV != Sym)
2565 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002566
Ted Kremenek6bd78702009-04-29 18:50:19 +00002567 if (Binding) {
2568 First = false;
2569 return false;
2570 }
2571 else
2572 Binding = R;
Mike Stump11289f42009-09-09 15:08:12 +00002573
2574 return true;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002575 }
Mike Stump11289f42009-09-09 15:08:12 +00002576
Ted Kremenek6bd78702009-04-29 18:50:19 +00002577 operator bool() { return First && Binding; }
2578 const MemRegion* getRegion() { return Binding; }
Mike Stump11289f42009-09-09 15:08:12 +00002579 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00002580}
2581
Zhongxing Xu20227f72009-08-06 01:32:16 +00002582static std::pair<const ExplodedNode*,const MemRegion*>
2583GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode* N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002584 SymbolRef Sym) {
Mike Stump11289f42009-09-09 15:08:12 +00002585
Ted Kremenek6bd78702009-04-29 18:50:19 +00002586 // Find both first node that referred to the tracked symbol and the
2587 // memory location that value was store to.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002588 const ExplodedNode* Last = N;
Mike Stump11289f42009-09-09 15:08:12 +00002589 const MemRegion* FirstBinding = 0;
2590
Ted Kremenek6bd78702009-04-29 18:50:19 +00002591 while (N) {
2592 const GRState* St = N->getState();
2593 RefBindings B = St->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00002594
Ted Kremenek6bd78702009-04-29 18:50:19 +00002595 if (!B.lookup(Sym))
2596 break;
Mike Stump11289f42009-09-09 15:08:12 +00002597
Ted Kremenek6bd78702009-04-29 18:50:19 +00002598 FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002599 StateMgr.iterBindings(St, FB);
2600 if (FB) FirstBinding = FB.getRegion();
2601
Ted Kremenek6bd78702009-04-29 18:50:19 +00002602 Last = N;
Mike Stump11289f42009-09-09 15:08:12 +00002603 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002604 }
Mike Stump11289f42009-09-09 15:08:12 +00002605
Ted Kremenek6bd78702009-04-29 18:50:19 +00002606 return std::make_pair(Last, FirstBinding);
2607}
2608
2609PathDiagnosticPiece*
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002610CFRefReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002611 const ExplodedNode* EndN) {
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002612 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002613 // assigned to different variables, etc.
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002614 BRC.addNotableSymbol(Sym);
2615 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002616}
2617
2618PathDiagnosticPiece*
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002619CFRefLeakReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002620 const ExplodedNode* EndN){
Mike Stump11289f42009-09-09 15:08:12 +00002621
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002622 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002623 // assigned to different variables, etc.
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002624 BRC.addNotableSymbol(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002625
Ted Kremenek6bd78702009-04-29 18:50:19 +00002626 // We are reporting a leak. Walk up the graph to get to the first node where
2627 // the symbol appeared, and also get the first VarDecl that tracked object
2628 // is stored to.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002629 const ExplodedNode* AllocNode = 0;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002630 const MemRegion* FirstBinding = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002631
Ted Kremenek6bd78702009-04-29 18:50:19 +00002632 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002633 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002634
2635 // Get the allocate site.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002636 assert(AllocNode);
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002637 const Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002638
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002639 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002640 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002641
Ted Kremenek6bd78702009-04-29 18:50:19 +00002642 // Compute an actual location for the leak. Sometimes a leak doesn't
2643 // occur at an actual statement (e.g., transition between blocks; end
2644 // of function) so we need to walk the graph and compute a real location.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002645 const ExplodedNode* LeakN = EndN;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002646 PathDiagnosticLocation L;
Mike Stump11289f42009-09-09 15:08:12 +00002647
Ted Kremenek6bd78702009-04-29 18:50:19 +00002648 while (LeakN) {
2649 ProgramPoint P = LeakN->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00002650
Ted Kremenek6bd78702009-04-29 18:50:19 +00002651 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2652 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2653 break;
2654 }
2655 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2656 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2657 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2658 break;
2659 }
2660 }
Mike Stump11289f42009-09-09 15:08:12 +00002661
Ted Kremenek6bd78702009-04-29 18:50:19 +00002662 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2663 }
Mike Stump11289f42009-09-09 15:08:12 +00002664
Ted Kremenek6bd78702009-04-29 18:50:19 +00002665 if (!L.isValid()) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002666 const Decl &D = EndN->getCodeDecl();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002667 L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Ted Kremenek6bd78702009-04-29 18:50:19 +00002670 std::string sbuf;
2671 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002672
Ted Kremenek6bd78702009-04-29 18:50:19 +00002673 os << "Object allocated on line " << AllocLine;
Mike Stump11289f42009-09-09 15:08:12 +00002674
Ted Kremenek6bd78702009-04-29 18:50:19 +00002675 if (FirstBinding)
Mike Stump11289f42009-09-09 15:08:12 +00002676 os << " and stored into '" << FirstBinding->getString() << '\'';
2677
Ted Kremenek6bd78702009-04-29 18:50:19 +00002678 // Get the retain count.
2679 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002680
Ted Kremenek6bd78702009-04-29 18:50:19 +00002681 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2682 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2683 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2684 // to the caller for NS objects.
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002685 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002686 os << " is returned from a method whose name ('"
Ted Kremenek223a7d52009-04-29 23:03:22 +00002687 << MD.getSelector().getAsString()
Ted Kremenek6bd78702009-04-29 18:50:19 +00002688 << "') does not contain 'copy' or otherwise starts with"
2689 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenekd6bef2e2009-04-29 22:25:52 +00002690 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002691 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002692 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002693 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002694 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002695 << "' is potentially leaked when using garbage collection. Callers "
2696 "of this method do not expect a returned object with a +1 retain "
2697 "count since they expect the object to be managed by the garbage "
2698 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002699 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002700 else
2701 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenekd6bef2e2009-04-29 22:25:52 +00002702 " +" << RV->getCount() << " (object leaked)";
Mike Stump11289f42009-09-09 15:08:12 +00002703
Ted Kremenek6bd78702009-04-29 18:50:19 +00002704 return new PathDiagnosticEventPiece(L, os.str());
2705}
2706
Ted Kremenek6bd78702009-04-29 18:50:19 +00002707CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002708 ExplodedNode *n,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002709 SymbolRef sym, GRExprEngine& Eng)
Mike Stump11289f42009-09-09 15:08:12 +00002710: CFRefReport(D, tf, n, sym) {
2711
Ted Kremenek6bd78702009-04-29 18:50:19 +00002712 // Most bug reports are cached at the location where they occured.
2713 // With leaks, we want to unique them by the location where they were
2714 // allocated, and only report a single path. To do this, we need to find
2715 // the allocation site of a piece of tracked memory, which we do via a
2716 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2717 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2718 // that all ancestor nodes that represent the allocation site have the
2719 // same SourceLocation.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002720 const ExplodedNode* AllocNode = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002721
Ted Kremenek6bd78702009-04-29 18:50:19 +00002722 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002723 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Mike Stump11289f42009-09-09 15:08:12 +00002724
Ted Kremenek6bd78702009-04-29 18:50:19 +00002725 // Get the SourceLocation for the allocation site.
2726 ProgramPoint P = AllocNode->getLocation();
2727 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00002728
Ted Kremenek6bd78702009-04-29 18:50:19 +00002729 // Fill in the description of the bug.
2730 Description.clear();
2731 llvm::raw_string_ostream os(Description);
2732 SourceManager& SMgr = Eng.getContext().getSourceManager();
2733 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002734 os << "Potential leak ";
2735 if (tf.isGCEnabled()) {
2736 os << "(when using garbage collection) ";
Mike Stump11289f42009-09-09 15:08:12 +00002737 }
Ted Kremenekf1e76672009-05-02 19:05:19 +00002738 os << "of an object allocated on line " << AllocLine;
Mike Stump11289f42009-09-09 15:08:12 +00002739
Ted Kremenek6bd78702009-04-29 18:50:19 +00002740 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2741 if (AllocBinding)
2742 os << " and stored into '" << AllocBinding->getString() << '\'';
2743}
2744
2745//===----------------------------------------------------------------------===//
2746// Main checker logic.
2747//===----------------------------------------------------------------------===//
2748
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002749/// GetReturnType - Used to get the return type of a message expression or
2750/// function call with the intention of affixing that type to a tracked symbol.
2751/// While the the return type can be queried directly from RetEx, when
2752/// invoking class methods we augment to the return type to be that of
2753/// a pointer to the class (as opposed it just being id).
Steve Naroff7cae42b2009-07-10 23:34:53 +00002754static QualType GetReturnType(const Expr* RetE, ASTContext& Ctx) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002755 QualType RetTy = RetE->getType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002756 // If RetE is not a message expression just return its type.
2757 // If RetE is a message expression, return its types if it is something
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002758 /// more specific than id.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002759 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
John McCall9dd450b2009-09-21 23:43:11 +00002760 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002761 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002762 PT->isObjCClassType()) {
2763 // At this point we know the return type of the message expression is
2764 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2765 // is a call to a class method whose type we can resolve. In such
2766 // cases, promote the return type to XXX* (where XXX is the class).
Mike Stump11289f42009-09-09 15:08:12 +00002767 const ObjCInterfaceDecl *D = ME->getClassInfo().first;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002768 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2769 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
Steve Naroff7cae42b2009-07-10 23:34:53 +00002771 return RetTy;
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002772}
2773
Zhongxing Xu20227f72009-08-06 01:32:16 +00002774void CFRefCount::EvalSummary(ExplodedNodeSet& Dst,
Ted Kremenek00daccd2008-05-05 22:11:16 +00002775 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002776 GRStmtNodeBuilder& Builder,
Ted Kremenek00daccd2008-05-05 22:11:16 +00002777 Expr* Ex,
2778 Expr* Receiver,
Ted Kremenekff606a12009-05-04 04:57:00 +00002779 const RetainSummary& Summ,
Zhongxing Xuac129432009-04-20 05:24:46 +00002780 ExprIterator arg_beg, ExprIterator arg_end,
Zhongxing Xuaf353292009-12-02 05:49:12 +00002781 ExplodedNode* Pred, const GRState *state) {
Ted Kremenek821537e2008-05-06 02:41:27 +00002782
2783 // Evaluate the effect of the arguments.
Ted Kremenek8cb96e92008-04-16 04:28:53 +00002784 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek68d73d12008-03-12 01:21:45 +00002785 unsigned idx = 0;
Ted Kremenek988990f2008-04-11 18:40:51 +00002786 Expr* ErrorExpr = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002787 SymbolRef ErrorSym = 0;
2788
2789 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
2790 SVal V = state->getSValAsScalarOrLoc(*I);
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002791 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek804fc232009-03-04 00:13:50 +00002792
Ted Kremenek3e31c262009-03-26 03:35:11 +00002793 if (Sym)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002794 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002795 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekc52f9392009-02-24 19:15:11 +00002796 if (hasErr) {
Ted Kremenek988990f2008-04-11 18:40:51 +00002797 ErrorExpr = *I;
Ted Kremenek4963d112008-07-07 16:21:19 +00002798 ErrorSym = Sym;
Ted Kremenek988990f2008-04-11 18:40:51 +00002799 break;
Mike Stump11289f42009-09-09 15:08:12 +00002800 }
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002801 continue;
Ted Kremenekc52f9392009-02-24 19:15:11 +00002802 }
Ted Kremenekae529272008-07-09 18:11:16 +00002803
Ted Kremenekf9539d02009-09-22 04:48:39 +00002804 tryAgain:
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002805 if (isa<Loc>(V)) {
2806 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002807 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekae529272008-07-09 18:11:16 +00002808 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002809
2810 // Invalidate the value of the variable passed by reference.
2811
Ted Kremenek4d851462008-07-03 23:26:32 +00002812 // FIXME: We can have collisions on the conjured symbol if the
2813 // expression *I also creates conjured symbols. We probably want
2814 // to identify conjured symbols by an expression pair: the enclosing
2815 // expression (the context) and the expression itself. This should
Mike Stump11289f42009-09-09 15:08:12 +00002816 // disambiguate conjured symbols.
Zhongxing Xu4744d562009-06-29 06:43:40 +00002817 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002818 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
Ted Kremenek97f75f82009-05-11 22:55:17 +00002819
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002820 const MemRegion *R = MR->getRegion();
2821 // Are we dealing with an ElementRegion? If the element type is
2822 // a basic integer type (e.g., char, int) and the underying region
2823 // is a variable region then strip off the ElementRegion.
2824 // FIXME: We really need to think about this for the general case
2825 // as sometimes we are reasoning about arrays and other times
2826 // about (char*), etc., is just a form of passing raw bytes.
2827 // e.g., void *p = alloca(); foo((char*)p);
2828 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2829 // Checking for 'integral type' is probably too promiscuous, but
2830 // we'll leave it in for now until we have a systematic way of
2831 // handling all of these cases. Eventually we need to come up
2832 // with an interface to StoreManager so that this logic can be
2833 // approriately delegated to the respective StoreManagers while
2834 // still allowing us to do checker-specific logic (e.g.,
2835 // invalidating reference counts), probably via callbacks.
2836 if (ER->getElementType()->isIntegralType()) {
2837 const MemRegion *superReg = ER->getSuperRegion();
2838 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2839 isa<ObjCIvarRegion>(superReg))
2840 R = cast<TypedRegion>(superReg);
Ted Kremenek0626df42009-05-06 18:19:24 +00002841 }
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002842 // FIXME: What about layers of ElementRegions?
2843 }
Zhongxing Xu4744d562009-06-29 06:43:40 +00002844
Ted Kremenek1eb68092009-10-16 00:30:49 +00002845 StoreManager::InvalidatedSymbols IS;
2846 state = StoreMgr.InvalidateRegion(state, R, *I, Count, &IS);
2847 for (StoreManager::InvalidatedSymbols::iterator I = IS.begin(),
2848 E = IS.end(); I!=E; ++I) {
2849 // Remove any existing reference-count binding.
2850 state = state->remove<RefBindings>(*I);
2851 }
Ted Kremenek4d851462008-07-03 23:26:32 +00002852 }
2853 else {
2854 // Nuke all other arguments passed by reference.
Ted Kremenekf9539d02009-09-22 04:48:39 +00002855 // FIXME: is this necessary or correct? This handles the non-Region
2856 // cases. Is it ever valid to store to these?
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002857 state = state->unbindLoc(cast<Loc>(V));
Ted Kremenek4d851462008-07-03 23:26:32 +00002858 }
Ted Kremenek0a86fdb2008-04-11 20:51:02 +00002859 }
Ted Kremenekf9539d02009-09-22 04:48:39 +00002860 else if (isa<nonloc::LocAsInteger>(V)) {
2861 // If we are passing a location wrapped as an integer, unwrap it and
2862 // invalidate the values referred by the location.
2863 V = cast<nonloc::LocAsInteger>(V).getLoc();
2864 goto tryAgain;
2865 }
Mike Stump11289f42009-09-09 15:08:12 +00002866 }
2867
2868 // Evaluate the effect on the message receiver.
Ted Kremenek821537e2008-05-06 02:41:27 +00002869 if (!ErrorExpr && Receiver) {
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002870 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek3e31c262009-03-26 03:35:11 +00002871 if (Sym) {
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002872 if (const RefVal* T = state->get<RefBindings>(Sym)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002873 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekc52f9392009-02-24 19:15:11 +00002874 if (hasErr) {
Ted Kremenek821537e2008-05-06 02:41:27 +00002875 ErrorExpr = Receiver;
Ted Kremenek4963d112008-07-07 16:21:19 +00002876 ErrorSym = Sym;
Ted Kremenek821537e2008-05-06 02:41:27 +00002877 }
Ted Kremenekc52f9392009-02-24 19:15:11 +00002878 }
Ted Kremenek821537e2008-05-06 02:41:27 +00002879 }
2880 }
Mike Stump11289f42009-09-09 15:08:12 +00002881
2882 // Process any errors.
Ted Kremenek8cb96e92008-04-16 04:28:53 +00002883 if (hasErr) {
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00002884 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek396f4362008-04-18 03:39:05 +00002885 hasErr, ErrorSym);
Ted Kremenek68d73d12008-03-12 01:21:45 +00002886 return;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00002887 }
Mike Stump11289f42009-09-09 15:08:12 +00002888
2889 // Consult the summary for the return value.
Ted Kremenekff606a12009-05-04 04:57:00 +00002890 RetEffect RE = Summ.getRetEffect();
Mike Stump11289f42009-09-09 15:08:12 +00002891
Ted Kremenek1272f702009-05-12 20:06:54 +00002892 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2893 assert(Receiver);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002894 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek1272f702009-05-12 20:06:54 +00002895 bool found = false;
2896 if (SymbolRef Sym = V.getAsLocSymbol())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002897 if (state->get<RefBindings>(Sym)) {
Ted Kremenek1272f702009-05-12 20:06:54 +00002898 found = true;
2899 RE = Summaries.getObjAllocRetEffect();
2900 }
2901
2902 if (!found)
2903 RE = RetEffect::MakeNoRet();
Mike Stump11289f42009-09-09 15:08:12 +00002904 }
2905
Ted Kremenek68d73d12008-03-12 01:21:45 +00002906 switch (RE.getKind()) {
2907 default:
2908 assert (false && "Unhandled RetEffect."); break;
Mike Stump11289f42009-09-09 15:08:12 +00002909
2910 case RetEffect::NoRet: {
Ted Kremenek831f3272008-04-11 20:23:24 +00002911 // Make up a symbol for the return value (not reference counted).
Ted Kremenek1642bda2009-06-26 00:05:51 +00002912 // FIXME: Most of this logic is not specific to the retain/release
2913 // checker.
Mike Stump11289f42009-09-09 15:08:12 +00002914
Ted Kremenek21387322008-10-17 22:23:12 +00002915 // FIXME: We eventually should handle structs and other compound types
2916 // that are returned by value.
Mike Stump11289f42009-09-09 15:08:12 +00002917
Ted Kremenek21387322008-10-17 22:23:12 +00002918 QualType T = Ex->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002919
Ted Kremenek16866d62008-11-13 06:10:40 +00002920 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek831f3272008-04-11 20:23:24 +00002921 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekf2489ea2009-04-09 22:22:44 +00002922 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremeneke41b81e2009-09-27 20:45:21 +00002923 SVal X = ValMgr.getConjuredSymbolVal(NULL, Ex, T, Count);
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002924 state = state->BindExpr(Ex, X, false);
Mike Stump11289f42009-09-09 15:08:12 +00002925 }
2926
Ted Kremenek4b772092008-04-10 23:44:06 +00002927 break;
Ted Kremenek21387322008-10-17 22:23:12 +00002928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929
Ted Kremenek68d73d12008-03-12 01:21:45 +00002930 case RetEffect::Alias: {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002931 unsigned idx = RE.getIndex();
Ted Kremenek08e17112008-06-17 02:43:46 +00002932 assert (arg_end >= arg_beg);
Ted Kremenek00daccd2008-05-05 22:11:16 +00002933 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002934 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002935 state = state->BindExpr(Ex, V, false);
Ted Kremenek68d73d12008-03-12 01:21:45 +00002936 break;
2937 }
Mike Stump11289f42009-09-09 15:08:12 +00002938
Ted Kremenek821537e2008-05-06 02:41:27 +00002939 case RetEffect::ReceiverAlias: {
2940 assert (Receiver);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002941 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002942 state = state->BindExpr(Ex, V, false);
Ted Kremenek821537e2008-05-06 02:41:27 +00002943 break;
2944 }
Mike Stump11289f42009-09-09 15:08:12 +00002945
Ted Kremenekab4a8b52008-06-23 18:02:52 +00002946 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek68d73d12008-03-12 01:21:45 +00002947 case RetEffect::OwnedSymbol: {
2948 unsigned Count = Builder.getCurrentBlockCount();
Mike Stump11289f42009-09-09 15:08:12 +00002949 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00002950 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
Mike Stump11289f42009-09-09 15:08:12 +00002951 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002952 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00002953 RetT));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002954 state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek0b891a32009-03-09 22:46:49 +00002955
2956 // FIXME: Add a flag to the checker where allocations are assumed to
2957 // *not fail.
2958#if 0
Ted Kremenek2e561dd2009-01-28 22:27:59 +00002959 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2960 bool isFeasible;
2961 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
Mike Stump11289f42009-09-09 15:08:12 +00002962 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
Ted Kremenek2e561dd2009-01-28 22:27:59 +00002963 }
Ted Kremenek0b891a32009-03-09 22:46:49 +00002964#endif
Mike Stump11289f42009-09-09 15:08:12 +00002965
Ted Kremenek68d73d12008-03-12 01:21:45 +00002966 break;
2967 }
Mike Stump11289f42009-09-09 15:08:12 +00002968
Ted Kremeneke6633562009-04-27 19:14:45 +00002969 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek68d73d12008-03-12 01:21:45 +00002970 case RetEffect::NotOwnedSymbol: {
2971 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00002972 ValueManager &ValMgr = Eng.getValueManager();
2973 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
Mike Stump11289f42009-09-09 15:08:12 +00002974 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002975 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00002976 RetT));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002977 state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek68d73d12008-03-12 01:21:45 +00002978 break;
2979 }
2980 }
Mike Stump11289f42009-09-09 15:08:12 +00002981
Ted Kremenekd84fff62009-02-18 02:00:25 +00002982 // Generate a sink node if we are at the end of a path.
Zhongxing Xu107f7592009-08-06 12:48:26 +00002983 ExplodedNode *NewNode =
Ted Kremenekff606a12009-05-04 04:57:00 +00002984 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2985 : Builder.MakeNode(Dst, Ex, Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00002986
Ted Kremenekd84fff62009-02-18 02:00:25 +00002987 // Annotate the edge with summary we used.
Ted Kremenekff606a12009-05-04 04:57:00 +00002988 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenek00daccd2008-05-05 22:11:16 +00002989}
2990
2991
Zhongxing Xu20227f72009-08-06 01:32:16 +00002992void CFRefCount::EvalCall(ExplodedNodeSet& Dst,
Ted Kremenek00daccd2008-05-05 22:11:16 +00002993 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002994 GRStmtNodeBuilder& Builder,
Zhongxing Xu27f17422008-10-17 05:57:07 +00002995 CallExpr* CE, SVal L,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002996 ExplodedNode* Pred) {
Ted Kremeneke6a27802009-11-25 01:35:18 +00002997
2998 RetainSummary *Summ = 0;
2999
3000 // FIXME: Better support for blocks. For now we stop tracking anything
3001 // that is passed to blocks.
3002 // FIXME: Need to handle variables that are "captured" by the block.
Ted Kremenekb63ad7a2009-11-25 23:53:07 +00003003 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
Ted Kremeneke6a27802009-11-25 01:35:18 +00003004 Summ = Summaries.getPersistentStopSummary();
3005 }
3006 else {
3007 const FunctionDecl* FD = L.getAsFunctionDecl();
3008 Summ = !FD ? Summaries.getDefaultSummary() :
3009 Summaries.getSummary(const_cast<FunctionDecl*>(FD));
3010 }
Mike Stump11289f42009-09-09 15:08:12 +00003011
Ted Kremenekff606a12009-05-04 04:57:00 +00003012 assert(Summ);
3013 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Zhongxing Xuaf353292009-12-02 05:49:12 +00003014 CE->arg_begin(), CE->arg_end(), Pred, Builder.GetState(Pred));
Ted Kremenekea6507f2008-03-06 00:08:09 +00003015}
Ted Kremenek819e9b62008-03-11 06:39:11 +00003016
Zhongxing Xu20227f72009-08-06 01:32:16 +00003017void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003018 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003019 GRStmtNodeBuilder& Builder,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003020 ObjCMessageExpr* ME,
Zhongxing Xuaf353292009-12-02 05:49:12 +00003021 ExplodedNode* Pred,
3022 const GRState *state) {
Ted Kremeneka2968e52009-11-13 01:54:21 +00003023 RetainSummary *Summ =
3024 ME->getReceiver()
Zhongxing Xuaf353292009-12-02 05:49:12 +00003025 ? Summaries.getInstanceMethodSummary(ME, state,Pred->getLocationContext())
Ted Kremeneka2968e52009-11-13 01:54:21 +00003026 : Summaries.getClassMethodSummary(ME);
Mike Stump11289f42009-09-09 15:08:12 +00003027
Ted Kremeneka2968e52009-11-13 01:54:21 +00003028 assert(Summ && "RetainSummary is null");
Ted Kremenekff606a12009-05-04 04:57:00 +00003029 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Zhongxing Xuaf353292009-12-02 05:49:12 +00003030 ME->arg_begin(), ME->arg_end(), Pred, state);
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003031}
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003032
3033namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003034class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek89a303c2009-06-18 00:49:02 +00003035 const GRState *state;
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003036public:
Ted Kremenek89a303c2009-06-18 00:49:02 +00003037 StopTrackingCallback(const GRState *st) : state(st) {}
3038 const GRState *getState() const { return state; }
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003039
3040 bool VisitSymbol(SymbolRef sym) {
Ted Kremenek89a303c2009-06-18 00:49:02 +00003041 state = state->remove<RefBindings>(sym);
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003042 return true;
3043 }
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003044};
3045} // end anonymous namespace
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003046
Mike Stump11289f42009-09-09 15:08:12 +00003047
3048void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
3049 // Are we storing to something that causes the value to "escape"?
Ted Kremenek71454892008-04-16 20:40:59 +00003050 bool escapes = false;
Mike Stump11289f42009-09-09 15:08:12 +00003051
Ted Kremeneke86755e2008-10-18 03:49:51 +00003052 // A value escapes in three possible cases (this may change):
3053 //
3054 // (1) we are binding to something that is not a memory region.
3055 // (2) we are binding to a memregion that does not have stack storage
3056 // (3) we are binding to a memregion with stack storage that the store
Mike Stump11289f42009-09-09 15:08:12 +00003057 // does not understand.
Ted Kremenek89a303c2009-06-18 00:49:02 +00003058 const GRState *state = B.getState();
Ted Kremeneke86755e2008-10-18 03:49:51 +00003059
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003060 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek71454892008-04-16 20:40:59 +00003061 escapes = true;
Ted Kremenek5ca90a22008-10-04 05:50:14 +00003062 else {
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003063 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
Ted Kremenek404b1322009-06-23 18:05:21 +00003064 escapes = !R->hasStackStorage();
Mike Stump11289f42009-09-09 15:08:12 +00003065
Ted Kremeneke86755e2008-10-18 03:49:51 +00003066 if (!escapes) {
3067 // To test (3), generate a new state with the binding removed. If it is
3068 // the same state, then it escapes (since the store cannot represent
3069 // the binding).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003070 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneke86755e2008-10-18 03:49:51 +00003071 }
Ted Kremenek5ca90a22008-10-04 05:50:14 +00003072 }
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003073
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003074 // If our store can represent the binding and we aren't storing to something
3075 // that doesn't have local storage then just return and have the simulation
3076 // state continue as is.
3077 if (!escapes)
3078 return;
Ted Kremeneke86755e2008-10-18 03:49:51 +00003079
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003080 // Otherwise, find all symbols referenced by 'val' that we are tracking
3081 // and stop tracking them.
Ted Kremenek89a303c2009-06-18 00:49:02 +00003082 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekcbf4c612008-04-16 22:32:20 +00003083}
3084
Ted Kremeneka506fec2008-04-17 18:12:53 +00003085 // Return statements.
3086
Zhongxing Xu20227f72009-08-06 01:32:16 +00003087void CFRefCount::EvalReturn(ExplodedNodeSet& Dst,
Ted Kremeneka506fec2008-04-17 18:12:53 +00003088 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003089 GRStmtNodeBuilder& Builder,
Ted Kremeneka506fec2008-04-17 18:12:53 +00003090 ReturnStmt* S,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003091 ExplodedNode* Pred) {
Mike Stump11289f42009-09-09 15:08:12 +00003092
Ted Kremeneka506fec2008-04-17 18:12:53 +00003093 Expr* RetE = S->getRetValue();
Ted Kremenekc9747dd2009-03-03 22:06:47 +00003094 if (!RetE)
Ted Kremeneka506fec2008-04-17 18:12:53 +00003095 return;
Mike Stump11289f42009-09-09 15:08:12 +00003096
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003097 const GRState *state = Builder.GetState(Pred);
3098 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
Mike Stump11289f42009-09-09 15:08:12 +00003099
Ted Kremenek3e31c262009-03-26 03:35:11 +00003100 if (!Sym)
Ted Kremenekc9747dd2009-03-03 22:06:47 +00003101 return;
Mike Stump11289f42009-09-09 15:08:12 +00003102
Ted Kremeneka506fec2008-04-17 18:12:53 +00003103 // Get the reference count binding (if any).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003104 const RefVal* T = state->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00003105
Ted Kremeneka506fec2008-04-17 18:12:53 +00003106 if (!T)
3107 return;
Mike Stump11289f42009-09-09 15:08:12 +00003108
3109 // Change the reference count.
3110 RefVal X = *T;
3111
3112 switch (X.getKind()) {
3113 case RefVal::Owned: {
Ted Kremeneka506fec2008-04-17 18:12:53 +00003114 unsigned cnt = X.getCount();
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003115 assert (cnt > 0);
Ted Kremenek3978f792009-05-10 05:11:21 +00003116 X.setCount(cnt - 1);
3117 X = X ^ RefVal::ReturnedOwned;
Ted Kremeneka506fec2008-04-17 18:12:53 +00003118 break;
3119 }
Mike Stump11289f42009-09-09 15:08:12 +00003120
Ted Kremeneka506fec2008-04-17 18:12:53 +00003121 case RefVal::NotOwned: {
3122 unsigned cnt = X.getCount();
Ted Kremenek3978f792009-05-10 05:11:21 +00003123 if (cnt) {
3124 X.setCount(cnt - 1);
3125 X = X ^ RefVal::ReturnedOwned;
3126 }
3127 else {
3128 X = X ^ RefVal::ReturnedNotOwned;
3129 }
Ted Kremeneka506fec2008-04-17 18:12:53 +00003130 break;
3131 }
Mike Stump11289f42009-09-09 15:08:12 +00003132
3133 default:
Ted Kremeneka506fec2008-04-17 18:12:53 +00003134 return;
3135 }
Mike Stump11289f42009-09-09 15:08:12 +00003136
Ted Kremeneka506fec2008-04-17 18:12:53 +00003137 // Update the binding.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003138 state = state->set<RefBindings>(Sym, X);
Ted Kremenek6bd78702009-04-29 18:50:19 +00003139 Pred = Builder.MakeNode(Dst, S, Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00003140
Ted Kremenekb4e27a12009-04-30 05:51:50 +00003141 // Did we cache out?
3142 if (!Pred)
3143 return;
Mike Stump11289f42009-09-09 15:08:12 +00003144
Ted Kremenek3978f792009-05-10 05:11:21 +00003145 // Update the autorelease counts.
3146 static unsigned autoreleasetag = 0;
3147 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3148 bool stop = false;
3149 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3150 X, stop);
Mike Stump11289f42009-09-09 15:08:12 +00003151
Ted Kremenek3978f792009-05-10 05:11:21 +00003152 // Did we cache out?
3153 if (!Pred || stop)
3154 return;
Mike Stump11289f42009-09-09 15:08:12 +00003155
Ted Kremenek3978f792009-05-10 05:11:21 +00003156 // Get the updated binding.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003157 T = state->get<RefBindings>(Sym);
Ted Kremenek3978f792009-05-10 05:11:21 +00003158 assert(T);
3159 X = *T;
Mike Stump11289f42009-09-09 15:08:12 +00003160
Ted Kremenek6bd78702009-04-29 18:50:19 +00003161 // Any leaks or other errors?
3162 if (X.isReturnedOwned() && X.getCount() == 0) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00003163 Decl const *CD = &Pred->getCodeDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003164 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00003165 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekdee56e32009-05-10 06:25:57 +00003166 RetEffect RE = Summ.getRetEffect();
3167 bool hasError = false;
3168
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003169 if (RE.getKind() != RetEffect::NoRet) {
3170 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3171 // Things are more complicated with garbage collection. If the
3172 // returned object is suppose to be an Objective-C object, we have
3173 // a leak (as the caller expects a GC'ed object) because no
3174 // method should return ownership unless it returns a CF object.
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003175 hasError = true;
Ted Kremenek8070b822009-10-14 23:58:34 +00003176 X = X ^ RefVal::ErrorGCLeakReturned;
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003177 }
3178 else if (!RE.isOwned()) {
3179 // Either we are using GC and the returned object is a CF type
3180 // or we aren't using GC. In either case, we expect that the
Mike Stump11289f42009-09-09 15:08:12 +00003181 // enclosing method is expected to return ownership.
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003182 hasError = true;
3183 X = X ^ RefVal::ErrorLeakReturned;
3184 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00003185 }
Mike Stump11289f42009-09-09 15:08:12 +00003186
3187 if (hasError) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00003188 // Generate an error node.
Ted Kremenekdee56e32009-05-10 06:25:57 +00003189 static int ReturnOwnLeakTag = 0;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003190 state = state->set<RefBindings>(Sym, X);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003191 ExplodedNode *N =
Zhongxing Xue1190f72009-08-15 03:17:38 +00003192 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
3193 &ReturnOwnLeakTag), state, Pred);
Ted Kremenekdee56e32009-05-10 06:25:57 +00003194 if (N) {
3195 CFRefReport *report =
Ted Kremenekb4e27a12009-04-30 05:51:50 +00003196 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3197 N, Sym, Eng);
3198 BR->EmitReport(report);
3199 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00003200 }
Mike Stump11289f42009-09-09 15:08:12 +00003201 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00003202 }
3203 else if (X.isReturnedNotOwned()) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00003204 Decl const *CD = &Pred->getCodeDecl();
Ted Kremenekdee56e32009-05-10 06:25:57 +00003205 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3206 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3207 if (Summ.getRetEffect().isOwned()) {
3208 // Trying to return a not owned object to a caller expecting an
3209 // owned object.
Mike Stump11289f42009-09-09 15:08:12 +00003210
Ted Kremenekdee56e32009-05-10 06:25:57 +00003211 static int ReturnNotOwnedForOwnedTag = 0;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003212 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003213 if (ExplodedNode *N =
Zhongxing Xue1190f72009-08-15 03:17:38 +00003214 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
3215 &ReturnNotOwnedForOwnedTag),
3216 state, Pred)) {
Ted Kremenekdee56e32009-05-10 06:25:57 +00003217 CFRefReport *report =
3218 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3219 *this, N, Sym);
3220 BR->EmitReport(report);
3221 }
3222 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00003223 }
3224 }
Ted Kremeneka506fec2008-04-17 18:12:53 +00003225}
3226
Ted Kremenek4d837282008-04-18 19:23:43 +00003227// Assumptions.
3228
Ted Kremenekf9906842009-06-18 22:57:13 +00003229const GRState* CFRefCount::EvalAssume(const GRState *state,
3230 SVal Cond, bool Assumption) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003231
3232 // FIXME: We may add to the interface of EvalAssume the list of symbols
3233 // whose assumptions have changed. For now we just iterate through the
3234 // bindings and check if any of the tracked symbols are NULL. This isn't
Mike Stump11289f42009-09-09 15:08:12 +00003235 // too bad since the number of symbols we will track in practice are
Ted Kremenek4d837282008-04-18 19:23:43 +00003236 // probably small and EvalAssume is only called at branches and a few
3237 // other places.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003238 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003239
Ted Kremenek4d837282008-04-18 19:23:43 +00003240 if (B.isEmpty())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003241 return state;
Mike Stump11289f42009-09-09 15:08:12 +00003242
3243 bool changed = false;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003244 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
Ted Kremenek4d837282008-04-18 19:23:43 +00003245
Mike Stump11289f42009-09-09 15:08:12 +00003246 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003247 // Check if the symbol is null (or equal to any constant).
3248 // If this is the case, stop tracking the symbol.
Ted Kremenekf9906842009-06-18 22:57:13 +00003249 if (state->getSymVal(I.getKey())) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003250 changed = true;
3251 B = RefBFactory.Remove(B, I.getKey());
3252 }
3253 }
Mike Stump11289f42009-09-09 15:08:12 +00003254
Ted Kremenek87aab6c2008-08-17 03:20:02 +00003255 if (changed)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003256 state = state->set<RefBindings>(B);
Mike Stump11289f42009-09-09 15:08:12 +00003257
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00003258 return state;
Ted Kremenek4d837282008-04-18 19:23:43 +00003259}
Ted Kremenek819e9b62008-03-11 06:39:11 +00003260
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003261const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
Ted Kremenekc52f9392009-02-24 19:15:11 +00003262 RefVal V, ArgEffect E,
3263 RefVal::Kind& hasErr) {
Ted Kremenekf68490a2009-02-18 18:54:33 +00003264
3265 // In GC mode [... release] and [... retain] do nothing.
3266 switch (E) {
3267 default: break;
3268 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3269 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek10452892009-02-18 21:57:45 +00003270 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Mike Stump11289f42009-09-09 15:08:12 +00003271 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
Ted Kremenek50db3d02009-02-23 17:45:03 +00003272 NewAutoreleasePool; break;
Ted Kremenekf68490a2009-02-18 18:54:33 +00003273 }
Mike Stump11289f42009-09-09 15:08:12 +00003274
Ted Kremenekea072e32009-03-17 19:42:23 +00003275 // Handle all use-after-releases.
3276 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3277 V = V ^ RefVal::ErrorUseAfterRelease;
3278 hasErr = V.getKind();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003279 return state->set<RefBindings>(sym, V);
Mike Stump11289f42009-09-09 15:08:12 +00003280 }
3281
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003282 switch (E) {
3283 default:
3284 assert (false && "Unhandled CFRef transition.");
Mike Stump11289f42009-09-09 15:08:12 +00003285
Ted Kremenekea072e32009-03-17 19:42:23 +00003286 case Dealloc:
3287 // Any use of -dealloc in GC is *bad*.
3288 if (isGCEnabled()) {
3289 V = V ^ RefVal::ErrorDeallocGC;
3290 hasErr = V.getKind();
3291 break;
3292 }
Mike Stump11289f42009-09-09 15:08:12 +00003293
Ted Kremenekea072e32009-03-17 19:42:23 +00003294 switch (V.getKind()) {
3295 default:
3296 assert(false && "Invalid case.");
3297 case RefVal::Owned:
3298 // The object immediately transitions to the released state.
3299 V = V ^ RefVal::Released;
3300 V.clearCounts();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003301 return state->set<RefBindings>(sym, V);
Ted Kremenekea072e32009-03-17 19:42:23 +00003302 case RefVal::NotOwned:
3303 V = V ^ RefVal::ErrorDeallocNotOwned;
3304 hasErr = V.getKind();
3305 break;
Mike Stump11289f42009-09-09 15:08:12 +00003306 }
Ted Kremenekea072e32009-03-17 19:42:23 +00003307 break;
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003308
Ted Kremenek8ec8cf02009-02-25 23:11:49 +00003309 case NewAutoreleasePool:
3310 assert(!isGCEnabled());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003311 return state->add<AutoreleaseStack>(sym);
Mike Stump11289f42009-09-09 15:08:12 +00003312
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003313 case MayEscape:
3314 if (V.getKind() == RefVal::Owned) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003315 V = V ^ RefVal::NotOwned;
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003316 break;
3317 }
Ted Kremenekea072e32009-03-17 19:42:23 +00003318
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003319 // Fall-through.
Mike Stump11289f42009-09-09 15:08:12 +00003320
Ted Kremenekae529272008-07-09 18:11:16 +00003321 case DoNothingByRef:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003322 case DoNothing:
Ted Kremenekc52f9392009-02-24 19:15:11 +00003323 return state;
Ted Kremeneka0e071c2008-06-30 16:57:41 +00003324
Ted Kremenekc7832092009-01-28 21:44:40 +00003325 case Autorelease:
Ted Kremenekea072e32009-03-17 19:42:23 +00003326 if (isGCEnabled())
3327 return state;
Mike Stump11289f42009-09-09 15:08:12 +00003328
Ted Kremenek8c3f0042009-03-20 17:34:15 +00003329 // Update the autorelease counts.
3330 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek3a0516b2009-05-08 20:01:42 +00003331 V = V.autorelease();
Ted Kremenek2d0ff622009-05-09 01:50:57 +00003332 break;
Ted Kremenekd35272f2009-05-09 00:10:05 +00003333
Ted Kremenek821537e2008-05-06 02:41:27 +00003334 case StopTracking:
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003335 return state->remove<RefBindings>(sym);
Ted Kremenek050b91c2008-08-12 18:30:56 +00003336
Mike Stump11289f42009-09-09 15:08:12 +00003337 case IncRef:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003338 switch (V.getKind()) {
3339 default:
3340 assert(false);
3341
3342 case RefVal::Owned:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003343 case RefVal::NotOwned:
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003344 V = V + 1;
Mike Stump11289f42009-09-09 15:08:12 +00003345 break;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003346 case RefVal::Released:
Ted Kremenekea072e32009-03-17 19:42:23 +00003347 // Non-GC cases are handled above.
3348 assert(isGCEnabled());
3349 V = (V ^ RefVal::Owned) + 1;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003350 break;
Mike Stump11289f42009-09-09 15:08:12 +00003351 }
Ted Kremenek4b772092008-04-10 23:44:06 +00003352 break;
Mike Stump11289f42009-09-09 15:08:12 +00003353
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003354 case SelfOwn:
3355 V = V ^ RefVal::NotOwned;
Ted Kremenekf68490a2009-02-18 18:54:33 +00003356 // Fall-through.
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003357 case DecRef:
3358 switch (V.getKind()) {
3359 default:
Ted Kremenekea072e32009-03-17 19:42:23 +00003360 // case 'RefVal::Released' handled above.
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003361 assert (false);
Ted Kremenek050b91c2008-08-12 18:30:56 +00003362
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003363 case RefVal::Owned:
Ted Kremenek551747f2009-02-18 22:57:22 +00003364 assert(V.getCount() > 0);
3365 if (V.getCount() == 1) V = V ^ RefVal::Released;
3366 V = V - 1;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003367 break;
Mike Stump11289f42009-09-09 15:08:12 +00003368
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003369 case RefVal::NotOwned:
3370 if (V.getCount() > 0)
3371 V = V - 1;
Ted Kremenek3c03d522008-04-10 23:09:18 +00003372 else {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003373 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek8cb96e92008-04-16 04:28:53 +00003374 hasErr = V.getKind();
Mike Stump11289f42009-09-09 15:08:12 +00003375 }
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003376 break;
Mike Stump11289f42009-09-09 15:08:12 +00003377
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003378 case RefVal::Released:
Ted Kremenekea072e32009-03-17 19:42:23 +00003379 // Non-GC cases are handled above.
3380 assert(isGCEnabled());
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003381 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek8cb96e92008-04-16 04:28:53 +00003382 hasErr = V.getKind();
Mike Stump11289f42009-09-09 15:08:12 +00003383 break;
3384 }
Ted Kremenek4b772092008-04-10 23:44:06 +00003385 break;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003386 }
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003387 return state->set<RefBindings>(sym, V);
Ted Kremenek819e9b62008-03-11 06:39:11 +00003388}
3389
Ted Kremenekce8e8812008-04-09 01:10:13 +00003390//===----------------------------------------------------------------------===//
Ted Kremenek400aae72009-02-05 06:50:21 +00003391// Handle dead symbols and end-of-path.
3392//===----------------------------------------------------------------------===//
3393
Zhongxing Xu20227f72009-08-06 01:32:16 +00003394std::pair<ExplodedNode*, const GRState *>
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003395CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003396 ExplodedNode* Pred,
Ted Kremenekd35272f2009-05-09 00:10:05 +00003397 GRExprEngine &Eng,
3398 SymbolRef Sym, RefVal V, bool &stop) {
Mike Stump11289f42009-09-09 15:08:12 +00003399
Ted Kremenekd35272f2009-05-09 00:10:05 +00003400 unsigned ACnt = V.getAutoreleaseCount();
3401 stop = false;
3402
3403 // No autorelease counts? Nothing to be done.
3404 if (!ACnt)
3405 return std::make_pair(Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00003406
3407 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
Ted Kremenekd35272f2009-05-09 00:10:05 +00003408 unsigned Cnt = V.getCount();
Mike Stump11289f42009-09-09 15:08:12 +00003409
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003410 // FIXME: Handle sending 'autorelease' to already released object.
3411
3412 if (V.getKind() == RefVal::ReturnedOwned)
3413 ++Cnt;
Mike Stump11289f42009-09-09 15:08:12 +00003414
Ted Kremenekd35272f2009-05-09 00:10:05 +00003415 if (ACnt <= Cnt) {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003416 if (ACnt == Cnt) {
3417 V.clearCounts();
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003418 if (V.getKind() == RefVal::ReturnedOwned)
3419 V = V ^ RefVal::ReturnedNotOwned;
3420 else
3421 V = V ^ RefVal::NotOwned;
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003422 }
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003423 else {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003424 V.setCount(Cnt - ACnt);
3425 V.setAutoreleaseCount(0);
3426 }
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003427 state = state->set<RefBindings>(Sym, V);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003428 ExplodedNode *N = Bd.MakeNode(state, Pred);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003429 stop = (N == 0);
3430 return std::make_pair(N, state);
Mike Stump11289f42009-09-09 15:08:12 +00003431 }
Ted Kremenekd35272f2009-05-09 00:10:05 +00003432
3433 // Woah! More autorelease counts then retain counts left.
3434 // Emit hard error.
3435 stop = true;
3436 V = V ^ RefVal::ErrorOverAutorelease;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003437 state = state->set<RefBindings>(Sym, V);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003438
Zhongxing Xu20227f72009-08-06 01:32:16 +00003439 if (ExplodedNode *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003440 N->markAsSink();
Mike Stump11289f42009-09-09 15:08:12 +00003441
Ted Kremenek3978f792009-05-10 05:11:21 +00003442 std::string sbuf;
3443 llvm::raw_string_ostream os(sbuf);
Ted Kremenek4785e412009-05-15 06:02:08 +00003444 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenek3978f792009-05-10 05:11:21 +00003445 if (V.getAutoreleaseCount() > 1)
3446 os << V.getAutoreleaseCount() << " times";
3447 os << " but the object has ";
3448 if (V.getCount() == 0)
3449 os << "zero (locally visible)";
3450 else
3451 os << "+" << V.getCount();
3452 os << " retain counts";
Mike Stump11289f42009-09-09 15:08:12 +00003453
Ted Kremenekd35272f2009-05-09 00:10:05 +00003454 CFRefReport *report =
3455 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Benjamin Kramer63415532009-11-29 18:27:55 +00003456 *this, N, Sym, os.str());
Ted Kremenekd35272f2009-05-09 00:10:05 +00003457 BR->EmitReport(report);
3458 }
Mike Stump11289f42009-09-09 15:08:12 +00003459
Zhongxing Xu20227f72009-08-06 01:32:16 +00003460 return std::make_pair((ExplodedNode*)0, state);
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003461}
Ted Kremenek884a8992009-05-08 23:09:42 +00003462
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003463const GRState *
3464CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek884a8992009-05-08 23:09:42 +00003465 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
Mike Stump11289f42009-09-09 15:08:12 +00003466
3467 bool hasLeak = V.isOwned() ||
Ted Kremenek884a8992009-05-08 23:09:42 +00003468 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Mike Stump11289f42009-09-09 15:08:12 +00003469
Ted Kremenek884a8992009-05-08 23:09:42 +00003470 if (!hasLeak)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003471 return state->remove<RefBindings>(sid);
Mike Stump11289f42009-09-09 15:08:12 +00003472
Ted Kremenek884a8992009-05-08 23:09:42 +00003473 Leaked.push_back(sid);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003474 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
Ted Kremenek884a8992009-05-08 23:09:42 +00003475}
3476
Zhongxing Xu20227f72009-08-06 01:32:16 +00003477ExplodedNode*
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003478CFRefCount::ProcessLeaks(const GRState * state,
Ted Kremenek884a8992009-05-08 23:09:42 +00003479 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3480 GenericNodeBuilder &Builder,
3481 GRExprEngine& Eng,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003482 ExplodedNode *Pred) {
Mike Stump11289f42009-09-09 15:08:12 +00003483
Ted Kremenek884a8992009-05-08 23:09:42 +00003484 if (Leaked.empty())
3485 return Pred;
Mike Stump11289f42009-09-09 15:08:12 +00003486
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003487 // Generate an intermediate node representing the leak point.
Zhongxing Xu20227f72009-08-06 01:32:16 +00003488 ExplodedNode *N = Builder.MakeNode(state, Pred);
Mike Stump11289f42009-09-09 15:08:12 +00003489
Ted Kremenek884a8992009-05-08 23:09:42 +00003490 if (N) {
3491 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3492 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00003493
3494 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
Ted Kremenek884a8992009-05-08 23:09:42 +00003495 : leakAtReturn);
3496 assert(BT && "BugType not initialized.");
3497 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3498 BR->EmitReport(report);
3499 }
3500 }
Mike Stump11289f42009-09-09 15:08:12 +00003501
Ted Kremenek884a8992009-05-08 23:09:42 +00003502 return N;
3503}
3504
Ted Kremenek400aae72009-02-05 06:50:21 +00003505void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003506 GREndPathNodeBuilder& Builder) {
Mike Stump11289f42009-09-09 15:08:12 +00003507
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003508 const GRState *state = Builder.getState();
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003509 GenericNodeBuilder Bd(Builder);
Mike Stump11289f42009-09-09 15:08:12 +00003510 RefBindings B = state->get<RefBindings>();
Zhongxing Xu20227f72009-08-06 01:32:16 +00003511 ExplodedNode *Pred = 0;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003512
3513 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenekd35272f2009-05-09 00:10:05 +00003514 bool stop = false;
3515 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3516 (*I).first,
Mike Stump11289f42009-09-09 15:08:12 +00003517 (*I).second, stop);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003518
3519 if (stop)
3520 return;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003521 }
Mike Stump11289f42009-09-09 15:08:12 +00003522
3523 B = state->get<RefBindings>();
3524 llvm::SmallVector<SymbolRef, 10> Leaked;
3525
Ted Kremenek884a8992009-05-08 23:09:42 +00003526 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3527 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3528
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003529 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek400aae72009-02-05 06:50:21 +00003530}
3531
Zhongxing Xu20227f72009-08-06 01:32:16 +00003532void CFRefCount::EvalDeadSymbols(ExplodedNodeSet& Dst,
Ted Kremenek400aae72009-02-05 06:50:21 +00003533 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003534 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003535 ExplodedNode* Pred,
Ted Kremenek400aae72009-02-05 06:50:21 +00003536 Stmt* S,
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003537 const GRState* state,
Ted Kremenek400aae72009-02-05 06:50:21 +00003538 SymbolReaper& SymReaper) {
Ted Kremenek884a8992009-05-08 23:09:42 +00003539
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003540 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003541
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003542 // Update counts from autorelease pools
3543 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3544 E = SymReaper.dead_end(); I != E; ++I) {
3545 SymbolRef Sym = *I;
3546 if (const RefVal* T = B.lookup(Sym)){
3547 // Use the symbol as the tag.
3548 // FIXME: This might not be as unique as we would like.
3549 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003550 bool stop = false;
3551 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3552 Sym, *T, stop);
3553 if (stop)
3554 return;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003555 }
3556 }
Mike Stump11289f42009-09-09 15:08:12 +00003557
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003558 B = state->get<RefBindings>();
Ted Kremenek884a8992009-05-08 23:09:42 +00003559 llvm::SmallVector<SymbolRef, 10> Leaked;
Mike Stump11289f42009-09-09 15:08:12 +00003560
Ted Kremenek400aae72009-02-05 06:50:21 +00003561 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00003562 E = SymReaper.dead_end(); I != E; ++I) {
Ted Kremenek884a8992009-05-08 23:09:42 +00003563 if (const RefVal* T = B.lookup(*I))
3564 state = HandleSymbolDeath(state, *I, *T, Leaked);
Mike Stump11289f42009-09-09 15:08:12 +00003565 }
3566
Ted Kremenek884a8992009-05-08 23:09:42 +00003567 static unsigned LeakPPTag = 0;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003568 {
3569 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3570 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3571 }
Mike Stump11289f42009-09-09 15:08:12 +00003572
Ted Kremenek884a8992009-05-08 23:09:42 +00003573 // Did we cache out?
3574 if (!Pred)
3575 return;
Mike Stump11289f42009-09-09 15:08:12 +00003576
Ted Kremenek68abaa92009-02-19 23:47:02 +00003577 // Now generate a new node that nukes the old bindings.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003578 RefBindings::Factory& F = state->get_context<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003579
Ted Kremenek68abaa92009-02-19 23:47:02 +00003580 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek884a8992009-05-08 23:09:42 +00003581 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
Mike Stump11289f42009-09-09 15:08:12 +00003582
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003583 state = state->set<RefBindings>(B);
Ted Kremenek68abaa92009-02-19 23:47:02 +00003584 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek400aae72009-02-05 06:50:21 +00003585}
3586
Zhongxing Xu20227f72009-08-06 01:32:16 +00003587void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003588 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003589 Expr* NodeExpr, Expr* ErrorExpr,
3590 ExplodedNode* Pred,
Ted Kremenek400aae72009-02-05 06:50:21 +00003591 const GRState* St,
3592 RefVal::Kind hasErr, SymbolRef Sym) {
3593 Builder.BuildSinks = true;
Zhongxing Xu107f7592009-08-06 12:48:26 +00003594 ExplodedNode *N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
Mike Stump11289f42009-09-09 15:08:12 +00003595
Ted Kremenek2d0ff622009-05-09 01:50:57 +00003596 if (!N)
3597 return;
Mike Stump11289f42009-09-09 15:08:12 +00003598
Ted Kremenek400aae72009-02-05 06:50:21 +00003599 CFRefBug *BT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003600
Ted Kremenekea072e32009-03-17 19:42:23 +00003601 switch (hasErr) {
3602 default:
3603 assert(false && "Unhandled error.");
3604 return;
3605 case RefVal::ErrorUseAfterRelease:
3606 BT = static_cast<CFRefBug*>(useAfterRelease);
Mike Stump11289f42009-09-09 15:08:12 +00003607 break;
Ted Kremenekea072e32009-03-17 19:42:23 +00003608 case RefVal::ErrorReleaseNotOwned:
3609 BT = static_cast<CFRefBug*>(releaseNotOwned);
3610 break;
3611 case RefVal::ErrorDeallocGC:
3612 BT = static_cast<CFRefBug*>(deallocGC);
3613 break;
3614 case RefVal::ErrorDeallocNotOwned:
3615 BT = static_cast<CFRefBug*>(deallocNotOwned);
3616 break;
Ted Kremenek400aae72009-02-05 06:50:21 +00003617 }
Mike Stump11289f42009-09-09 15:08:12 +00003618
Ted Kremenek48d16452009-02-18 03:48:14 +00003619 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek400aae72009-02-05 06:50:21 +00003620 report->addRange(ErrorExpr->getSourceRange());
3621 BR->EmitReport(report);
3622}
3623
3624//===----------------------------------------------------------------------===//
Ted Kremenek70a87882009-11-25 22:17:44 +00003625// Pieces of the retain/release checker implemented using a CheckerVisitor.
3626// More pieces of the retain/release checker will be migrated to this interface
3627// (ideally, all of it some day).
3628//===----------------------------------------------------------------------===//
3629
3630namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003631class RetainReleaseChecker
Ted Kremenek70a87882009-11-25 22:17:44 +00003632 : public CheckerVisitor<RetainReleaseChecker> {
3633 CFRefCount *TF;
3634public:
3635 RetainReleaseChecker(CFRefCount *tf) : TF(tf) {}
Ted Kremenekf89dcda2009-11-26 02:38:19 +00003636 static void* getTag() { static int x = 0; return &x; }
3637
3638 void PostVisitBlockExpr(CheckerContext &C, const BlockExpr *BE);
Ted Kremenek70a87882009-11-25 22:17:44 +00003639};
3640} // end anonymous namespace
3641
Ted Kremenekf89dcda2009-11-26 02:38:19 +00003642
3643void RetainReleaseChecker::PostVisitBlockExpr(CheckerContext &C,
3644 const BlockExpr *BE) {
3645
3646 // Scan the BlockDecRefExprs for any object the retain/release checker
3647 // may be tracking.
3648 if (!BE->hasBlockDeclRefExprs())
3649 return;
3650
3651 const GRState *state = C.getState();
3652 const BlockDataRegion *R =
3653 cast<BlockDataRegion>(state->getSVal(BE).getAsRegion());
3654
3655 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
3656 E = R->referenced_vars_end();
3657
3658 if (I == E)
3659 return;
3660
3661 state = state->scanReachableSymbols<StopTrackingCallback>(I, E).getState();
3662 C.addTransition(state);
3663}
3664
Ted Kremenek70a87882009-11-25 22:17:44 +00003665//===----------------------------------------------------------------------===//
Ted Kremenek4a78c3a2008-04-10 22:16:52 +00003666// Transfer function creation for external clients.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003667//===----------------------------------------------------------------------===//
3668
Ted Kremenek9454227942009-11-25 22:08:49 +00003669void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
3670 BugReporter &BR = Eng.getBugReporter();
3671
3672 useAfterRelease = new UseAfterRelease(this);
3673 BR.Register(useAfterRelease);
3674
3675 releaseNotOwned = new BadRelease(this);
3676 BR.Register(releaseNotOwned);
3677
3678 deallocGC = new DeallocGC(this);
3679 BR.Register(deallocGC);
3680
3681 deallocNotOwned = new DeallocNotOwned(this);
3682 BR.Register(deallocNotOwned);
3683
3684 overAutorelease = new OverAutorelease(this);
3685 BR.Register(overAutorelease);
3686
3687 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
3688 BR.Register(returnNotOwnedForOwned);
3689
3690 // First register "return" leaks.
3691 const char* name = 0;
3692
3693 if (isGCEnabled())
3694 name = "Leak of returned object when using garbage collection";
3695 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
3696 name = "Leak of returned object when not using garbage collection (GC) in "
3697 "dual GC/non-GC code";
3698 else {
3699 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
3700 name = "Leak of returned object";
3701 }
3702
3703 // Leaks should not be reported if they are post-dominated by a sink.
3704 leakAtReturn = new LeakAtReturn(this, name);
3705 leakAtReturn->setSuppressOnSink(true);
3706 BR.Register(leakAtReturn);
3707
3708 // Second, register leaks within a function/method.
3709 if (isGCEnabled())
3710 name = "Leak of object when using garbage collection";
3711 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
3712 name = "Leak of object when not using garbage collection (GC) in "
3713 "dual GC/non-GC code";
3714 else {
3715 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
3716 name = "Leak";
3717 }
3718
3719 // Leaks should not be reported if they are post-dominated by sinks.
3720 leakWithinFunction = new LeakWithinFunction(this, name);
3721 leakWithinFunction->setSuppressOnSink(true);
3722 BR.Register(leakWithinFunction);
3723
3724 // Save the reference to the BugReporter.
3725 this->BR = &BR;
Ted Kremenek70a87882009-11-25 22:17:44 +00003726
3727 // Register the RetainReleaseChecker with the GRExprEngine object.
3728 // Functionality in CFRefCount will be migrated to RetainReleaseChecker
3729 // over time.
3730 Eng.registerCheck(new RetainReleaseChecker(this));
Ted Kremenek9454227942009-11-25 22:08:49 +00003731}
3732
Ted Kremenekb0f87c42008-04-30 23:47:44 +00003733GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3734 const LangOptions& lopts) {
Ted Kremenek1f352db2008-07-22 16:21:24 +00003735 return new CFRefCount(Ctx, GCEnabled, lopts);
Mike Stump11289f42009-09-09 15:08:12 +00003736}