blob: 10d07762dbf1d86b2cb9d3d51a7682c8fb6f4dfb [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 Kremenek819e9b62008-03-11 06:39:11 +000027#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/FoldingSet.h"
29#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek0747e7e2008-10-21 15:53:15 +000030#include "llvm/ADT/ImmutableList.h"
Ted Kremenekb6cbf282008-05-07 18:36:45 +000031#include "llvm/ADT/StringExtras.h"
Ted Kremenekce8e8812008-04-09 01:10:13 +000032#include "llvm/Support/Compiler.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 {
172class VISIBILITY_HIDDEN 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.
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000250class VISIBILITY_HIDDEN 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
Ted Kremeneka2968e52009-11-13 01:54:21 +0000316class VISIBILITY_HIDDEN RefVal {
317public:
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 {
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000540class VISIBILITY_HIDDEN 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 {
631class VISIBILITY_HIDDEN ObjCSummaryKey {
632 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 {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000686class VISIBILITY_HIDDEN ObjCSummaryCache {
687 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 {
780class VISIBILITY_HIDDEN 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
Ted Kremenekc52f9392009-02-24 19:15:11 +00001869namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenekdce78462009-02-25 02:54:57 +00001870namespace { class VISIBILITY_HIDDEN 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
Ted Kremenek1642bda2009-06-26 00:05:51 +00001912class VISIBILITY_HIDDEN 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 Xu20227f72009-08-06 01:32:16 +00001988 ExplodedNode* Pred);
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 Xu20227f72009-08-06 01:32:16 +00002001 ExplodedNode* Pred);
Mike Stump11289f42009-09-09 15:08:12 +00002002
Zhongxing Xu20227f72009-08-06 01:32:16 +00002003 bool EvalObjCMessageExprAux(ExplodedNodeSet& Dst,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002004 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002005 GRStmtNodeBuilder& Builder,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002006 ObjCMessageExpr* ME,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002007 ExplodedNode* Pred);
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002008
Mike Stump11289f42009-09-09 15:08:12 +00002009 // Stores.
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00002010 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
2011
Ted Kremenek8784a7c2008-04-11 22:25:11 +00002012 // End-of-path.
Mike Stump11289f42009-09-09 15:08:12 +00002013
Ted Kremenek8784a7c2008-04-11 22:25:11 +00002014 virtual void EvalEndPath(GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002015 GREndPathNodeBuilder& Builder);
Mike Stump11289f42009-09-09 15:08:12 +00002016
Zhongxing Xu20227f72009-08-06 01:32:16 +00002017 virtual void EvalDeadSymbols(ExplodedNodeSet& Dst,
Ted Kremenekb0daf2f2008-04-24 23:57:27 +00002018 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002019 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002020 ExplodedNode* Pred,
Ted Kremenek16fbfe62009-01-21 22:26:05 +00002021 Stmt* S, const GRState* state,
2022 SymbolReaper& SymReaper);
Mike Stump11289f42009-09-09 15:08:12 +00002023
Zhongxing Xu20227f72009-08-06 01:32:16 +00002024 std::pair<ExplodedNode*, const GRState *>
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002025 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002026 ExplodedNode* Pred, GRExprEngine &Eng,
Ted Kremenekd35272f2009-05-09 00:10:05 +00002027 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremeneka506fec2008-04-17 18:12:53 +00002028 // Return statements.
Mike Stump11289f42009-09-09 15:08:12 +00002029
Zhongxing Xu20227f72009-08-06 01:32:16 +00002030 virtual void EvalReturn(ExplodedNodeSet& Dst,
Ted Kremeneka506fec2008-04-17 18:12:53 +00002031 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002032 GRStmtNodeBuilder& Builder,
Ted Kremeneka506fec2008-04-17 18:12:53 +00002033 ReturnStmt* S,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002034 ExplodedNode* Pred);
Ted Kremenek4d837282008-04-18 19:23:43 +00002035
2036 // Assumptions.
2037
Ted Kremenekf9906842009-06-18 22:57:13 +00002038 virtual const GRState *EvalAssume(const GRState* state, SVal condition,
2039 bool assumption);
Ted Kremenek819e9b62008-03-11 06:39:11 +00002040};
2041
2042} // end anonymous namespace
2043
Ted Kremenek799bb6e2009-06-24 23:06:47 +00002044static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym,
2045 const GRState *state) {
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002046 Out << ' ';
Ted Kremenek3e31c262009-03-26 03:35:11 +00002047 if (Sym)
2048 Out << Sym->getSymbolID();
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002049 else
2050 Out << "<pool>";
2051 Out << ":{";
Mike Stump11289f42009-09-09 15:08:12 +00002052
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002053 // Get the contents of the pool.
2054 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
2055 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
2056 Out << '(' << J.getKey() << ',' << J.getData() << ')';
2057
Mike Stump11289f42009-09-09 15:08:12 +00002058 Out << '}';
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002059}
Ted Kremenek396f4362008-04-18 03:39:05 +00002060
Ted Kremenek799bb6e2009-06-24 23:06:47 +00002061void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out,
2062 const GRState* state,
Ted Kremenek16306102008-08-13 21:24:49 +00002063 const char* nl, const char* sep) {
Mike Stump11289f42009-09-09 15:08:12 +00002064
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00002065 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00002066
Ted Kremenek16306102008-08-13 21:24:49 +00002067 if (!B.isEmpty())
Ted Kremenek2a723e62008-03-11 19:44:10 +00002068 Out << sep << nl;
Mike Stump11289f42009-09-09 15:08:12 +00002069
Ted Kremenek2a723e62008-03-11 19:44:10 +00002070 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
2071 Out << (*I).first << " : ";
2072 (*I).second.print(Out);
2073 Out << nl;
2074 }
Mike Stump11289f42009-09-09 15:08:12 +00002075
Ted Kremenekdce78462009-02-25 02:54:57 +00002076 // Print the autorelease stack.
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002077 Out << sep << nl << "AR pool stack:";
Ted Kremenekdce78462009-02-25 02:54:57 +00002078 ARStack stack = state->get<AutoreleaseStack>();
Mike Stump11289f42009-09-09 15:08:12 +00002079
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002080 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
2081 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
2082 PrintPool(Out, *I, state);
2083
2084 Out << nl;
Ted Kremenek2a723e62008-03-11 19:44:10 +00002085}
2086
Ted Kremenek6bd78702009-04-29 18:50:19 +00002087//===----------------------------------------------------------------------===//
2088// Error reporting.
2089//===----------------------------------------------------------------------===//
2090
2091namespace {
Mike Stump11289f42009-09-09 15:08:12 +00002092
Ted Kremenek6bd78702009-04-29 18:50:19 +00002093 //===-------------===//
2094 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00002095 //===-------------===//
2096
Ted Kremenek6bd78702009-04-29 18:50:19 +00002097 class VISIBILITY_HIDDEN CFRefBug : public BugType {
2098 protected:
2099 CFRefCount& TF;
Mike Stump11289f42009-09-09 15:08:12 +00002100
2101 CFRefBug(CFRefCount* tf, const char* name)
2102 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek6bd78702009-04-29 18:50:19 +00002103 public:
Mike Stump11289f42009-09-09 15:08:12 +00002104
Ted Kremenek6bd78702009-04-29 18:50:19 +00002105 CFRefCount& getTF() { return TF; }
2106 const CFRefCount& getTF() const { return TF; }
Mike Stump11289f42009-09-09 15:08:12 +00002107
Ted Kremenek6bd78702009-04-29 18:50:19 +00002108 // FIXME: Eventually remove.
2109 virtual const char* getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002110
Ted Kremenek6bd78702009-04-29 18:50:19 +00002111 virtual bool isLeak() const { return false; }
2112 };
Mike Stump11289f42009-09-09 15:08:12 +00002113
Ted Kremenek6bd78702009-04-29 18:50:19 +00002114 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2115 public:
2116 UseAfterRelease(CFRefCount* tf)
2117 : CFRefBug(tf, "Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00002118
Ted Kremenek6bd78702009-04-29 18:50:19 +00002119 const char* getDescription() const {
2120 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00002121 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002122 };
Mike Stump11289f42009-09-09 15:08:12 +00002123
Ted Kremenek6bd78702009-04-29 18:50:19 +00002124 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2125 public:
2126 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00002127
Ted Kremenek6bd78702009-04-29 18:50:19 +00002128 const char* getDescription() const {
Ted Kremenek5c22e112009-10-01 17:31:50 +00002129 return "Incorrect decrement of the reference count of an object that is "
2130 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002131 }
2132 };
Mike Stump11289f42009-09-09 15:08:12 +00002133
Ted Kremenek6bd78702009-04-29 18:50:19 +00002134 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2135 public:
Ted Kremenekd35272f2009-05-09 00:10:05 +00002136 DeallocGC(CFRefCount *tf)
2137 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00002138
Ted Kremenek6bd78702009-04-29 18:50:19 +00002139 const char *getDescription() const {
Ted Kremenekd35272f2009-05-09 00:10:05 +00002140 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002141 }
2142 };
Mike Stump11289f42009-09-09 15:08:12 +00002143
Ted Kremenek6bd78702009-04-29 18:50:19 +00002144 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2145 public:
Ted Kremenekd35272f2009-05-09 00:10:05 +00002146 DeallocNotOwned(CFRefCount *tf)
2147 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00002148
Ted Kremenek6bd78702009-04-29 18:50:19 +00002149 const char *getDescription() const {
2150 return "-dealloc sent to object that may be referenced elsewhere";
2151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152 };
2153
Ted Kremenekd35272f2009-05-09 00:10:05 +00002154 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
2155 public:
Mike Stump11289f42009-09-09 15:08:12 +00002156 OverAutorelease(CFRefCount *tf) :
Ted Kremenekd35272f2009-05-09 00:10:05 +00002157 CFRefBug(tf, "Object sent -autorelease too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00002158
Ted Kremenekd35272f2009-05-09 00:10:05 +00002159 const char *getDescription() const {
Ted Kremenek3978f792009-05-10 05:11:21 +00002160 return "Object sent -autorelease too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00002161 }
2162 };
Mike Stump11289f42009-09-09 15:08:12 +00002163
Ted Kremenekdee56e32009-05-10 06:25:57 +00002164 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
2165 public:
2166 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2167 CFRefBug(tf, "Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00002168
Ted Kremenekdee56e32009-05-10 06:25:57 +00002169 const char *getDescription() const {
2170 return "Object with +0 retain counts returned to caller where a +1 "
2171 "(owning) retain count is expected";
2172 }
2173 };
Mike Stump11289f42009-09-09 15:08:12 +00002174
Ted Kremenek6bd78702009-04-29 18:50:19 +00002175 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2176 const bool isReturn;
2177 protected:
2178 Leak(CFRefCount* tf, const char* name, bool isRet)
2179 : CFRefBug(tf, name), isReturn(isRet) {}
2180 public:
Mike Stump11289f42009-09-09 15:08:12 +00002181
Ted Kremenek6bd78702009-04-29 18:50:19 +00002182 const char* getDescription() const { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Ted Kremenek6bd78702009-04-29 18:50:19 +00002184 bool isLeak() const { return true; }
2185 };
Mike Stump11289f42009-09-09 15:08:12 +00002186
Ted Kremenek6bd78702009-04-29 18:50:19 +00002187 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2188 public:
2189 LeakAtReturn(CFRefCount* tf, const char* name)
2190 : Leak(tf, name, true) {}
2191 };
Mike Stump11289f42009-09-09 15:08:12 +00002192
Ted Kremenek6bd78702009-04-29 18:50:19 +00002193 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2194 public:
2195 LeakWithinFunction(CFRefCount* tf, const char* name)
2196 : Leak(tf, name, false) {}
Mike Stump11289f42009-09-09 15:08:12 +00002197 };
2198
Ted Kremenek6bd78702009-04-29 18:50:19 +00002199 //===---------===//
2200 // Bug Reports. //
2201 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00002202
Ted Kremenek6bd78702009-04-29 18:50:19 +00002203 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2204 protected:
2205 SymbolRef Sym;
2206 const CFRefCount &TF;
2207 public:
2208 CFRefReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002209 ExplodedNode *n, SymbolRef sym)
Ted Kremenek3978f792009-05-10 05:11:21 +00002210 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2211
2212 CFRefReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002213 ExplodedNode *n, SymbolRef sym, const char* endText)
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002214 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Mike Stump11289f42009-09-09 15:08:12 +00002215
Ted Kremenek6bd78702009-04-29 18:50:19 +00002216 virtual ~CFRefReport() {}
Mike Stump11289f42009-09-09 15:08:12 +00002217
Ted Kremenek6bd78702009-04-29 18:50:19 +00002218 CFRefBug& getBugType() {
2219 return (CFRefBug&) RangedBugReport::getBugType();
2220 }
2221 const CFRefBug& getBugType() const {
2222 return (const CFRefBug&) RangedBugReport::getBugType();
2223 }
Mike Stump11289f42009-09-09 15:08:12 +00002224
Zhongxing Xu7864b9ea2009-08-18 08:58:41 +00002225 virtual void getRanges(const SourceRange*& beg, const SourceRange*& end) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002226 if (!getBugType().isLeak())
Zhongxing Xu7864b9ea2009-08-18 08:58:41 +00002227 RangedBugReport::getRanges(beg, end);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002228 else
2229 beg = end = 0;
2230 }
Mike Stump11289f42009-09-09 15:08:12 +00002231
Ted Kremenek6bd78702009-04-29 18:50:19 +00002232 SymbolRef getSymbol() const { return Sym; }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002234 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002235 const ExplodedNode* N);
Mike Stump11289f42009-09-09 15:08:12 +00002236
Ted Kremenek6bd78702009-04-29 18:50:19 +00002237 std::pair<const char**,const char**> getExtraDescriptiveText();
Mike Stump11289f42009-09-09 15:08:12 +00002238
Zhongxing Xu20227f72009-08-06 01:32:16 +00002239 PathDiagnosticPiece* VisitNode(const ExplodedNode* N,
2240 const ExplodedNode* PrevN,
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002241 BugReporterContext& BRC);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002242 };
Ted Kremenek3978f792009-05-10 05:11:21 +00002243
Ted Kremenek6bd78702009-04-29 18:50:19 +00002244 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2245 SourceLocation AllocSite;
2246 const MemRegion* AllocBinding;
2247 public:
2248 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002249 ExplodedNode *n, SymbolRef sym,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002250 GRExprEngine& Eng);
Mike Stump11289f42009-09-09 15:08:12 +00002251
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002252 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002253 const ExplodedNode* N);
Mike Stump11289f42009-09-09 15:08:12 +00002254
Ted Kremenek6bd78702009-04-29 18:50:19 +00002255 SourceLocation getLocation() const { return AllocSite; }
Mike Stump11289f42009-09-09 15:08:12 +00002256 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00002257} // end anonymous namespace
2258
Mike Stump11289f42009-09-09 15:08:12 +00002259
Ted Kremenek6bd78702009-04-29 18:50:19 +00002260
2261static const char* Msgs[] = {
2262 // GC only
Mike Stump11289f42009-09-09 15:08:12 +00002263 "Code is compiled to only use garbage collection",
Ted Kremenek6bd78702009-04-29 18:50:19 +00002264 // No GC.
2265 "Code is compiled to use reference counts",
2266 // Hybrid, with GC.
2267 "Code is compiled to use either garbage collection (GC) or reference counts"
Mike Stump11289f42009-09-09 15:08:12 +00002268 " (non-GC). The bug occurs with GC enabled",
Ted Kremenek6bd78702009-04-29 18:50:19 +00002269 // Hybrid, without GC
2270 "Code is compiled to use either garbage collection (GC) or reference counts"
2271 " (non-GC). The bug occurs in non-GC mode"
2272};
2273
2274std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2275 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
Mike Stump11289f42009-09-09 15:08:12 +00002276
Ted Kremenek6bd78702009-04-29 18:50:19 +00002277 switch (TF.getLangOptions().getGCMode()) {
2278 default:
2279 assert(false);
Mike Stump11289f42009-09-09 15:08:12 +00002280
Ted Kremenek6bd78702009-04-29 18:50:19 +00002281 case LangOptions::GCOnly:
2282 assert (TF.isGCEnabled());
Mike Stump11289f42009-09-09 15:08:12 +00002283 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2284
Ted Kremenek6bd78702009-04-29 18:50:19 +00002285 case LangOptions::NonGC:
2286 assert (!TF.isGCEnabled());
2287 return std::make_pair(&Msgs[1], &Msgs[1]+1);
Mike Stump11289f42009-09-09 15:08:12 +00002288
Ted Kremenek6bd78702009-04-29 18:50:19 +00002289 case LangOptions::HybridGC:
2290 if (TF.isGCEnabled())
2291 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2292 else
2293 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2294 }
2295}
2296
2297static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2298 ArgEffect X) {
2299 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2300 I!=E; ++I)
2301 if (*I == X) return true;
Mike Stump11289f42009-09-09 15:08:12 +00002302
Ted Kremenek6bd78702009-04-29 18:50:19 +00002303 return false;
2304}
2305
Zhongxing Xu20227f72009-08-06 01:32:16 +00002306PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N,
2307 const ExplodedNode* PrevN,
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002308 BugReporterContext& BRC) {
Mike Stump11289f42009-09-09 15:08:12 +00002309
Ted Kremenek051a03d2009-05-13 07:12:33 +00002310 if (!isa<PostStmt>(N->getLocation()))
2311 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002312
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002313 // Check if the type state has changed.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002314 const GRState *PrevSt = PrevN->getState();
2315 const GRState *CurrSt = N->getState();
Mike Stump11289f42009-09-09 15:08:12 +00002316
2317 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002318 if (!CurrT) return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002319
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002320 const RefVal &CurrV = *CurrT;
2321 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002322
Ted Kremenek6bd78702009-04-29 18:50:19 +00002323 // Create a string buffer to constain all the useful things we want
2324 // to tell the user.
2325 std::string sbuf;
2326 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002327
Ted Kremenek6bd78702009-04-29 18:50:19 +00002328 // This is the allocation site since the previous node had no bindings
2329 // for this symbol.
2330 if (!PrevT) {
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002331 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002332
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002333 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002334 // Get the name of the callee (if it is available).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002335 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002336 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2337 os << "Call to function '" << FD->getNameAsString() <<'\'';
2338 else
Mike Stump11289f42009-09-09 15:08:12 +00002339 os << "function call";
2340 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002341 else {
2342 assert (isa<ObjCMessageExpr>(S));
2343 os << "Method";
2344 }
Mike Stump11289f42009-09-09 15:08:12 +00002345
Ted Kremenek6bd78702009-04-29 18:50:19 +00002346 if (CurrV.getObjKind() == RetEffect::CF) {
2347 os << " returns a Core Foundation object with a ";
2348 }
2349 else {
2350 assert (CurrV.getObjKind() == RetEffect::ObjC);
2351 os << " returns an Objective-C object with a ";
2352 }
Mike Stump11289f42009-09-09 15:08:12 +00002353
Ted Kremenek6bd78702009-04-29 18:50:19 +00002354 if (CurrV.isOwned()) {
2355 os << "+1 retain count (owning reference).";
Mike Stump11289f42009-09-09 15:08:12 +00002356
Ted Kremenek6bd78702009-04-29 18:50:19 +00002357 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2358 assert(CurrV.getObjKind() == RetEffect::CF);
2359 os << " "
2360 "Core Foundation objects are not automatically garbage collected.";
2361 }
2362 }
2363 else {
2364 assert (CurrV.isNotOwned());
2365 os << "+0 retain count (non-owning reference).";
2366 }
Mike Stump11289f42009-09-09 15:08:12 +00002367
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002368 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002369 return new PathDiagnosticEventPiece(Pos, os.str());
2370 }
Mike Stump11289f42009-09-09 15:08:12 +00002371
Ted Kremenek6bd78702009-04-29 18:50:19 +00002372 // Gather up the effects that were performed on the object at this
2373 // program point
2374 llvm::SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00002375
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002376 if (const RetainSummary *Summ =
2377 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002378 // We only have summaries attached to nodes after evaluating CallExpr and
2379 // ObjCMessageExprs.
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002380 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002381
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002382 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002383 // Iterate through the parameter expressions and see if the symbol
2384 // was ever passed as an argument.
2385 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002386
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002387 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002388 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002389
Ted Kremenek6bd78702009-04-29 18:50:19 +00002390 // Retrieve the value of the argument. Is it the symbol
2391 // we are interested in?
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002392 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002393 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002394
Ted Kremenek6bd78702009-04-29 18:50:19 +00002395 // We have an argument. Get the effect!
2396 AEffects.push_back(Summ->getArg(i));
2397 }
2398 }
Mike Stump11289f42009-09-09 15:08:12 +00002399 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002400 if (const Expr *receiver = ME->getReceiver())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002401 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002402 // The symbol we are tracking is the receiver.
2403 AEffects.push_back(Summ->getReceiverEffect());
2404 }
2405 }
2406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
Ted Kremenek6bd78702009-04-29 18:50:19 +00002408 do {
2409 // Get the previous type state.
2410 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00002411
Ted Kremenek6bd78702009-04-29 18:50:19 +00002412 // Specially handle -dealloc.
2413 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2414 // Determine if the object's reference count was pushed to zero.
2415 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2416 // We may not have transitioned to 'release' if we hit an error.
2417 // This case is handled elsewhere.
2418 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002419 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002420 os << "Object released by directly sending the '-dealloc' message";
2421 break;
2422 }
2423 }
Mike Stump11289f42009-09-09 15:08:12 +00002424
Ted Kremenek6bd78702009-04-29 18:50:19 +00002425 // Specially handle CFMakeCollectable and friends.
2426 if (contains(AEffects, MakeCollectable)) {
2427 // Get the name of the function.
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002428 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002429 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002430 const FunctionDecl* FD = X.getAsFunctionDecl();
2431 const std::string& FName = FD->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00002432
Ted Kremenek6bd78702009-04-29 18:50:19 +00002433 if (TF.isGCEnabled()) {
2434 // Determine if the object's reference count was pushed to zero.
2435 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00002436
Ted Kremenek6bd78702009-04-29 18:50:19 +00002437 os << "In GC mode a call to '" << FName
2438 << "' decrements an object's retain count and registers the "
2439 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00002440
Ted Kremenek6bd78702009-04-29 18:50:19 +00002441 if (CurrV.getKind() == RefVal::Released) {
2442 assert(CurrV.getCount() == 0);
2443 os << "Since it now has a 0 retain count the object can be "
2444 "automatically collected by the garbage collector.";
2445 }
2446 else
2447 os << "An object must have a 0 retain count to be garbage collected. "
2448 "After this call its retain count is +" << CurrV.getCount()
2449 << '.';
2450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451 else
Ted Kremenek6bd78702009-04-29 18:50:19 +00002452 os << "When GC is not enabled a call to '" << FName
2453 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00002454
Ted Kremenek6bd78702009-04-29 18:50:19 +00002455 // Nothing more to say.
2456 break;
2457 }
Mike Stump11289f42009-09-09 15:08:12 +00002458
2459 // Determine if the typestate has changed.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002460 if (!(PrevV == CurrV))
2461 switch (CurrV.getKind()) {
2462 case RefVal::Owned:
2463 case RefVal::NotOwned:
Mike Stump11289f42009-09-09 15:08:12 +00002464
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002465 if (PrevV.getCount() == CurrV.getCount()) {
2466 // Did an autorelease message get sent?
2467 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2468 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002469
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002470 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenek3978f792009-05-10 05:11:21 +00002471 os << "Object sent -autorelease message";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002472 break;
2473 }
Mike Stump11289f42009-09-09 15:08:12 +00002474
Ted Kremenek6bd78702009-04-29 18:50:19 +00002475 if (PrevV.getCount() > CurrV.getCount())
2476 os << "Reference count decremented.";
2477 else
2478 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00002479
Ted Kremenek6bd78702009-04-29 18:50:19 +00002480 if (unsigned Count = CurrV.getCount())
2481 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00002482
Ted Kremenek6bd78702009-04-29 18:50:19 +00002483 if (PrevV.getKind() == RefVal::Released) {
2484 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2485 os << " The object is not eligible for garbage collection until the "
2486 "retain count reaches 0 again.";
2487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Ted Kremenek6bd78702009-04-29 18:50:19 +00002489 break;
Mike Stump11289f42009-09-09 15:08:12 +00002490
Ted Kremenek6bd78702009-04-29 18:50:19 +00002491 case RefVal::Released:
2492 os << "Object released.";
2493 break;
Mike Stump11289f42009-09-09 15:08:12 +00002494
Ted Kremenek6bd78702009-04-29 18:50:19 +00002495 case RefVal::ReturnedOwned:
2496 os << "Object returned to caller as an owning reference (single retain "
2497 "count transferred to caller).";
2498 break;
Mike Stump11289f42009-09-09 15:08:12 +00002499
Ted Kremenek6bd78702009-04-29 18:50:19 +00002500 case RefVal::ReturnedNotOwned:
2501 os << "Object returned to caller with a +0 (non-owning) retain count.";
2502 break;
Mike Stump11289f42009-09-09 15:08:12 +00002503
Ted Kremenek6bd78702009-04-29 18:50:19 +00002504 default:
2505 return NULL;
2506 }
Mike Stump11289f42009-09-09 15:08:12 +00002507
Ted Kremenek6bd78702009-04-29 18:50:19 +00002508 // Emit any remaining diagnostics for the argument effects (if any).
2509 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2510 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002511
Ted Kremenek6bd78702009-04-29 18:50:19 +00002512 // A bunch of things have alternate behavior under GC.
2513 if (TF.isGCEnabled())
2514 switch (*I) {
2515 default: break;
2516 case Autorelease:
2517 os << "In GC mode an 'autorelease' has no effect.";
2518 continue;
2519 case IncRefMsg:
2520 os << "In GC mode the 'retain' message has no effect.";
2521 continue;
2522 case DecRefMsg:
2523 os << "In GC mode the 'release' message has no effect.";
2524 continue;
2525 }
2526 }
Mike Stump11289f42009-09-09 15:08:12 +00002527 } while (0);
2528
Ted Kremenek6bd78702009-04-29 18:50:19 +00002529 if (os.str().empty())
2530 return 0; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002531
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002532 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002533 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002534 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002535
Ted Kremenek6bd78702009-04-29 18:50:19 +00002536 // Add the range by scanning the children of the statement for any bindings
2537 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002538 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002539 I!=E; ++I)
2540 if (const Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002541 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002542 P->addRange(Exp->getSourceRange());
2543 break;
2544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
Ted Kremenek6bd78702009-04-29 18:50:19 +00002546 return P;
2547}
2548
2549namespace {
2550 class VISIBILITY_HIDDEN FindUniqueBinding :
2551 public StoreManager::BindingsHandler {
2552 SymbolRef Sym;
2553 const MemRegion* Binding;
2554 bool First;
Mike Stump11289f42009-09-09 15:08:12 +00002555
Ted Kremenek6bd78702009-04-29 18:50:19 +00002556 public:
2557 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Mike Stump11289f42009-09-09 15:08:12 +00002558
Ted Kremenek6bd78702009-04-29 18:50:19 +00002559 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2560 SVal val) {
Mike Stump11289f42009-09-09 15:08:12 +00002561
2562 SymbolRef SymV = val.getAsSymbol();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002563 if (!SymV || SymV != Sym)
2564 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002565
Ted Kremenek6bd78702009-04-29 18:50:19 +00002566 if (Binding) {
2567 First = false;
2568 return false;
2569 }
2570 else
2571 Binding = R;
Mike Stump11289f42009-09-09 15:08:12 +00002572
2573 return true;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002574 }
Mike Stump11289f42009-09-09 15:08:12 +00002575
Ted Kremenek6bd78702009-04-29 18:50:19 +00002576 operator bool() { return First && Binding; }
2577 const MemRegion* getRegion() { return Binding; }
Mike Stump11289f42009-09-09 15:08:12 +00002578 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00002579}
2580
Zhongxing Xu20227f72009-08-06 01:32:16 +00002581static std::pair<const ExplodedNode*,const MemRegion*>
2582GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode* N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002583 SymbolRef Sym) {
Mike Stump11289f42009-09-09 15:08:12 +00002584
Ted Kremenek6bd78702009-04-29 18:50:19 +00002585 // Find both first node that referred to the tracked symbol and the
2586 // memory location that value was store to.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002587 const ExplodedNode* Last = N;
Mike Stump11289f42009-09-09 15:08:12 +00002588 const MemRegion* FirstBinding = 0;
2589
Ted Kremenek6bd78702009-04-29 18:50:19 +00002590 while (N) {
2591 const GRState* St = N->getState();
2592 RefBindings B = St->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00002593
Ted Kremenek6bd78702009-04-29 18:50:19 +00002594 if (!B.lookup(Sym))
2595 break;
Mike Stump11289f42009-09-09 15:08:12 +00002596
Ted Kremenek6bd78702009-04-29 18:50:19 +00002597 FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002598 StateMgr.iterBindings(St, FB);
2599 if (FB) FirstBinding = FB.getRegion();
2600
Ted Kremenek6bd78702009-04-29 18:50:19 +00002601 Last = N;
Mike Stump11289f42009-09-09 15:08:12 +00002602 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002603 }
Mike Stump11289f42009-09-09 15:08:12 +00002604
Ted Kremenek6bd78702009-04-29 18:50:19 +00002605 return std::make_pair(Last, FirstBinding);
2606}
2607
2608PathDiagnosticPiece*
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002609CFRefReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002610 const ExplodedNode* EndN) {
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002611 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002612 // assigned to different variables, etc.
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002613 BRC.addNotableSymbol(Sym);
2614 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002615}
2616
2617PathDiagnosticPiece*
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002618CFRefLeakReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002619 const ExplodedNode* EndN){
Mike Stump11289f42009-09-09 15:08:12 +00002620
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002621 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002622 // assigned to different variables, etc.
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002623 BRC.addNotableSymbol(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002624
Ted Kremenek6bd78702009-04-29 18:50:19 +00002625 // We are reporting a leak. Walk up the graph to get to the first node where
2626 // the symbol appeared, and also get the first VarDecl that tracked object
2627 // is stored to.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002628 const ExplodedNode* AllocNode = 0;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002629 const MemRegion* FirstBinding = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002630
Ted Kremenek6bd78702009-04-29 18:50:19 +00002631 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002632 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002633
2634 // Get the allocate site.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002635 assert(AllocNode);
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002636 const Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002637
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002638 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002639 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002640
Ted Kremenek6bd78702009-04-29 18:50:19 +00002641 // Compute an actual location for the leak. Sometimes a leak doesn't
2642 // occur at an actual statement (e.g., transition between blocks; end
2643 // of function) so we need to walk the graph and compute a real location.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002644 const ExplodedNode* LeakN = EndN;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002645 PathDiagnosticLocation L;
Mike Stump11289f42009-09-09 15:08:12 +00002646
Ted Kremenek6bd78702009-04-29 18:50:19 +00002647 while (LeakN) {
2648 ProgramPoint P = LeakN->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00002649
Ted Kremenek6bd78702009-04-29 18:50:19 +00002650 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2651 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2652 break;
2653 }
2654 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2655 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2656 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2657 break;
2658 }
2659 }
Mike Stump11289f42009-09-09 15:08:12 +00002660
Ted Kremenek6bd78702009-04-29 18:50:19 +00002661 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2662 }
Mike Stump11289f42009-09-09 15:08:12 +00002663
Ted Kremenek6bd78702009-04-29 18:50:19 +00002664 if (!L.isValid()) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002665 const Decl &D = EndN->getCodeDecl();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002666 L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002667 }
Mike Stump11289f42009-09-09 15:08:12 +00002668
Ted Kremenek6bd78702009-04-29 18:50:19 +00002669 std::string sbuf;
2670 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002671
Ted Kremenek6bd78702009-04-29 18:50:19 +00002672 os << "Object allocated on line " << AllocLine;
Mike Stump11289f42009-09-09 15:08:12 +00002673
Ted Kremenek6bd78702009-04-29 18:50:19 +00002674 if (FirstBinding)
Mike Stump11289f42009-09-09 15:08:12 +00002675 os << " and stored into '" << FirstBinding->getString() << '\'';
2676
Ted Kremenek6bd78702009-04-29 18:50:19 +00002677 // Get the retain count.
2678 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002679
Ted Kremenek6bd78702009-04-29 18:50:19 +00002680 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2681 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2682 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2683 // to the caller for NS objects.
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002684 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002685 os << " is returned from a method whose name ('"
Ted Kremenek223a7d52009-04-29 23:03:22 +00002686 << MD.getSelector().getAsString()
Ted Kremenek6bd78702009-04-29 18:50:19 +00002687 << "') does not contain 'copy' or otherwise starts with"
2688 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenekd6bef2e2009-04-29 22:25:52 +00002689 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002690 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002691 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002692 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002693 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002694 << "' is potentially leaked when using garbage collection. Callers "
2695 "of this method do not expect a returned object with a +1 retain "
2696 "count since they expect the object to be managed by the garbage "
2697 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002698 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002699 else
2700 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenekd6bef2e2009-04-29 22:25:52 +00002701 " +" << RV->getCount() << " (object leaked)";
Mike Stump11289f42009-09-09 15:08:12 +00002702
Ted Kremenek6bd78702009-04-29 18:50:19 +00002703 return new PathDiagnosticEventPiece(L, os.str());
2704}
2705
Ted Kremenek6bd78702009-04-29 18:50:19 +00002706CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002707 ExplodedNode *n,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002708 SymbolRef sym, GRExprEngine& Eng)
Mike Stump11289f42009-09-09 15:08:12 +00002709: CFRefReport(D, tf, n, sym) {
2710
Ted Kremenek6bd78702009-04-29 18:50:19 +00002711 // Most bug reports are cached at the location where they occured.
2712 // With leaks, we want to unique them by the location where they were
2713 // allocated, and only report a single path. To do this, we need to find
2714 // the allocation site of a piece of tracked memory, which we do via a
2715 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2716 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2717 // that all ancestor nodes that represent the allocation site have the
2718 // same SourceLocation.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002719 const ExplodedNode* AllocNode = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002720
Ted Kremenek6bd78702009-04-29 18:50:19 +00002721 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002722 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Mike Stump11289f42009-09-09 15:08:12 +00002723
Ted Kremenek6bd78702009-04-29 18:50:19 +00002724 // Get the SourceLocation for the allocation site.
2725 ProgramPoint P = AllocNode->getLocation();
2726 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00002727
Ted Kremenek6bd78702009-04-29 18:50:19 +00002728 // Fill in the description of the bug.
2729 Description.clear();
2730 llvm::raw_string_ostream os(Description);
2731 SourceManager& SMgr = Eng.getContext().getSourceManager();
2732 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002733 os << "Potential leak ";
2734 if (tf.isGCEnabled()) {
2735 os << "(when using garbage collection) ";
Mike Stump11289f42009-09-09 15:08:12 +00002736 }
Ted Kremenekf1e76672009-05-02 19:05:19 +00002737 os << "of an object allocated on line " << AllocLine;
Mike Stump11289f42009-09-09 15:08:12 +00002738
Ted Kremenek6bd78702009-04-29 18:50:19 +00002739 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2740 if (AllocBinding)
2741 os << " and stored into '" << AllocBinding->getString() << '\'';
2742}
2743
2744//===----------------------------------------------------------------------===//
2745// Main checker logic.
2746//===----------------------------------------------------------------------===//
2747
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002748/// GetReturnType - Used to get the return type of a message expression or
2749/// function call with the intention of affixing that type to a tracked symbol.
2750/// While the the return type can be queried directly from RetEx, when
2751/// invoking class methods we augment to the return type to be that of
2752/// a pointer to the class (as opposed it just being id).
Steve Naroff7cae42b2009-07-10 23:34:53 +00002753static QualType GetReturnType(const Expr* RetE, ASTContext& Ctx) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002754 QualType RetTy = RetE->getType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002755 // If RetE is not a message expression just return its type.
2756 // If RetE is a message expression, return its types if it is something
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002757 /// more specific than id.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002758 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
John McCall9dd450b2009-09-21 23:43:11 +00002759 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002760 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002761 PT->isObjCClassType()) {
2762 // At this point we know the return type of the message expression is
2763 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2764 // is a call to a class method whose type we can resolve. In such
2765 // cases, promote the return type to XXX* (where XXX is the class).
Mike Stump11289f42009-09-09 15:08:12 +00002766 const ObjCInterfaceDecl *D = ME->getClassInfo().first;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002767 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2768 }
Mike Stump11289f42009-09-09 15:08:12 +00002769
Steve Naroff7cae42b2009-07-10 23:34:53 +00002770 return RetTy;
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002771}
2772
Zhongxing Xu20227f72009-08-06 01:32:16 +00002773void CFRefCount::EvalSummary(ExplodedNodeSet& Dst,
Ted Kremenek00daccd2008-05-05 22:11:16 +00002774 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002775 GRStmtNodeBuilder& Builder,
Ted Kremenek00daccd2008-05-05 22:11:16 +00002776 Expr* Ex,
2777 Expr* Receiver,
Ted Kremenekff606a12009-05-04 04:57:00 +00002778 const RetainSummary& Summ,
Zhongxing Xuac129432009-04-20 05:24:46 +00002779 ExprIterator arg_beg, ExprIterator arg_end,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002780 ExplodedNode* Pred) {
Mike Stump11289f42009-09-09 15:08:12 +00002781
Ted Kremenek819e9b62008-03-11 06:39:11 +00002782 // Get the state.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002783 const GRState *state = Builder.GetState(Pred);
Ted Kremenek821537e2008-05-06 02:41:27 +00002784
2785 // Evaluate the effect of the arguments.
Ted Kremenek8cb96e92008-04-16 04:28:53 +00002786 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek68d73d12008-03-12 01:21:45 +00002787 unsigned idx = 0;
Ted Kremenek988990f2008-04-11 18:40:51 +00002788 Expr* ErrorExpr = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002789 SymbolRef ErrorSym = 0;
2790
2791 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
2792 SVal V = state->getSValAsScalarOrLoc(*I);
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002793 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek804fc232009-03-04 00:13:50 +00002794
Ted Kremenek3e31c262009-03-26 03:35:11 +00002795 if (Sym)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002796 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002797 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekc52f9392009-02-24 19:15:11 +00002798 if (hasErr) {
Ted Kremenek988990f2008-04-11 18:40:51 +00002799 ErrorExpr = *I;
Ted Kremenek4963d112008-07-07 16:21:19 +00002800 ErrorSym = Sym;
Ted Kremenek988990f2008-04-11 18:40:51 +00002801 break;
Mike Stump11289f42009-09-09 15:08:12 +00002802 }
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002803 continue;
Ted Kremenekc52f9392009-02-24 19:15:11 +00002804 }
Ted Kremenekae529272008-07-09 18:11:16 +00002805
Ted Kremenekf9539d02009-09-22 04:48:39 +00002806 tryAgain:
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002807 if (isa<Loc>(V)) {
2808 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002809 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekae529272008-07-09 18:11:16 +00002810 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002811
2812 // Invalidate the value of the variable passed by reference.
2813
Ted Kremenek4d851462008-07-03 23:26:32 +00002814 // FIXME: We can have collisions on the conjured symbol if the
2815 // expression *I also creates conjured symbols. We probably want
2816 // to identify conjured symbols by an expression pair: the enclosing
2817 // expression (the context) and the expression itself. This should
Mike Stump11289f42009-09-09 15:08:12 +00002818 // disambiguate conjured symbols.
Zhongxing Xu4744d562009-06-29 06:43:40 +00002819 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002820 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
Ted Kremenek97f75f82009-05-11 22:55:17 +00002821
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002822 const MemRegion *R = MR->getRegion();
2823 // Are we dealing with an ElementRegion? If the element type is
2824 // a basic integer type (e.g., char, int) and the underying region
2825 // is a variable region then strip off the ElementRegion.
2826 // FIXME: We really need to think about this for the general case
2827 // as sometimes we are reasoning about arrays and other times
2828 // about (char*), etc., is just a form of passing raw bytes.
2829 // e.g., void *p = alloca(); foo((char*)p);
2830 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2831 // Checking for 'integral type' is probably too promiscuous, but
2832 // we'll leave it in for now until we have a systematic way of
2833 // handling all of these cases. Eventually we need to come up
2834 // with an interface to StoreManager so that this logic can be
2835 // approriately delegated to the respective StoreManagers while
2836 // still allowing us to do checker-specific logic (e.g.,
2837 // invalidating reference counts), probably via callbacks.
2838 if (ER->getElementType()->isIntegralType()) {
2839 const MemRegion *superReg = ER->getSuperRegion();
2840 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2841 isa<ObjCIvarRegion>(superReg))
2842 R = cast<TypedRegion>(superReg);
Ted Kremenek0626df42009-05-06 18:19:24 +00002843 }
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002844 // FIXME: What about layers of ElementRegions?
2845 }
Zhongxing Xu4744d562009-06-29 06:43:40 +00002846
Ted Kremenek1eb68092009-10-16 00:30:49 +00002847 StoreManager::InvalidatedSymbols IS;
2848 state = StoreMgr.InvalidateRegion(state, R, *I, Count, &IS);
2849 for (StoreManager::InvalidatedSymbols::iterator I = IS.begin(),
2850 E = IS.end(); I!=E; ++I) {
2851 // Remove any existing reference-count binding.
2852 state = state->remove<RefBindings>(*I);
2853 }
Ted Kremenek4d851462008-07-03 23:26:32 +00002854 }
2855 else {
2856 // Nuke all other arguments passed by reference.
Ted Kremenekf9539d02009-09-22 04:48:39 +00002857 // FIXME: is this necessary or correct? This handles the non-Region
2858 // cases. Is it ever valid to store to these?
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002859 state = state->unbindLoc(cast<Loc>(V));
Ted Kremenek4d851462008-07-03 23:26:32 +00002860 }
Ted Kremenek0a86fdb2008-04-11 20:51:02 +00002861 }
Ted Kremenekf9539d02009-09-22 04:48:39 +00002862 else if (isa<nonloc::LocAsInteger>(V)) {
2863 // If we are passing a location wrapped as an integer, unwrap it and
2864 // invalidate the values referred by the location.
2865 V = cast<nonloc::LocAsInteger>(V).getLoc();
2866 goto tryAgain;
2867 }
Mike Stump11289f42009-09-09 15:08:12 +00002868 }
2869
2870 // Evaluate the effect on the message receiver.
Ted Kremenek821537e2008-05-06 02:41:27 +00002871 if (!ErrorExpr && Receiver) {
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002872 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek3e31c262009-03-26 03:35:11 +00002873 if (Sym) {
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002874 if (const RefVal* T = state->get<RefBindings>(Sym)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002875 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekc52f9392009-02-24 19:15:11 +00002876 if (hasErr) {
Ted Kremenek821537e2008-05-06 02:41:27 +00002877 ErrorExpr = Receiver;
Ted Kremenek4963d112008-07-07 16:21:19 +00002878 ErrorSym = Sym;
Ted Kremenek821537e2008-05-06 02:41:27 +00002879 }
Ted Kremenekc52f9392009-02-24 19:15:11 +00002880 }
Ted Kremenek821537e2008-05-06 02:41:27 +00002881 }
2882 }
Mike Stump11289f42009-09-09 15:08:12 +00002883
2884 // Process any errors.
Ted Kremenek8cb96e92008-04-16 04:28:53 +00002885 if (hasErr) {
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00002886 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek396f4362008-04-18 03:39:05 +00002887 hasErr, ErrorSym);
Ted Kremenek68d73d12008-03-12 01:21:45 +00002888 return;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00002889 }
Mike Stump11289f42009-09-09 15:08:12 +00002890
2891 // Consult the summary for the return value.
Ted Kremenekff606a12009-05-04 04:57:00 +00002892 RetEffect RE = Summ.getRetEffect();
Mike Stump11289f42009-09-09 15:08:12 +00002893
Ted Kremenek1272f702009-05-12 20:06:54 +00002894 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2895 assert(Receiver);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002896 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek1272f702009-05-12 20:06:54 +00002897 bool found = false;
2898 if (SymbolRef Sym = V.getAsLocSymbol())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002899 if (state->get<RefBindings>(Sym)) {
Ted Kremenek1272f702009-05-12 20:06:54 +00002900 found = true;
2901 RE = Summaries.getObjAllocRetEffect();
2902 }
2903
2904 if (!found)
2905 RE = RetEffect::MakeNoRet();
Mike Stump11289f42009-09-09 15:08:12 +00002906 }
2907
Ted Kremenek68d73d12008-03-12 01:21:45 +00002908 switch (RE.getKind()) {
2909 default:
2910 assert (false && "Unhandled RetEffect."); break;
Mike Stump11289f42009-09-09 15:08:12 +00002911
2912 case RetEffect::NoRet: {
Ted Kremenek831f3272008-04-11 20:23:24 +00002913 // Make up a symbol for the return value (not reference counted).
Ted Kremenek1642bda2009-06-26 00:05:51 +00002914 // FIXME: Most of this logic is not specific to the retain/release
2915 // checker.
Mike Stump11289f42009-09-09 15:08:12 +00002916
Ted Kremenek21387322008-10-17 22:23:12 +00002917 // FIXME: We eventually should handle structs and other compound types
2918 // that are returned by value.
Mike Stump11289f42009-09-09 15:08:12 +00002919
Ted Kremenek21387322008-10-17 22:23:12 +00002920 QualType T = Ex->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002921
Ted Kremenek16866d62008-11-13 06:10:40 +00002922 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek831f3272008-04-11 20:23:24 +00002923 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekf2489ea2009-04-09 22:22:44 +00002924 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremeneke41b81e2009-09-27 20:45:21 +00002925 SVal X = ValMgr.getConjuredSymbolVal(NULL, Ex, T, Count);
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002926 state = state->BindExpr(Ex, X, false);
Mike Stump11289f42009-09-09 15:08:12 +00002927 }
2928
Ted Kremenek4b772092008-04-10 23:44:06 +00002929 break;
Ted Kremenek21387322008-10-17 22:23:12 +00002930 }
Mike Stump11289f42009-09-09 15:08:12 +00002931
Ted Kremenek68d73d12008-03-12 01:21:45 +00002932 case RetEffect::Alias: {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002933 unsigned idx = RE.getIndex();
Ted Kremenek08e17112008-06-17 02:43:46 +00002934 assert (arg_end >= arg_beg);
Ted Kremenek00daccd2008-05-05 22:11:16 +00002935 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002936 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002937 state = state->BindExpr(Ex, V, false);
Ted Kremenek68d73d12008-03-12 01:21:45 +00002938 break;
2939 }
Mike Stump11289f42009-09-09 15:08:12 +00002940
Ted Kremenek821537e2008-05-06 02:41:27 +00002941 case RetEffect::ReceiverAlias: {
2942 assert (Receiver);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002943 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002944 state = state->BindExpr(Ex, V, false);
Ted Kremenek821537e2008-05-06 02:41:27 +00002945 break;
2946 }
Mike Stump11289f42009-09-09 15:08:12 +00002947
Ted Kremenekab4a8b52008-06-23 18:02:52 +00002948 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek68d73d12008-03-12 01:21:45 +00002949 case RetEffect::OwnedSymbol: {
2950 unsigned Count = Builder.getCurrentBlockCount();
Mike Stump11289f42009-09-09 15:08:12 +00002951 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00002952 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
Mike Stump11289f42009-09-09 15:08:12 +00002953 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002954 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00002955 RetT));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002956 state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek0b891a32009-03-09 22:46:49 +00002957
2958 // FIXME: Add a flag to the checker where allocations are assumed to
2959 // *not fail.
2960#if 0
Ted Kremenek2e561dd2009-01-28 22:27:59 +00002961 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2962 bool isFeasible;
2963 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
Mike Stump11289f42009-09-09 15:08:12 +00002964 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
Ted Kremenek2e561dd2009-01-28 22:27:59 +00002965 }
Ted Kremenek0b891a32009-03-09 22:46:49 +00002966#endif
Mike Stump11289f42009-09-09 15:08:12 +00002967
Ted Kremenek68d73d12008-03-12 01:21:45 +00002968 break;
2969 }
Mike Stump11289f42009-09-09 15:08:12 +00002970
Ted Kremeneke6633562009-04-27 19:14:45 +00002971 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek68d73d12008-03-12 01:21:45 +00002972 case RetEffect::NotOwnedSymbol: {
2973 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00002974 ValueManager &ValMgr = Eng.getValueManager();
2975 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
Mike Stump11289f42009-09-09 15:08:12 +00002976 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002977 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00002978 RetT));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002979 state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek68d73d12008-03-12 01:21:45 +00002980 break;
2981 }
2982 }
Mike Stump11289f42009-09-09 15:08:12 +00002983
Ted Kremenekd84fff62009-02-18 02:00:25 +00002984 // Generate a sink node if we are at the end of a path.
Zhongxing Xu107f7592009-08-06 12:48:26 +00002985 ExplodedNode *NewNode =
Ted Kremenekff606a12009-05-04 04:57:00 +00002986 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2987 : Builder.MakeNode(Dst, Ex, Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00002988
Ted Kremenekd84fff62009-02-18 02:00:25 +00002989 // Annotate the edge with summary we used.
Ted Kremenekff606a12009-05-04 04:57:00 +00002990 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenek00daccd2008-05-05 22:11:16 +00002991}
2992
2993
Zhongxing Xu20227f72009-08-06 01:32:16 +00002994void CFRefCount::EvalCall(ExplodedNodeSet& Dst,
Ted Kremenek00daccd2008-05-05 22:11:16 +00002995 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002996 GRStmtNodeBuilder& Builder,
Zhongxing Xu27f17422008-10-17 05:57:07 +00002997 CallExpr* CE, SVal L,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002998 ExplodedNode* Pred) {
Ted Kremeneke6a27802009-11-25 01:35:18 +00002999
3000 RetainSummary *Summ = 0;
3001
3002 // FIXME: Better support for blocks. For now we stop tracking anything
3003 // that is passed to blocks.
3004 // FIXME: Need to handle variables that are "captured" by the block.
3005 if (dyn_cast_or_null<BlockTextRegion>(L.getAsRegion())) {
3006 Summ = Summaries.getPersistentStopSummary();
3007 }
3008 else {
3009 const FunctionDecl* FD = L.getAsFunctionDecl();
3010 Summ = !FD ? Summaries.getDefaultSummary() :
3011 Summaries.getSummary(const_cast<FunctionDecl*>(FD));
3012 }
Mike Stump11289f42009-09-09 15:08:12 +00003013
Ted Kremenekff606a12009-05-04 04:57:00 +00003014 assert(Summ);
3015 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenek00daccd2008-05-05 22:11:16 +00003016 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenekea6507f2008-03-06 00:08:09 +00003017}
Ted Kremenek819e9b62008-03-11 06:39:11 +00003018
Zhongxing Xu20227f72009-08-06 01:32:16 +00003019void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003020 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003021 GRStmtNodeBuilder& Builder,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003022 ObjCMessageExpr* ME,
Mike Stump11289f42009-09-09 15:08:12 +00003023 ExplodedNode* Pred) {
Zhongxing Xu9e200792009-11-24 07:06:39 +00003024 // FIXME: Since we moved the nil check into a checker, we could get nil
3025 // receiver here. Need a better way to check such case.
3026 if (Expr* Receiver = ME->getReceiver()) {
3027 const GRState *state = Pred->getState();
3028 DefinedOrUnknownSVal L=cast<DefinedOrUnknownSVal>(state->getSVal(Receiver));
3029 if (!state->Assume(L, true)) {
3030 Dst.Add(Pred);
3031 return;
3032 }
3033 }
Ted Kremeneka2968e52009-11-13 01:54:21 +00003034
3035 RetainSummary *Summ =
3036 ME->getReceiver()
3037 ? Summaries.getInstanceMethodSummary(ME, Builder.GetState(Pred),
3038 Pred->getLocationContext())
3039 : Summaries.getClassMethodSummary(ME);
Mike Stump11289f42009-09-09 15:08:12 +00003040
Ted Kremeneka2968e52009-11-13 01:54:21 +00003041 assert(Summ && "RetainSummary is null");
Ted Kremenekff606a12009-05-04 04:57:00 +00003042 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek015c3562008-05-06 04:20:12 +00003043 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003044}
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003045
3046namespace {
3047class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
Ted Kremenek89a303c2009-06-18 00:49:02 +00003048 const GRState *state;
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003049public:
Ted Kremenek89a303c2009-06-18 00:49:02 +00003050 StopTrackingCallback(const GRState *st) : state(st) {}
3051 const GRState *getState() const { return state; }
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003052
3053 bool VisitSymbol(SymbolRef sym) {
Ted Kremenek89a303c2009-06-18 00:49:02 +00003054 state = state->remove<RefBindings>(sym);
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003055 return true;
3056 }
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003057};
3058} // end anonymous namespace
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003059
Mike Stump11289f42009-09-09 15:08:12 +00003060
3061void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
3062 // Are we storing to something that causes the value to "escape"?
Ted Kremenek71454892008-04-16 20:40:59 +00003063 bool escapes = false;
Mike Stump11289f42009-09-09 15:08:12 +00003064
Ted Kremeneke86755e2008-10-18 03:49:51 +00003065 // A value escapes in three possible cases (this may change):
3066 //
3067 // (1) we are binding to something that is not a memory region.
3068 // (2) we are binding to a memregion that does not have stack storage
3069 // (3) we are binding to a memregion with stack storage that the store
Mike Stump11289f42009-09-09 15:08:12 +00003070 // does not understand.
Ted Kremenek89a303c2009-06-18 00:49:02 +00003071 const GRState *state = B.getState();
Ted Kremeneke86755e2008-10-18 03:49:51 +00003072
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003073 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek71454892008-04-16 20:40:59 +00003074 escapes = true;
Ted Kremenek5ca90a22008-10-04 05:50:14 +00003075 else {
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003076 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
Ted Kremenek404b1322009-06-23 18:05:21 +00003077 escapes = !R->hasStackStorage();
Mike Stump11289f42009-09-09 15:08:12 +00003078
Ted Kremeneke86755e2008-10-18 03:49:51 +00003079 if (!escapes) {
3080 // To test (3), generate a new state with the binding removed. If it is
3081 // the same state, then it escapes (since the store cannot represent
3082 // the binding).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003083 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneke86755e2008-10-18 03:49:51 +00003084 }
Ted Kremenek5ca90a22008-10-04 05:50:14 +00003085 }
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003086
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003087 // If our store can represent the binding and we aren't storing to something
3088 // that doesn't have local storage then just return and have the simulation
3089 // state continue as is.
3090 if (!escapes)
3091 return;
Ted Kremeneke86755e2008-10-18 03:49:51 +00003092
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003093 // Otherwise, find all symbols referenced by 'val' that we are tracking
3094 // and stop tracking them.
Ted Kremenek89a303c2009-06-18 00:49:02 +00003095 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekcbf4c612008-04-16 22:32:20 +00003096}
3097
Ted Kremeneka506fec2008-04-17 18:12:53 +00003098 // Return statements.
3099
Zhongxing Xu20227f72009-08-06 01:32:16 +00003100void CFRefCount::EvalReturn(ExplodedNodeSet& Dst,
Ted Kremeneka506fec2008-04-17 18:12:53 +00003101 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003102 GRStmtNodeBuilder& Builder,
Ted Kremeneka506fec2008-04-17 18:12:53 +00003103 ReturnStmt* S,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003104 ExplodedNode* Pred) {
Mike Stump11289f42009-09-09 15:08:12 +00003105
Ted Kremeneka506fec2008-04-17 18:12:53 +00003106 Expr* RetE = S->getRetValue();
Ted Kremenekc9747dd2009-03-03 22:06:47 +00003107 if (!RetE)
Ted Kremeneka506fec2008-04-17 18:12:53 +00003108 return;
Mike Stump11289f42009-09-09 15:08:12 +00003109
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003110 const GRState *state = Builder.GetState(Pred);
3111 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
Mike Stump11289f42009-09-09 15:08:12 +00003112
Ted Kremenek3e31c262009-03-26 03:35:11 +00003113 if (!Sym)
Ted Kremenekc9747dd2009-03-03 22:06:47 +00003114 return;
Mike Stump11289f42009-09-09 15:08:12 +00003115
Ted Kremeneka506fec2008-04-17 18:12:53 +00003116 // Get the reference count binding (if any).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003117 const RefVal* T = state->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00003118
Ted Kremeneka506fec2008-04-17 18:12:53 +00003119 if (!T)
3120 return;
Mike Stump11289f42009-09-09 15:08:12 +00003121
3122 // Change the reference count.
3123 RefVal X = *T;
3124
3125 switch (X.getKind()) {
3126 case RefVal::Owned: {
Ted Kremeneka506fec2008-04-17 18:12:53 +00003127 unsigned cnt = X.getCount();
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003128 assert (cnt > 0);
Ted Kremenek3978f792009-05-10 05:11:21 +00003129 X.setCount(cnt - 1);
3130 X = X ^ RefVal::ReturnedOwned;
Ted Kremeneka506fec2008-04-17 18:12:53 +00003131 break;
3132 }
Mike Stump11289f42009-09-09 15:08:12 +00003133
Ted Kremeneka506fec2008-04-17 18:12:53 +00003134 case RefVal::NotOwned: {
3135 unsigned cnt = X.getCount();
Ted Kremenek3978f792009-05-10 05:11:21 +00003136 if (cnt) {
3137 X.setCount(cnt - 1);
3138 X = X ^ RefVal::ReturnedOwned;
3139 }
3140 else {
3141 X = X ^ RefVal::ReturnedNotOwned;
3142 }
Ted Kremeneka506fec2008-04-17 18:12:53 +00003143 break;
3144 }
Mike Stump11289f42009-09-09 15:08:12 +00003145
3146 default:
Ted Kremeneka506fec2008-04-17 18:12:53 +00003147 return;
3148 }
Mike Stump11289f42009-09-09 15:08:12 +00003149
Ted Kremeneka506fec2008-04-17 18:12:53 +00003150 // Update the binding.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003151 state = state->set<RefBindings>(Sym, X);
Ted Kremenek6bd78702009-04-29 18:50:19 +00003152 Pred = Builder.MakeNode(Dst, S, Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00003153
Ted Kremenekb4e27a12009-04-30 05:51:50 +00003154 // Did we cache out?
3155 if (!Pred)
3156 return;
Mike Stump11289f42009-09-09 15:08:12 +00003157
Ted Kremenek3978f792009-05-10 05:11:21 +00003158 // Update the autorelease counts.
3159 static unsigned autoreleasetag = 0;
3160 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3161 bool stop = false;
3162 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3163 X, stop);
Mike Stump11289f42009-09-09 15:08:12 +00003164
Ted Kremenek3978f792009-05-10 05:11:21 +00003165 // Did we cache out?
3166 if (!Pred || stop)
3167 return;
Mike Stump11289f42009-09-09 15:08:12 +00003168
Ted Kremenek3978f792009-05-10 05:11:21 +00003169 // Get the updated binding.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003170 T = state->get<RefBindings>(Sym);
Ted Kremenek3978f792009-05-10 05:11:21 +00003171 assert(T);
3172 X = *T;
Mike Stump11289f42009-09-09 15:08:12 +00003173
Ted Kremenek6bd78702009-04-29 18:50:19 +00003174 // Any leaks or other errors?
3175 if (X.isReturnedOwned() && X.getCount() == 0) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00003176 Decl const *CD = &Pred->getCodeDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003177 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00003178 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekdee56e32009-05-10 06:25:57 +00003179 RetEffect RE = Summ.getRetEffect();
3180 bool hasError = false;
3181
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003182 if (RE.getKind() != RetEffect::NoRet) {
3183 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3184 // Things are more complicated with garbage collection. If the
3185 // returned object is suppose to be an Objective-C object, we have
3186 // a leak (as the caller expects a GC'ed object) because no
3187 // method should return ownership unless it returns a CF object.
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003188 hasError = true;
Ted Kremenek8070b822009-10-14 23:58:34 +00003189 X = X ^ RefVal::ErrorGCLeakReturned;
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003190 }
3191 else if (!RE.isOwned()) {
3192 // Either we are using GC and the returned object is a CF type
3193 // or we aren't using GC. In either case, we expect that the
Mike Stump11289f42009-09-09 15:08:12 +00003194 // enclosing method is expected to return ownership.
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003195 hasError = true;
3196 X = X ^ RefVal::ErrorLeakReturned;
3197 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00003198 }
Mike Stump11289f42009-09-09 15:08:12 +00003199
3200 if (hasError) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00003201 // Generate an error node.
Ted Kremenekdee56e32009-05-10 06:25:57 +00003202 static int ReturnOwnLeakTag = 0;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003203 state = state->set<RefBindings>(Sym, X);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003204 ExplodedNode *N =
Zhongxing Xue1190f72009-08-15 03:17:38 +00003205 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
3206 &ReturnOwnLeakTag), state, Pred);
Ted Kremenekdee56e32009-05-10 06:25:57 +00003207 if (N) {
3208 CFRefReport *report =
Ted Kremenekb4e27a12009-04-30 05:51:50 +00003209 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3210 N, Sym, Eng);
3211 BR->EmitReport(report);
3212 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00003213 }
Mike Stump11289f42009-09-09 15:08:12 +00003214 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00003215 }
3216 else if (X.isReturnedNotOwned()) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00003217 Decl const *CD = &Pred->getCodeDecl();
Ted Kremenekdee56e32009-05-10 06:25:57 +00003218 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3219 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3220 if (Summ.getRetEffect().isOwned()) {
3221 // Trying to return a not owned object to a caller expecting an
3222 // owned object.
Mike Stump11289f42009-09-09 15:08:12 +00003223
Ted Kremenekdee56e32009-05-10 06:25:57 +00003224 static int ReturnNotOwnedForOwnedTag = 0;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003225 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003226 if (ExplodedNode *N =
Zhongxing Xue1190f72009-08-15 03:17:38 +00003227 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
3228 &ReturnNotOwnedForOwnedTag),
3229 state, Pred)) {
Ted Kremenekdee56e32009-05-10 06:25:57 +00003230 CFRefReport *report =
3231 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3232 *this, N, Sym);
3233 BR->EmitReport(report);
3234 }
3235 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00003236 }
3237 }
Ted Kremeneka506fec2008-04-17 18:12:53 +00003238}
3239
Ted Kremenek4d837282008-04-18 19:23:43 +00003240// Assumptions.
3241
Ted Kremenekf9906842009-06-18 22:57:13 +00003242const GRState* CFRefCount::EvalAssume(const GRState *state,
3243 SVal Cond, bool Assumption) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003244
3245 // FIXME: We may add to the interface of EvalAssume the list of symbols
3246 // whose assumptions have changed. For now we just iterate through the
3247 // bindings and check if any of the tracked symbols are NULL. This isn't
Mike Stump11289f42009-09-09 15:08:12 +00003248 // too bad since the number of symbols we will track in practice are
Ted Kremenek4d837282008-04-18 19:23:43 +00003249 // probably small and EvalAssume is only called at branches and a few
3250 // other places.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003251 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003252
Ted Kremenek4d837282008-04-18 19:23:43 +00003253 if (B.isEmpty())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003254 return state;
Mike Stump11289f42009-09-09 15:08:12 +00003255
3256 bool changed = false;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003257 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
Ted Kremenek4d837282008-04-18 19:23:43 +00003258
Mike Stump11289f42009-09-09 15:08:12 +00003259 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003260 // Check if the symbol is null (or equal to any constant).
3261 // If this is the case, stop tracking the symbol.
Ted Kremenekf9906842009-06-18 22:57:13 +00003262 if (state->getSymVal(I.getKey())) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003263 changed = true;
3264 B = RefBFactory.Remove(B, I.getKey());
3265 }
3266 }
Mike Stump11289f42009-09-09 15:08:12 +00003267
Ted Kremenek87aab6c2008-08-17 03:20:02 +00003268 if (changed)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003269 state = state->set<RefBindings>(B);
Mike Stump11289f42009-09-09 15:08:12 +00003270
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00003271 return state;
Ted Kremenek4d837282008-04-18 19:23:43 +00003272}
Ted Kremenek819e9b62008-03-11 06:39:11 +00003273
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003274const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
Ted Kremenekc52f9392009-02-24 19:15:11 +00003275 RefVal V, ArgEffect E,
3276 RefVal::Kind& hasErr) {
Ted Kremenekf68490a2009-02-18 18:54:33 +00003277
3278 // In GC mode [... release] and [... retain] do nothing.
3279 switch (E) {
3280 default: break;
3281 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3282 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek10452892009-02-18 21:57:45 +00003283 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Mike Stump11289f42009-09-09 15:08:12 +00003284 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
Ted Kremenek50db3d02009-02-23 17:45:03 +00003285 NewAutoreleasePool; break;
Ted Kremenekf68490a2009-02-18 18:54:33 +00003286 }
Mike Stump11289f42009-09-09 15:08:12 +00003287
Ted Kremenekea072e32009-03-17 19:42:23 +00003288 // Handle all use-after-releases.
3289 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3290 V = V ^ RefVal::ErrorUseAfterRelease;
3291 hasErr = V.getKind();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003292 return state->set<RefBindings>(sym, V);
Mike Stump11289f42009-09-09 15:08:12 +00003293 }
3294
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003295 switch (E) {
3296 default:
3297 assert (false && "Unhandled CFRef transition.");
Mike Stump11289f42009-09-09 15:08:12 +00003298
Ted Kremenekea072e32009-03-17 19:42:23 +00003299 case Dealloc:
3300 // Any use of -dealloc in GC is *bad*.
3301 if (isGCEnabled()) {
3302 V = V ^ RefVal::ErrorDeallocGC;
3303 hasErr = V.getKind();
3304 break;
3305 }
Mike Stump11289f42009-09-09 15:08:12 +00003306
Ted Kremenekea072e32009-03-17 19:42:23 +00003307 switch (V.getKind()) {
3308 default:
3309 assert(false && "Invalid case.");
3310 case RefVal::Owned:
3311 // The object immediately transitions to the released state.
3312 V = V ^ RefVal::Released;
3313 V.clearCounts();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003314 return state->set<RefBindings>(sym, V);
Ted Kremenekea072e32009-03-17 19:42:23 +00003315 case RefVal::NotOwned:
3316 V = V ^ RefVal::ErrorDeallocNotOwned;
3317 hasErr = V.getKind();
3318 break;
Mike Stump11289f42009-09-09 15:08:12 +00003319 }
Ted Kremenekea072e32009-03-17 19:42:23 +00003320 break;
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003321
Ted Kremenek8ec8cf02009-02-25 23:11:49 +00003322 case NewAutoreleasePool:
3323 assert(!isGCEnabled());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003324 return state->add<AutoreleaseStack>(sym);
Mike Stump11289f42009-09-09 15:08:12 +00003325
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003326 case MayEscape:
3327 if (V.getKind() == RefVal::Owned) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003328 V = V ^ RefVal::NotOwned;
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003329 break;
3330 }
Ted Kremenekea072e32009-03-17 19:42:23 +00003331
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003332 // Fall-through.
Mike Stump11289f42009-09-09 15:08:12 +00003333
Ted Kremenekae529272008-07-09 18:11:16 +00003334 case DoNothingByRef:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003335 case DoNothing:
Ted Kremenekc52f9392009-02-24 19:15:11 +00003336 return state;
Ted Kremeneka0e071c2008-06-30 16:57:41 +00003337
Ted Kremenekc7832092009-01-28 21:44:40 +00003338 case Autorelease:
Ted Kremenekea072e32009-03-17 19:42:23 +00003339 if (isGCEnabled())
3340 return state;
Mike Stump11289f42009-09-09 15:08:12 +00003341
Ted Kremenek8c3f0042009-03-20 17:34:15 +00003342 // Update the autorelease counts.
3343 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek3a0516b2009-05-08 20:01:42 +00003344 V = V.autorelease();
Ted Kremenek2d0ff622009-05-09 01:50:57 +00003345 break;
Ted Kremenekd35272f2009-05-09 00:10:05 +00003346
Ted Kremenek821537e2008-05-06 02:41:27 +00003347 case StopTracking:
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003348 return state->remove<RefBindings>(sym);
Ted Kremenek050b91c2008-08-12 18:30:56 +00003349
Mike Stump11289f42009-09-09 15:08:12 +00003350 case IncRef:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003351 switch (V.getKind()) {
3352 default:
3353 assert(false);
3354
3355 case RefVal::Owned:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003356 case RefVal::NotOwned:
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003357 V = V + 1;
Mike Stump11289f42009-09-09 15:08:12 +00003358 break;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003359 case RefVal::Released:
Ted Kremenekea072e32009-03-17 19:42:23 +00003360 // Non-GC cases are handled above.
3361 assert(isGCEnabled());
3362 V = (V ^ RefVal::Owned) + 1;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003363 break;
Mike Stump11289f42009-09-09 15:08:12 +00003364 }
Ted Kremenek4b772092008-04-10 23:44:06 +00003365 break;
Mike Stump11289f42009-09-09 15:08:12 +00003366
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003367 case SelfOwn:
3368 V = V ^ RefVal::NotOwned;
Ted Kremenekf68490a2009-02-18 18:54:33 +00003369 // Fall-through.
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003370 case DecRef:
3371 switch (V.getKind()) {
3372 default:
Ted Kremenekea072e32009-03-17 19:42:23 +00003373 // case 'RefVal::Released' handled above.
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003374 assert (false);
Ted Kremenek050b91c2008-08-12 18:30:56 +00003375
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003376 case RefVal::Owned:
Ted Kremenek551747f2009-02-18 22:57:22 +00003377 assert(V.getCount() > 0);
3378 if (V.getCount() == 1) V = V ^ RefVal::Released;
3379 V = V - 1;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003380 break;
Mike Stump11289f42009-09-09 15:08:12 +00003381
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003382 case RefVal::NotOwned:
3383 if (V.getCount() > 0)
3384 V = V - 1;
Ted Kremenek3c03d522008-04-10 23:09:18 +00003385 else {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003386 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek8cb96e92008-04-16 04:28:53 +00003387 hasErr = V.getKind();
Mike Stump11289f42009-09-09 15:08:12 +00003388 }
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003389 break;
Mike Stump11289f42009-09-09 15:08:12 +00003390
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003391 case RefVal::Released:
Ted Kremenekea072e32009-03-17 19:42:23 +00003392 // Non-GC cases are handled above.
3393 assert(isGCEnabled());
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003394 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek8cb96e92008-04-16 04:28:53 +00003395 hasErr = V.getKind();
Mike Stump11289f42009-09-09 15:08:12 +00003396 break;
3397 }
Ted Kremenek4b772092008-04-10 23:44:06 +00003398 break;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003399 }
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003400 return state->set<RefBindings>(sym, V);
Ted Kremenek819e9b62008-03-11 06:39:11 +00003401}
3402
Ted Kremenekce8e8812008-04-09 01:10:13 +00003403//===----------------------------------------------------------------------===//
Ted Kremenek400aae72009-02-05 06:50:21 +00003404// Handle dead symbols and end-of-path.
3405//===----------------------------------------------------------------------===//
3406
Zhongxing Xu20227f72009-08-06 01:32:16 +00003407std::pair<ExplodedNode*, const GRState *>
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003408CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003409 ExplodedNode* Pred,
Ted Kremenekd35272f2009-05-09 00:10:05 +00003410 GRExprEngine &Eng,
3411 SymbolRef Sym, RefVal V, bool &stop) {
Mike Stump11289f42009-09-09 15:08:12 +00003412
Ted Kremenekd35272f2009-05-09 00:10:05 +00003413 unsigned ACnt = V.getAutoreleaseCount();
3414 stop = false;
3415
3416 // No autorelease counts? Nothing to be done.
3417 if (!ACnt)
3418 return std::make_pair(Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00003419
3420 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
Ted Kremenekd35272f2009-05-09 00:10:05 +00003421 unsigned Cnt = V.getCount();
Mike Stump11289f42009-09-09 15:08:12 +00003422
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003423 // FIXME: Handle sending 'autorelease' to already released object.
3424
3425 if (V.getKind() == RefVal::ReturnedOwned)
3426 ++Cnt;
Mike Stump11289f42009-09-09 15:08:12 +00003427
Ted Kremenekd35272f2009-05-09 00:10:05 +00003428 if (ACnt <= Cnt) {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003429 if (ACnt == Cnt) {
3430 V.clearCounts();
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003431 if (V.getKind() == RefVal::ReturnedOwned)
3432 V = V ^ RefVal::ReturnedNotOwned;
3433 else
3434 V = V ^ RefVal::NotOwned;
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003435 }
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003436 else {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003437 V.setCount(Cnt - ACnt);
3438 V.setAutoreleaseCount(0);
3439 }
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003440 state = state->set<RefBindings>(Sym, V);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003441 ExplodedNode *N = Bd.MakeNode(state, Pred);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003442 stop = (N == 0);
3443 return std::make_pair(N, state);
Mike Stump11289f42009-09-09 15:08:12 +00003444 }
Ted Kremenekd35272f2009-05-09 00:10:05 +00003445
3446 // Woah! More autorelease counts then retain counts left.
3447 // Emit hard error.
3448 stop = true;
3449 V = V ^ RefVal::ErrorOverAutorelease;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003450 state = state->set<RefBindings>(Sym, V);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003451
Zhongxing Xu20227f72009-08-06 01:32:16 +00003452 if (ExplodedNode *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003453 N->markAsSink();
Mike Stump11289f42009-09-09 15:08:12 +00003454
Ted Kremenek3978f792009-05-10 05:11:21 +00003455 std::string sbuf;
3456 llvm::raw_string_ostream os(sbuf);
Ted Kremenek4785e412009-05-15 06:02:08 +00003457 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenek3978f792009-05-10 05:11:21 +00003458 if (V.getAutoreleaseCount() > 1)
3459 os << V.getAutoreleaseCount() << " times";
3460 os << " but the object has ";
3461 if (V.getCount() == 0)
3462 os << "zero (locally visible)";
3463 else
3464 os << "+" << V.getCount();
3465 os << " retain counts";
Mike Stump11289f42009-09-09 15:08:12 +00003466
Ted Kremenekd35272f2009-05-09 00:10:05 +00003467 CFRefReport *report =
3468 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenek3978f792009-05-10 05:11:21 +00003469 *this, N, Sym, os.str().c_str());
Ted Kremenekd35272f2009-05-09 00:10:05 +00003470 BR->EmitReport(report);
3471 }
Mike Stump11289f42009-09-09 15:08:12 +00003472
Zhongxing Xu20227f72009-08-06 01:32:16 +00003473 return std::make_pair((ExplodedNode*)0, state);
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003474}
Ted Kremenek884a8992009-05-08 23:09:42 +00003475
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003476const GRState *
3477CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek884a8992009-05-08 23:09:42 +00003478 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
Mike Stump11289f42009-09-09 15:08:12 +00003479
3480 bool hasLeak = V.isOwned() ||
Ted Kremenek884a8992009-05-08 23:09:42 +00003481 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Mike Stump11289f42009-09-09 15:08:12 +00003482
Ted Kremenek884a8992009-05-08 23:09:42 +00003483 if (!hasLeak)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003484 return state->remove<RefBindings>(sid);
Mike Stump11289f42009-09-09 15:08:12 +00003485
Ted Kremenek884a8992009-05-08 23:09:42 +00003486 Leaked.push_back(sid);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003487 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
Ted Kremenek884a8992009-05-08 23:09:42 +00003488}
3489
Zhongxing Xu20227f72009-08-06 01:32:16 +00003490ExplodedNode*
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003491CFRefCount::ProcessLeaks(const GRState * state,
Ted Kremenek884a8992009-05-08 23:09:42 +00003492 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3493 GenericNodeBuilder &Builder,
3494 GRExprEngine& Eng,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003495 ExplodedNode *Pred) {
Mike Stump11289f42009-09-09 15:08:12 +00003496
Ted Kremenek884a8992009-05-08 23:09:42 +00003497 if (Leaked.empty())
3498 return Pred;
Mike Stump11289f42009-09-09 15:08:12 +00003499
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003500 // Generate an intermediate node representing the leak point.
Zhongxing Xu20227f72009-08-06 01:32:16 +00003501 ExplodedNode *N = Builder.MakeNode(state, Pred);
Mike Stump11289f42009-09-09 15:08:12 +00003502
Ted Kremenek884a8992009-05-08 23:09:42 +00003503 if (N) {
3504 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3505 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00003506
3507 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
Ted Kremenek884a8992009-05-08 23:09:42 +00003508 : leakAtReturn);
3509 assert(BT && "BugType not initialized.");
3510 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3511 BR->EmitReport(report);
3512 }
3513 }
Mike Stump11289f42009-09-09 15:08:12 +00003514
Ted Kremenek884a8992009-05-08 23:09:42 +00003515 return N;
3516}
3517
Ted Kremenek400aae72009-02-05 06:50:21 +00003518void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003519 GREndPathNodeBuilder& Builder) {
Mike Stump11289f42009-09-09 15:08:12 +00003520
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003521 const GRState *state = Builder.getState();
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003522 GenericNodeBuilder Bd(Builder);
Mike Stump11289f42009-09-09 15:08:12 +00003523 RefBindings B = state->get<RefBindings>();
Zhongxing Xu20227f72009-08-06 01:32:16 +00003524 ExplodedNode *Pred = 0;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003525
3526 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenekd35272f2009-05-09 00:10:05 +00003527 bool stop = false;
3528 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3529 (*I).first,
Mike Stump11289f42009-09-09 15:08:12 +00003530 (*I).second, stop);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003531
3532 if (stop)
3533 return;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003534 }
Mike Stump11289f42009-09-09 15:08:12 +00003535
3536 B = state->get<RefBindings>();
3537 llvm::SmallVector<SymbolRef, 10> Leaked;
3538
Ted Kremenek884a8992009-05-08 23:09:42 +00003539 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3540 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3541
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003542 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek400aae72009-02-05 06:50:21 +00003543}
3544
Zhongxing Xu20227f72009-08-06 01:32:16 +00003545void CFRefCount::EvalDeadSymbols(ExplodedNodeSet& Dst,
Ted Kremenek400aae72009-02-05 06:50:21 +00003546 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003547 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003548 ExplodedNode* Pred,
Ted Kremenek400aae72009-02-05 06:50:21 +00003549 Stmt* S,
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003550 const GRState* state,
Ted Kremenek400aae72009-02-05 06:50:21 +00003551 SymbolReaper& SymReaper) {
Ted Kremenek884a8992009-05-08 23:09:42 +00003552
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003553 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003554
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003555 // Update counts from autorelease pools
3556 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3557 E = SymReaper.dead_end(); I != E; ++I) {
3558 SymbolRef Sym = *I;
3559 if (const RefVal* T = B.lookup(Sym)){
3560 // Use the symbol as the tag.
3561 // FIXME: This might not be as unique as we would like.
3562 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003563 bool stop = false;
3564 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3565 Sym, *T, stop);
3566 if (stop)
3567 return;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003568 }
3569 }
Mike Stump11289f42009-09-09 15:08:12 +00003570
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003571 B = state->get<RefBindings>();
Ted Kremenek884a8992009-05-08 23:09:42 +00003572 llvm::SmallVector<SymbolRef, 10> Leaked;
Mike Stump11289f42009-09-09 15:08:12 +00003573
Ted Kremenek400aae72009-02-05 06:50:21 +00003574 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00003575 E = SymReaper.dead_end(); I != E; ++I) {
Ted Kremenek884a8992009-05-08 23:09:42 +00003576 if (const RefVal* T = B.lookup(*I))
3577 state = HandleSymbolDeath(state, *I, *T, Leaked);
Mike Stump11289f42009-09-09 15:08:12 +00003578 }
3579
Ted Kremenek884a8992009-05-08 23:09:42 +00003580 static unsigned LeakPPTag = 0;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003581 {
3582 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3583 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3584 }
Mike Stump11289f42009-09-09 15:08:12 +00003585
Ted Kremenek884a8992009-05-08 23:09:42 +00003586 // Did we cache out?
3587 if (!Pred)
3588 return;
Mike Stump11289f42009-09-09 15:08:12 +00003589
Ted Kremenek68abaa92009-02-19 23:47:02 +00003590 // Now generate a new node that nukes the old bindings.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003591 RefBindings::Factory& F = state->get_context<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003592
Ted Kremenek68abaa92009-02-19 23:47:02 +00003593 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek884a8992009-05-08 23:09:42 +00003594 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
Mike Stump11289f42009-09-09 15:08:12 +00003595
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003596 state = state->set<RefBindings>(B);
Ted Kremenek68abaa92009-02-19 23:47:02 +00003597 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek400aae72009-02-05 06:50:21 +00003598}
3599
Zhongxing Xu20227f72009-08-06 01:32:16 +00003600void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003601 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003602 Expr* NodeExpr, Expr* ErrorExpr,
3603 ExplodedNode* Pred,
Ted Kremenek400aae72009-02-05 06:50:21 +00003604 const GRState* St,
3605 RefVal::Kind hasErr, SymbolRef Sym) {
3606 Builder.BuildSinks = true;
Zhongxing Xu107f7592009-08-06 12:48:26 +00003607 ExplodedNode *N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
Mike Stump11289f42009-09-09 15:08:12 +00003608
Ted Kremenek2d0ff622009-05-09 01:50:57 +00003609 if (!N)
3610 return;
Mike Stump11289f42009-09-09 15:08:12 +00003611
Ted Kremenek400aae72009-02-05 06:50:21 +00003612 CFRefBug *BT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003613
Ted Kremenekea072e32009-03-17 19:42:23 +00003614 switch (hasErr) {
3615 default:
3616 assert(false && "Unhandled error.");
3617 return;
3618 case RefVal::ErrorUseAfterRelease:
3619 BT = static_cast<CFRefBug*>(useAfterRelease);
Mike Stump11289f42009-09-09 15:08:12 +00003620 break;
Ted Kremenekea072e32009-03-17 19:42:23 +00003621 case RefVal::ErrorReleaseNotOwned:
3622 BT = static_cast<CFRefBug*>(releaseNotOwned);
3623 break;
3624 case RefVal::ErrorDeallocGC:
3625 BT = static_cast<CFRefBug*>(deallocGC);
3626 break;
3627 case RefVal::ErrorDeallocNotOwned:
3628 BT = static_cast<CFRefBug*>(deallocNotOwned);
3629 break;
Ted Kremenek400aae72009-02-05 06:50:21 +00003630 }
Mike Stump11289f42009-09-09 15:08:12 +00003631
Ted Kremenek48d16452009-02-18 03:48:14 +00003632 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek400aae72009-02-05 06:50:21 +00003633 report->addRange(ErrorExpr->getSourceRange());
3634 BR->EmitReport(report);
3635}
3636
3637//===----------------------------------------------------------------------===//
Ted Kremenek70a87882009-11-25 22:17:44 +00003638// Pieces of the retain/release checker implemented using a CheckerVisitor.
3639// More pieces of the retain/release checker will be migrated to this interface
3640// (ideally, all of it some day).
3641//===----------------------------------------------------------------------===//
3642
3643namespace {
3644class VISIBILITY_HIDDEN RetainReleaseChecker
3645 : public CheckerVisitor<RetainReleaseChecker> {
3646 CFRefCount *TF;
3647public:
3648 RetainReleaseChecker(CFRefCount *tf) : TF(tf) {}
3649 static void* getTag() { static int x = 0; return &x; }
3650};
3651} // end anonymous namespace
3652
3653//===----------------------------------------------------------------------===//
Ted Kremenek4a78c3a2008-04-10 22:16:52 +00003654// Transfer function creation for external clients.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003655//===----------------------------------------------------------------------===//
3656
Ted Kremenek9454227942009-11-25 22:08:49 +00003657void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
3658 BugReporter &BR = Eng.getBugReporter();
3659
3660 useAfterRelease = new UseAfterRelease(this);
3661 BR.Register(useAfterRelease);
3662
3663 releaseNotOwned = new BadRelease(this);
3664 BR.Register(releaseNotOwned);
3665
3666 deallocGC = new DeallocGC(this);
3667 BR.Register(deallocGC);
3668
3669 deallocNotOwned = new DeallocNotOwned(this);
3670 BR.Register(deallocNotOwned);
3671
3672 overAutorelease = new OverAutorelease(this);
3673 BR.Register(overAutorelease);
3674
3675 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
3676 BR.Register(returnNotOwnedForOwned);
3677
3678 // First register "return" leaks.
3679 const char* name = 0;
3680
3681 if (isGCEnabled())
3682 name = "Leak of returned object when using garbage collection";
3683 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
3684 name = "Leak of returned object when not using garbage collection (GC) in "
3685 "dual GC/non-GC code";
3686 else {
3687 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
3688 name = "Leak of returned object";
3689 }
3690
3691 // Leaks should not be reported if they are post-dominated by a sink.
3692 leakAtReturn = new LeakAtReturn(this, name);
3693 leakAtReturn->setSuppressOnSink(true);
3694 BR.Register(leakAtReturn);
3695
3696 // Second, register leaks within a function/method.
3697 if (isGCEnabled())
3698 name = "Leak of object when using garbage collection";
3699 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
3700 name = "Leak of object when not using garbage collection (GC) in "
3701 "dual GC/non-GC code";
3702 else {
3703 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
3704 name = "Leak";
3705 }
3706
3707 // Leaks should not be reported if they are post-dominated by sinks.
3708 leakWithinFunction = new LeakWithinFunction(this, name);
3709 leakWithinFunction->setSuppressOnSink(true);
3710 BR.Register(leakWithinFunction);
3711
3712 // Save the reference to the BugReporter.
3713 this->BR = &BR;
Ted Kremenek70a87882009-11-25 22:17:44 +00003714
3715 // Register the RetainReleaseChecker with the GRExprEngine object.
3716 // Functionality in CFRefCount will be migrated to RetainReleaseChecker
3717 // over time.
3718 Eng.registerCheck(new RetainReleaseChecker(this));
Ted Kremenek9454227942009-11-25 22:08:49 +00003719}
3720
Ted Kremenekb0f87c42008-04-30 23:47:44 +00003721GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3722 const LangOptions& lopts) {
Ted Kremenek1f352db2008-07-22 16:21:24 +00003723 return new CFRefCount(Ctx, GCEnabled, lopts);
Mike Stump11289f42009-09-09 15:08:12 +00003724}