2 * Copyright (c) 2010-2012 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 #include "objc-private.h"
27 #include "objc-weak.h"
28 #include "llvm-DenseMap.h"
31 #include <malloc/malloc.h>
34 #include <mach/mach.h>
35 #include <mach-o/dyld.h>
36 #include <mach-o/nlist.h>
37 #include <sys/types.h>
39 #include <libkern/OSAtomic.h>
44 @interface NSInvocation
51 // NSObject used to be in Foundation/CoreFoundation.
53 #define SYMBOL_ELSEWHERE_IN_3(sym, vers, n) \
54 OBJC_EXPORT const char elsewhere_ ##n __asm__("$ld$hide$os" #vers "$" #sym); const char elsewhere_ ##n = 0
55 #define SYMBOL_ELSEWHERE_IN_2(sym, vers, n) \
56 SYMBOL_ELSEWHERE_IN_3(sym, vers, n)
57 #define SYMBOL_ELSEWHERE_IN(sym, vers) \
58 SYMBOL_ELSEWHERE_IN_2(sym, vers, __COUNTER__)
61 # define NSOBJECT_ELSEWHERE_IN(vers) \
62 SYMBOL_ELSEWHERE_IN(_OBJC_CLASS_$_NSObject, vers); \
63 SYMBOL_ELSEWHERE_IN(_OBJC_METACLASS_$_NSObject, vers); \
64 SYMBOL_ELSEWHERE_IN(_OBJC_IVAR_$_NSObject.isa, vers)
66 # define NSOBJECT_ELSEWHERE_IN(vers) \
67 SYMBOL_ELSEWHERE_IN(.objc_class_name_NSObject, vers)
71 NSOBJECT_ELSEWHERE_IN(5.1);
72 NSOBJECT_ELSEWHERE_IN(5.0);
73 NSOBJECT_ELSEWHERE_IN(4.3);
74 NSOBJECT_ELSEWHERE_IN(4.2);
75 NSOBJECT_ELSEWHERE_IN(4.1);
76 NSOBJECT_ELSEWHERE_IN(4.0);
77 NSOBJECT_ELSEWHERE_IN(3.2);
78 NSOBJECT_ELSEWHERE_IN(3.1);
79 NSOBJECT_ELSEWHERE_IN(3.0);
80 NSOBJECT_ELSEWHERE_IN(2.2);
81 NSOBJECT_ELSEWHERE_IN(2.1);
82 NSOBJECT_ELSEWHERE_IN(2.0);
84 NSOBJECT_ELSEWHERE_IN(10.7);
85 NSOBJECT_ELSEWHERE_IN(10.6);
86 NSOBJECT_ELSEWHERE_IN(10.5);
87 NSOBJECT_ELSEWHERE_IN(10.4);
88 NSOBJECT_ELSEWHERE_IN(10.3);
89 NSOBJECT_ELSEWHERE_IN(10.2);
90 NSOBJECT_ELSEWHERE_IN(10.1);
91 NSOBJECT_ELSEWHERE_IN(10.0);
93 // NSObject has always been in libobjc on these platforms.
100 /***********************************************************************
102 **********************************************************************/
104 static id defaultBadAllocHandler(Class cls)
106 _objc_fatal("attempt to allocate object of class '%s' failed",
107 cls->nameForLogging());
110 static id(*badAllocHandler)(Class) = &defaultBadAllocHandler;
112 static id callBadAllocHandler(Class cls)
114 // fixme add re-entrancy protection in case allocation fails inside handler
115 return (*badAllocHandler)(cls);
118 void _objc_setBadAllocHandler(id(*newHandler)(Class))
120 badAllocHandler = newHandler;
126 // The order of these bits is important.
127 #define SIDE_TABLE_WEAKLY_REFERENCED (1UL<<0)
128 #define SIDE_TABLE_DEALLOCATING (1UL<<1) // MSB-ward of weak bit
129 #define SIDE_TABLE_RC_ONE (1UL<<2) // MSB-ward of deallocating bit
130 #define SIDE_TABLE_RC_PINNED (1UL<<(WORD_BITS-1))
132 #define SIDE_TABLE_RC_SHIFT 2
133 #define SIDE_TABLE_FLAG_MASK (SIDE_TABLE_RC_ONE-1)
135 // RefcountMap disguises its pointers because we
136 // don't want the table to act as a root for `leaks`.
137 typedef objc::DenseMap<DisguisedPtr<objc_object>,size_t,true> RefcountMap;
142 weak_table_t weak_table;
145 memset(&weak_table, 0, sizeof(weak_table));
149 _objc_fatal("Do not delete SideTable.");
152 void lock() { slock.lock(); }
153 void unlock() { slock.unlock(); }
155 // Address-ordered lock discipline for a pair of side tables.
157 template<bool HaveOld, bool HaveNew>
158 static void lockTwo(SideTable *lock1, SideTable *lock2);
159 template<bool HaveOld, bool HaveNew>
160 static void unlockTwo(SideTable *lock1, SideTable *lock2);
165 void SideTable::lockTwo<true, true>(SideTable *lock1, SideTable *lock2) {
166 spinlock_t::lockTwo(&lock1->slock, &lock2->slock);
170 void SideTable::lockTwo<true, false>(SideTable *lock1, SideTable *) {
175 void SideTable::lockTwo<false, true>(SideTable *, SideTable *lock2) {
180 void SideTable::unlockTwo<true, true>(SideTable *lock1, SideTable *lock2) {
181 spinlock_t::unlockTwo(&lock1->slock, &lock2->slock);
185 void SideTable::unlockTwo<true, false>(SideTable *lock1, SideTable *) {
190 void SideTable::unlockTwo<false, true>(SideTable *, SideTable *lock2) {
196 // We cannot use a C++ static initializer to initialize SideTables because
197 // libc calls us before our C++ initializers run. We also don't want a global
198 // pointer to this struct because of the extra indirection.
199 // Do it the hard way.
200 alignas(StripedMap<SideTable>) static uint8_t
201 SideTableBuf[sizeof(StripedMap<SideTable>)];
203 static void SideTableInit() {
204 new (SideTableBuf) StripedMap<SideTable>();
207 static StripedMap<SideTable>& SideTables() {
208 return *reinterpret_cast<StripedMap<SideTable>*>(SideTableBuf);
211 // anonymous namespace
216 // The -fobjc-arc flag causes the compiler to issue calls to objc_{retain/release/autorelease/retain_block}
219 id objc_retainBlock(id x) {
220 return (id)_Block_copy(x);
224 // The following SHOULD be called by the compiler directly, but the request hasn't been made yet :-)
227 BOOL objc_should_deallocate(id object) {
232 objc_retain_autorelease(id obj)
234 return objc_autorelease(objc_retain(obj));
239 objc_storeStrong(id *location, id obj)
251 // Update a weak variable.
252 // If HaveOld is true, the variable has an existing value
253 // that needs to be cleaned up. This value might be nil.
254 // If HaveNew is true, there is a new value that needs to be
255 // assigned into the variable. This value might be nil.
256 // If CrashIfDeallocating is true, the process is halted if newObj is
257 // deallocating or newObj's class does not support weak references.
258 // If CrashIfDeallocating is false, nil is stored instead.
259 template <bool HaveOld, bool HaveNew, bool CrashIfDeallocating>
261 storeWeak(id *location, objc_object *newObj)
263 assert(HaveOld || HaveNew);
264 if (!HaveNew) assert(newObj == nil);
266 Class previouslyInitializedClass = nil;
271 // Acquire locks for old and new values.
272 // Order by lock address to prevent lock ordering problems.
273 // Retry if the old value changes underneath us.
277 oldTable = &SideTables()[oldObj];
282 newTable = &SideTables()[newObj];
287 SideTable::lockTwo<HaveOld, HaveNew>(oldTable, newTable);
289 if (HaveOld && *location != oldObj) {
290 SideTable::unlockTwo<HaveOld, HaveNew>(oldTable, newTable);
294 // Prevent a deadlock between the weak reference machinery
295 // and the +initialize machinery by ensuring that no
296 // weakly-referenced object has an un-+initialized isa.
297 if (HaveNew && newObj) {
298 Class cls = newObj->getIsa();
299 if (cls != previouslyInitializedClass &&
300 !((objc_class *)cls)->isInitialized())
302 SideTable::unlockTwo<HaveOld, HaveNew>(oldTable, newTable);
303 _class_initialize(_class_getNonMetaClass(cls, (id)newObj));
305 // If this class is finished with +initialize then we're good.
306 // If this class is still running +initialize on this thread
307 // (i.e. +initialize called storeWeak on an instance of itself)
308 // then we may proceed but it will appear initializing and
309 // not yet initialized to the check above.
310 // Instead set previouslyInitializedClass to recognize it on retry.
311 previouslyInitializedClass = cls;
317 // Clean up old value, if any.
319 weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
322 // Assign new value, if any.
324 newObj = (objc_object *)weak_register_no_lock(&newTable->weak_table,
325 (id)newObj, location,
326 CrashIfDeallocating);
327 // weak_register_no_lock returns nil if weak store should be rejected
329 // Set is-weakly-referenced bit in refcount table.
330 if (newObj && !newObj->isTaggedPointer()) {
331 newObj->setWeaklyReferenced_nolock();
334 // Do not set *location anywhere else. That would introduce a race.
335 *location = (id)newObj;
338 // No new value. The storage is not changed.
341 SideTable::unlockTwo<HaveOld, HaveNew>(oldTable, newTable);
348 * This function stores a new value into a __weak variable. It would
349 * be used anywhere a __weak variable is the target of an assignment.
351 * @param location The address of the weak pointer itself
352 * @param newObj The new object this weak ptr should now point to
357 objc_storeWeak(id *location, id newObj)
359 return storeWeak<true/*old*/, true/*new*/, true/*crash*/>
360 (location, (objc_object *)newObj);
365 * This function stores a new value into a __weak variable.
366 * If the new object is deallocating or the new object's class
367 * does not support weak references, stores nil instead.
369 * @param location The address of the weak pointer itself
370 * @param newObj The new object this weak ptr should now point to
372 * @return The value stored (either the new object or nil)
375 objc_storeWeakOrNil(id *location, id newObj)
377 return storeWeak<true/*old*/, true/*new*/, false/*crash*/>
378 (location, (objc_object *)newObj);
383 * Initialize a fresh weak pointer to some object location.
384 * It would be used for code like:
390 * __weak id weakPtr = o;
392 * This function IS NOT thread-safe with respect to concurrent
393 * modifications to the weak variable. (Concurrent weak clear is safe.)
395 * @param location Address of __weak ptr.
396 * @param newObj Object ptr.
399 objc_initWeak(id *location, id newObj)
406 return storeWeak<false/*old*/, true/*new*/, true/*crash*/>
407 (location, (objc_object*)newObj);
411 objc_initWeakOrNil(id *location, id newObj)
418 return storeWeak<false/*old*/, true/*new*/, false/*crash*/>
419 (location, (objc_object*)newObj);
424 * Destroys the relationship between a weak pointer
425 * and the object it is referencing in the internal weak
426 * table. If the weak pointer is not referencing anything,
427 * there is no need to edit the weak table.
429 * This function IS NOT thread-safe with respect to concurrent
430 * modifications to the weak variable. (Concurrent weak clear is safe.)
432 * @param location The weak pointer address.
435 objc_destroyWeak(id *location)
437 (void)storeWeak<true/*old*/, false/*new*/, false/*crash*/>
443 Once upon a time we eagerly cleared *location if we saw the object
444 was deallocating. This confuses code like NSPointerFunctions which
445 tries to pre-flight the raw storage and assumes if the storage is
446 zero then the weak system is done interfering. That is false: the
447 weak system is still going to check and clear the storage later.
448 This can cause objc_weak_error complaints and crashes.
449 So we now don't touch the storage until deallocation completes.
453 objc_loadWeakRetained(id *location)
462 // fixme std::atomic this load
464 if (!obj) return nil;
465 if (obj->isTaggedPointer()) return obj;
467 table = &SideTables()[obj];
470 if (*location != obj) {
478 if (! cls->hasCustomRR()) {
479 // Fast case. We know +initialize is complete because
480 // default-RR can never be set before then.
481 assert(cls->isInitialized());
482 if (! obj->rootTryRetain()) {
487 // Slow case. We must check for +initialize and call it outside
488 // the lock if necessary in order to avoid deadlocks.
489 if (cls->isInitialized() || _thisThreadIsInitializingClass(cls)) {
490 BOOL (*tryRetain)(id, SEL) = (BOOL(*)(id, SEL))
491 class_getMethodImplementation(cls, SEL_retainWeakReference);
492 if ((IMP)tryRetain == _objc_msgForward) {
495 else if (! (*tryRetain)(obj, SEL_retainWeakReference)) {
501 _class_initialize(cls);
511 * This loads the object referenced by a weak pointer and returns it, after
512 * retaining and autoreleasing the object to ensure that it stays alive
513 * long enough for the caller to use it. This function would be used
514 * anywhere a __weak variable is used in an expression.
516 * @param location The weak pointer address
518 * @return The object pointed to by \e location, or \c nil if \e location is \c nil.
521 objc_loadWeak(id *location)
523 if (!*location) return nil;
524 return objc_autorelease(objc_loadWeakRetained(location));
529 * This function copies a weak pointer from one location to another,
530 * when the destination doesn't already contain a weak pointer. It
531 * would be used for code like:
533 * __weak id src = ...;
534 * __weak id dst = src;
536 * This function IS NOT thread-safe with respect to concurrent
537 * modifications to the destination variable. (Concurrent weak clear is safe.)
539 * @param dst The destination variable.
540 * @param src The source variable.
543 objc_copyWeak(id *dst, id *src)
545 id obj = objc_loadWeakRetained(src);
546 objc_initWeak(dst, obj);
551 * Move a weak pointer from one location to another.
552 * Before the move, the destination must be uninitialized.
553 * After the move, the source is nil.
555 * This function IS NOT thread-safe with respect to concurrent
556 * modifications to either weak variable. (Concurrent weak clear is safe.)
560 objc_moveWeak(id *dst, id *src)
562 objc_copyWeak(dst, src);
563 objc_destroyWeak(src);
568 /***********************************************************************
569 Autorelease pool implementation
571 A thread's autorelease pool is a stack of pointers.
572 Each pointer is either an object to release, or POOL_BOUNDARY which is
573 an autorelease pool boundary.
574 A pool token is a pointer to the POOL_BOUNDARY for that pool. When
575 the pool is popped, every object hotter than the sentinel is released.
576 The stack is divided into a doubly-linked list of pages. Pages are added
577 and deleted as necessary.
578 Thread-local storage points to the hot page, where newly autoreleased
580 **********************************************************************/
582 // Set this to 1 to mprotect() autorelease pool contents
583 #define PROTECT_AUTORELEASEPOOL 0
585 // Set this to 1 to validate the entire autorelease pool header all the time
586 // (i.e. use check() instead of fastcheck() everywhere)
587 #define CHECK_AUTORELEASEPOOL (DEBUG)
589 BREAKPOINT_FUNCTION(void objc_autoreleaseNoPool(id obj));
590 BREAKPOINT_FUNCTION(void objc_autoreleasePoolInvalid(const void *token));
595 static const uint32_t M0 = 0xA1A1A1A1;
596 # define M1 "AUTORELEASE!"
597 static const size_t M1_len = 12;
601 assert(M1_len == strlen(M1));
602 assert(M1_len == 3 * sizeof(m[1]));
605 strncpy((char *)&m[1], M1, M1_len);
609 m[0] = m[1] = m[2] = m[3] = 0;
613 return (m[0] == M0 && 0 == strncmp((char *)&m[1], M1, M1_len));
616 bool fastcheck() const {
617 #if CHECK_AUTORELEASEPOOL
628 class AutoreleasePoolPage
630 // EMPTY_POOL_PLACEHOLDER is stored in TLS when exactly one pool is
631 // pushed and it has never contained any objects. This saves memory
632 // when the top level (i.e. libdispatch) pushes and pops pools but
634 # define EMPTY_POOL_PLACEHOLDER ((id*)1)
636 # define POOL_BOUNDARY nil
637 static pthread_key_t const key = AUTORELEASE_POOL_KEY;
638 static uint8_t const SCRIBBLE = 0xA3; // 0xA3A3A3A3 after releasing
639 static size_t const SIZE =
640 #if PROTECT_AUTORELEASEPOOL
641 PAGE_MAX_SIZE; // must be multiple of vm page size
643 PAGE_MAX_SIZE; // size and alignment, power of 2
645 static size_t const COUNT = SIZE / sizeof(id);
649 pthread_t const thread;
650 AutoreleasePoolPage * const parent;
651 AutoreleasePoolPage *child;
652 uint32_t const depth;
655 // SIZE-sizeof(*this) bytes of contents follow
657 static void * operator new(size_t size) {
658 return malloc_zone_memalign(malloc_default_zone(), SIZE, SIZE);
660 static void operator delete(void * p) {
664 inline void protect() {
665 #if PROTECT_AUTORELEASEPOOL
666 mprotect(this, SIZE, PROT_READ);
671 inline void unprotect() {
672 #if PROTECT_AUTORELEASEPOOL
674 mprotect(this, SIZE, PROT_READ | PROT_WRITE);
678 AutoreleasePoolPage(AutoreleasePoolPage *newParent)
679 : magic(), next(begin()), thread(pthread_self()),
680 parent(newParent), child(nil),
681 depth(parent ? 1+parent->depth : 0),
682 hiwat(parent ? parent->hiwat : 0)
686 assert(!parent->child);
688 parent->child = this;
694 ~AutoreleasePoolPage()
700 // Not recursive: we don't want to blow out the stack
701 // if a thread accumulates a stupendous amount of garbage
706 void busted(bool die = true)
709 (die ? _objc_fatal : _objc_inform)
710 ("autorelease pool page %p corrupted\n"
711 " magic 0x%08x 0x%08x 0x%08x 0x%08x\n"
712 " should be 0x%08x 0x%08x 0x%08x 0x%08x\n"
716 magic.m[0], magic.m[1], magic.m[2], magic.m[3],
717 right.m[0], right.m[1], right.m[2], right.m[3],
718 this->thread, pthread_self());
721 void check(bool die = true)
723 if (!magic.check() || !pthread_equal(thread, pthread_self())) {
728 void fastcheck(bool die = true)
730 #if CHECK_AUTORELEASEPOOL
733 if (! magic.fastcheck()) {
741 return (id *) ((uint8_t *)this+sizeof(*this));
745 return (id *) ((uint8_t *)this+SIZE);
749 return next == begin();
753 return next == end();
756 bool lessThanHalfFull() {
757 return (next - begin() < (end() - begin()) / 2);
764 id *ret = next; // faster than `return next-1` because of aliasing
772 releaseUntil(begin());
775 void releaseUntil(id *stop)
777 // Not recursive: we don't want to blow out the stack
778 // if a thread accumulates a stupendous amount of garbage
780 while (this->next != stop) {
781 // Restart from hotPage() every time, in case -release
782 // autoreleased more objects
783 AutoreleasePoolPage *page = hotPage();
785 // fixme I think this `while` can be `if`, but I can't prove it
786 while (page->empty()) {
792 id obj = *--page->next;
793 memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
796 if (obj != POOL_BOUNDARY) {
804 // we expect any children to be completely empty
805 for (AutoreleasePoolPage *page = child; page; page = page->child) {
806 assert(page->empty());
813 // Not recursive: we don't want to blow out the stack
814 // if a thread accumulates a stupendous amount of garbage
815 AutoreleasePoolPage *page = this;
816 while (page->child) page = page->child;
818 AutoreleasePoolPage *deathptr;
828 } while (deathptr != this);
831 static void tls_dealloc(void *p)
833 if (p == (void*)EMPTY_POOL_PLACEHOLDER) {
834 // No objects or pool pages to clean up here.
838 // reinstate TLS value while we work
839 setHotPage((AutoreleasePoolPage *)p);
841 if (AutoreleasePoolPage *page = coldPage()) {
842 if (!page->empty()) pop(page->begin()); // pop all of the pools
843 if (DebugMissingPools || DebugPoolAllocation) {
844 // pop() killed the pages already
846 page->kill(); // free all of the pages
850 // clear TLS value so TLS destruction doesn't loop
854 static AutoreleasePoolPage *pageForPointer(const void *p)
856 return pageForPointer((uintptr_t)p);
859 static AutoreleasePoolPage *pageForPointer(uintptr_t p)
861 AutoreleasePoolPage *result;
862 uintptr_t offset = p % SIZE;
864 assert(offset >= sizeof(AutoreleasePoolPage));
866 result = (AutoreleasePoolPage *)(p - offset);
873 static inline bool haveEmptyPoolPlaceholder()
875 id *tls = (id *)tls_get_direct(key);
876 return (tls == EMPTY_POOL_PLACEHOLDER);
879 static inline id* setEmptyPoolPlaceholder()
881 assert(tls_get_direct(key) == nil);
882 tls_set_direct(key, (void *)EMPTY_POOL_PLACEHOLDER);
883 return EMPTY_POOL_PLACEHOLDER;
886 static inline AutoreleasePoolPage *hotPage()
888 AutoreleasePoolPage *result = (AutoreleasePoolPage *)
890 if ((id *)result == EMPTY_POOL_PLACEHOLDER) return nil;
891 if (result) result->fastcheck();
895 static inline void setHotPage(AutoreleasePoolPage *page)
897 if (page) page->fastcheck();
898 tls_set_direct(key, (void *)page);
901 static inline AutoreleasePoolPage *coldPage()
903 AutoreleasePoolPage *result = hotPage();
905 while (result->parent) {
906 result = result->parent;
914 static inline id *autoreleaseFast(id obj)
916 AutoreleasePoolPage *page = hotPage();
917 if (page && !page->full()) {
918 return page->add(obj);
920 return autoreleaseFullPage(obj, page);
922 return autoreleaseNoPage(obj);
926 static __attribute__((noinline))
927 id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page)
929 // The hot page is full.
930 // Step to the next non-full page, adding a new page if necessary.
931 // Then add the object to that page.
932 assert(page == hotPage());
933 assert(page->full() || DebugPoolAllocation);
936 if (page->child) page = page->child;
937 else page = new AutoreleasePoolPage(page);
938 } while (page->full());
941 return page->add(obj);
944 static __attribute__((noinline))
945 id *autoreleaseNoPage(id obj)
947 // "No page" could mean no pool has been pushed
948 // or an empty placeholder pool has been pushed and has no contents yet
951 bool pushExtraBoundary = false;
952 if (haveEmptyPoolPlaceholder()) {
953 // We are pushing a second pool over the empty placeholder pool
954 // or pushing the first object into the empty placeholder pool.
955 // Before doing that, push a pool boundary on behalf of the pool
956 // that is currently represented by the empty placeholder.
957 pushExtraBoundary = true;
959 else if (obj != POOL_BOUNDARY && DebugMissingPools) {
960 // We are pushing an object with no pool in place,
961 // and no-pool debugging was requested by environment.
962 _objc_inform("MISSING POOLS: (%p) Object %p of class %s "
963 "autoreleased with no pool in place - "
964 "just leaking - break on "
965 "objc_autoreleaseNoPool() to debug",
966 pthread_self(), (void*)obj, object_getClassName(obj));
967 objc_autoreleaseNoPool(obj);
970 else if (obj == POOL_BOUNDARY && !DebugPoolAllocation) {
971 // We are pushing a pool with no pool in place,
972 // and alloc-per-pool debugging was not requested.
973 // Install and return the empty pool placeholder.
974 return setEmptyPoolPlaceholder();
977 // We are pushing an object or a non-placeholder'd pool.
979 // Install the first page.
980 AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
983 // Push a boundary on behalf of the previously-placeholder'd pool.
984 if (pushExtraBoundary) {
985 page->add(POOL_BOUNDARY);
988 // Push the requested object or pool.
989 return page->add(obj);
993 static __attribute__((noinline))
994 id *autoreleaseNewPage(id obj)
996 AutoreleasePoolPage *page = hotPage();
997 if (page) return autoreleaseFullPage(obj, page);
998 else return autoreleaseNoPage(obj);
1002 static inline id autorelease(id obj)
1005 assert(!obj->isTaggedPointer());
1006 id *dest __unused = autoreleaseFast(obj);
1007 assert(!dest || dest == EMPTY_POOL_PLACEHOLDER || *dest == obj);
1012 static inline void *push()
1015 if (DebugPoolAllocation) {
1016 // Each autorelease pool starts on a new pool page.
1017 dest = autoreleaseNewPage(POOL_BOUNDARY);
1019 dest = autoreleaseFast(POOL_BOUNDARY);
1021 assert(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
1025 static void badPop(void *token)
1027 // Error. For bincompat purposes this is not
1028 // fatal in executables built with old SDKs.
1030 if (DebugPoolAllocation || sdkIsAtLeast(10_12, 10_0, 10_0, 3_0)) {
1031 // OBJC_DEBUG_POOL_ALLOCATION or new SDK. Bad pop is fatal.
1033 ("Invalid or prematurely-freed autorelease pool %p.", token);
1036 // Old SDK. Bad pop is warned once.
1037 static bool complained = false;
1040 _objc_inform_now_and_on_crash
1041 ("Invalid or prematurely-freed autorelease pool %p. "
1042 "Set a breakpoint on objc_autoreleasePoolInvalid to debug. "
1043 "Proceeding anyway because the app is old "
1044 "(SDK version " SDK_FORMAT "). Memory errors are likely.",
1045 token, FORMAT_SDK(sdkVersion()));
1047 objc_autoreleasePoolInvalid(token);
1050 static inline void pop(void *token)
1052 AutoreleasePoolPage *page;
1055 if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
1056 // Popping the top-level placeholder pool.
1058 // Pool was used. Pop its contents normally.
1059 // Pool pages remain allocated for re-use as usual.
1060 pop(coldPage()->begin());
1062 // Pool was never used. Clear the placeholder.
1068 page = pageForPointer(token);
1070 if (*stop != POOL_BOUNDARY) {
1071 if (stop == page->begin() && !page->parent) {
1072 // Start of coldest page may correctly not be POOL_BOUNDARY:
1073 // 1. top-level pool is popped, leaving the cold page in place
1074 // 2. an object is autoreleased with no pool
1076 // Error. For bincompat purposes this is not
1077 // fatal in executables built with old SDKs.
1078 return badPop(token);
1082 if (PrintPoolHiwat) printHiwat();
1084 page->releaseUntil(stop);
1086 // memory: delete empty children
1087 if (DebugPoolAllocation && page->empty()) {
1088 // special case: delete everything during page-per-pool debugging
1089 AutoreleasePoolPage *parent = page->parent;
1092 } else if (DebugMissingPools && page->empty() && !page->parent) {
1093 // special case: delete everything for pop(top)
1094 // when debugging missing autorelease pools
1098 else if (page->child) {
1099 // hysteresis: keep one empty child if page is more than half full
1100 if (page->lessThanHalfFull()) {
1101 page->child->kill();
1103 else if (page->child->child) {
1104 page->child->child->kill();
1111 int r __unused = pthread_key_init_np(AutoreleasePoolPage::key,
1112 AutoreleasePoolPage::tls_dealloc);
1118 _objc_inform("[%p] ................ PAGE %s %s %s", this,
1119 full() ? "(full)" : "",
1120 this == hotPage() ? "(hot)" : "",
1121 this == coldPage() ? "(cold)" : "");
1123 for (id *p = begin(); p < next; p++) {
1124 if (*p == POOL_BOUNDARY) {
1125 _objc_inform("[%p] ################ POOL %p", p, p);
1127 _objc_inform("[%p] %#16lx %s",
1128 p, (unsigned long)*p, object_getClassName(*p));
1133 static void printAll()
1135 _objc_inform("##############");
1136 _objc_inform("AUTORELEASE POOLS for thread %p", pthread_self());
1138 AutoreleasePoolPage *page;
1139 ptrdiff_t objects = 0;
1140 for (page = coldPage(); page; page = page->child) {
1141 objects += page->next - page->begin();
1143 _objc_inform("%llu releases pending.", (unsigned long long)objects);
1145 if (haveEmptyPoolPlaceholder()) {
1146 _objc_inform("[%p] ................ PAGE (placeholder)",
1147 EMPTY_POOL_PLACEHOLDER);
1148 _objc_inform("[%p] ################ POOL (placeholder)",
1149 EMPTY_POOL_PLACEHOLDER);
1152 for (page = coldPage(); page; page = page->child) {
1157 _objc_inform("##############");
1160 static void printHiwat()
1162 // Check and propagate high water mark
1163 // Ignore high water marks under 256 to suppress noise.
1164 AutoreleasePoolPage *p = hotPage();
1165 uint32_t mark = p->depth*COUNT + (uint32_t)(p->next - p->begin());
1166 if (mark > p->hiwat && mark > 256) {
1167 for( ; p; p = p->parent) {
1173 _objc_inform("POOL HIGHWATER: new high water mark of %u "
1174 "pending releases for thread %p:",
1175 mark, pthread_self());
1178 int count = backtrace(stack, sizeof(stack)/sizeof(stack[0]));
1179 char **sym = backtrace_symbols(stack, count);
1180 for (int i = 0; i < count; i++) {
1181 _objc_inform("POOL HIGHWATER: %s", sym[i]);
1187 #undef POOL_BOUNDARY
1190 // anonymous namespace
1194 /***********************************************************************
1195 * Slow paths for inline control
1196 **********************************************************************/
1198 #if SUPPORT_NONPOINTER_ISA
1201 objc_object::rootRetain_overflow(bool tryRetain)
1203 return rootRetain(tryRetain, true);
1208 objc_object::rootRelease_underflow(bool performDealloc)
1210 return rootRelease(performDealloc, true);
1214 // Slow path of clearDeallocating()
1215 // for objects with nonpointer isa
1216 // that were ever weakly referenced
1217 // or whose retain count ever overflowed to the side table.
1219 objc_object::clearDeallocating_slow()
1221 assert(isa.nonpointer && (isa.weakly_referenced || isa.has_sidetable_rc));
1223 SideTable& table = SideTables()[this];
1225 if (isa.weakly_referenced) {
1226 weak_clear_no_lock(&table.weak_table, (id)this);
1228 if (isa.has_sidetable_rc) {
1229 table.refcnts.erase(this);
1236 __attribute__((noinline,used))
1238 objc_object::rootAutorelease2()
1240 assert(!isTaggedPointer());
1241 return AutoreleasePoolPage::autorelease((id)this);
1245 BREAKPOINT_FUNCTION(
1246 void objc_overrelease_during_dealloc_error(void)
1252 objc_object::overrelease_error()
1254 _objc_inform_now_and_on_crash("%s object %p overreleased while already deallocating; break on objc_overrelease_during_dealloc_error to debug", object_getClassName((id)this), this);
1255 objc_overrelease_during_dealloc_error();
1256 return false; // allow rootRelease() to tail-call this
1260 /***********************************************************************
1261 * Retain count operations for side table.
1262 **********************************************************************/
1266 // Used to assert that an object is not present in the side table.
1268 objc_object::sidetable_present()
1270 bool result = false;
1271 SideTable& table = SideTables()[this];
1275 RefcountMap::iterator it = table.refcnts.find(this);
1276 if (it != table.refcnts.end()) result = true;
1278 if (weak_is_registered_no_lock(&table.weak_table, (id)this)) result = true;
1286 #if SUPPORT_NONPOINTER_ISA
1289 objc_object::sidetable_lock()
1291 SideTable& table = SideTables()[this];
1296 objc_object::sidetable_unlock()
1298 SideTable& table = SideTables()[this];
1303 // Move the entire retain count to the side table,
1304 // as well as isDeallocating and weaklyReferenced.
1306 objc_object::sidetable_moveExtraRC_nolock(size_t extra_rc,
1307 bool isDeallocating,
1308 bool weaklyReferenced)
1310 assert(!isa.nonpointer); // should already be changed to raw pointer
1311 SideTable& table = SideTables()[this];
1313 size_t& refcntStorage = table.refcnts[this];
1314 size_t oldRefcnt = refcntStorage;
1315 // not deallocating - that was in the isa
1316 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1317 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1320 size_t refcnt = addc(oldRefcnt, extra_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
1321 if (carry) refcnt = SIDE_TABLE_RC_PINNED;
1322 if (isDeallocating) refcnt |= SIDE_TABLE_DEALLOCATING;
1323 if (weaklyReferenced) refcnt |= SIDE_TABLE_WEAKLY_REFERENCED;
1325 refcntStorage = refcnt;
1329 // Move some retain counts to the side table from the isa field.
1330 // Returns true if the object is now pinned.
1332 objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)
1334 assert(isa.nonpointer);
1335 SideTable& table = SideTables()[this];
1337 size_t& refcntStorage = table.refcnts[this];
1338 size_t oldRefcnt = refcntStorage;
1339 // isa-side bits should not be set here
1340 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1341 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1343 if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;
1347 addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
1350 SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK);
1354 refcntStorage = newRefcnt;
1360 // Move some retain counts from the side table to the isa field.
1361 // Returns the actual count subtracted, which may be less than the request.
1363 objc_object::sidetable_subExtraRC_nolock(size_t delta_rc)
1365 assert(isa.nonpointer);
1366 SideTable& table = SideTables()[this];
1368 RefcountMap::iterator it = table.refcnts.find(this);
1369 if (it == table.refcnts.end() || it->second == 0) {
1370 // Side table retain count is zero. Can't borrow.
1373 size_t oldRefcnt = it->second;
1375 // isa-side bits should not be set here
1376 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1377 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1379 size_t newRefcnt = oldRefcnt - (delta_rc << SIDE_TABLE_RC_SHIFT);
1380 assert(oldRefcnt > newRefcnt); // shouldn't underflow
1381 it->second = newRefcnt;
1387 objc_object::sidetable_getExtraRC_nolock()
1389 assert(isa.nonpointer);
1390 SideTable& table = SideTables()[this];
1391 RefcountMap::iterator it = table.refcnts.find(this);
1392 if (it == table.refcnts.end()) return 0;
1393 else return it->second >> SIDE_TABLE_RC_SHIFT;
1397 // SUPPORT_NONPOINTER_ISA
1402 objc_object::sidetable_retain()
1404 #if SUPPORT_NONPOINTER_ISA
1405 assert(!isa.nonpointer);
1407 SideTable& table = SideTables()[this];
1410 size_t& refcntStorage = table.refcnts[this];
1411 if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) {
1412 refcntStorage += SIDE_TABLE_RC_ONE;
1421 objc_object::sidetable_tryRetain()
1423 #if SUPPORT_NONPOINTER_ISA
1424 assert(!isa.nonpointer);
1426 SideTable& table = SideTables()[this];
1429 // _objc_rootTryRetain() is called exclusively by _objc_loadWeak(),
1430 // which already acquired the lock on our behalf.
1432 // fixme can't do this efficiently with os_lock_handoff_s
1433 // if (table.slock == 0) {
1434 // _objc_fatal("Do not call -_tryRetain.");
1438 RefcountMap::iterator it = table.refcnts.find(this);
1439 if (it == table.refcnts.end()) {
1440 table.refcnts[this] = SIDE_TABLE_RC_ONE;
1441 } else if (it->second & SIDE_TABLE_DEALLOCATING) {
1443 } else if (! (it->second & SIDE_TABLE_RC_PINNED)) {
1444 it->second += SIDE_TABLE_RC_ONE;
1452 objc_object::sidetable_retainCount()
1454 SideTable& table = SideTables()[this];
1456 size_t refcnt_result = 1;
1459 RefcountMap::iterator it = table.refcnts.find(this);
1460 if (it != table.refcnts.end()) {
1461 // this is valid for SIDE_TABLE_RC_PINNED too
1462 refcnt_result += it->second >> SIDE_TABLE_RC_SHIFT;
1465 return refcnt_result;
1470 objc_object::sidetable_isDeallocating()
1472 SideTable& table = SideTables()[this];
1475 // _objc_rootIsDeallocating() is called exclusively by _objc_storeWeak(),
1476 // which already acquired the lock on our behalf.
1479 // fixme can't do this efficiently with os_lock_handoff_s
1480 // if (table.slock == 0) {
1481 // _objc_fatal("Do not call -_isDeallocating.");
1484 RefcountMap::iterator it = table.refcnts.find(this);
1485 return (it != table.refcnts.end()) && (it->second & SIDE_TABLE_DEALLOCATING);
1490 objc_object::sidetable_isWeaklyReferenced()
1492 bool result = false;
1494 SideTable& table = SideTables()[this];
1497 RefcountMap::iterator it = table.refcnts.find(this);
1498 if (it != table.refcnts.end()) {
1499 result = it->second & SIDE_TABLE_WEAKLY_REFERENCED;
1509 objc_object::sidetable_setWeaklyReferenced_nolock()
1511 #if SUPPORT_NONPOINTER_ISA
1512 assert(!isa.nonpointer);
1515 SideTable& table = SideTables()[this];
1517 table.refcnts[this] |= SIDE_TABLE_WEAKLY_REFERENCED;
1522 // return uintptr_t instead of bool so that the various raw-isa
1523 // -release paths all return zero in eax
1525 objc_object::sidetable_release(bool performDealloc)
1527 #if SUPPORT_NONPOINTER_ISA
1528 assert(!isa.nonpointer);
1530 SideTable& table = SideTables()[this];
1532 bool do_dealloc = false;
1535 RefcountMap::iterator it = table.refcnts.find(this);
1536 if (it == table.refcnts.end()) {
1538 table.refcnts[this] = SIDE_TABLE_DEALLOCATING;
1539 } else if (it->second < SIDE_TABLE_DEALLOCATING) {
1540 // SIDE_TABLE_WEAKLY_REFERENCED may be set. Don't change it.
1542 it->second |= SIDE_TABLE_DEALLOCATING;
1543 } else if (! (it->second & SIDE_TABLE_RC_PINNED)) {
1544 it->second -= SIDE_TABLE_RC_ONE;
1547 if (do_dealloc && performDealloc) {
1548 ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
1555 objc_object::sidetable_clearDeallocating()
1557 SideTable& table = SideTables()[this];
1559 // clear any weak table items
1560 // clear extra retain count and deallocating bit
1561 // (fixme warn or abort if extra retain count == 0 ?)
1563 RefcountMap::iterator it = table.refcnts.find(this);
1564 if (it != table.refcnts.end()) {
1565 if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
1566 weak_clear_no_lock(&table.weak_table, (id)this);
1568 table.refcnts.erase(it);
1574 /***********************************************************************
1575 * Optimized retain/release/autorelease entrypoints
1576 **********************************************************************/
1581 __attribute__((aligned(16)))
1585 if (!obj) return obj;
1586 if (obj->isTaggedPointer()) return obj;
1587 return obj->retain();
1591 __attribute__((aligned(16)))
1593 objc_release(id obj)
1596 if (obj->isTaggedPointer()) return;
1597 return obj->release();
1601 __attribute__((aligned(16)))
1603 objc_autorelease(id obj)
1605 if (!obj) return obj;
1606 if (obj->isTaggedPointer()) return obj;
1607 return obj->autorelease();
1616 id objc_retain(id obj) { return [obj retain]; }
1617 void objc_release(id obj) { [obj release]; }
1618 id objc_autorelease(id obj) { return [obj autorelease]; }
1624 /***********************************************************************
1625 * Basic operations for root class implementations a.k.a. _objc_root*()
1626 **********************************************************************/
1629 _objc_rootTryRetain(id obj)
1633 return obj->rootTryRetain();
1637 _objc_rootIsDeallocating(id obj)
1641 return obj->rootIsDeallocating();
1646 objc_clear_deallocating(id obj)
1650 if (obj->isTaggedPointer()) return;
1651 obj->clearDeallocating();
1656 _objc_rootReleaseWasZero(id obj)
1660 return obj->rootReleaseShouldDealloc();
1665 _objc_rootAutorelease(id obj)
1668 return obj->rootAutorelease();
1672 _objc_rootRetainCount(id obj)
1676 return obj->rootRetainCount();
1681 _objc_rootRetain(id obj)
1685 return obj->rootRetain();
1689 _objc_rootRelease(id obj)
1698 _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
1703 // allocWithZone under __OBJC2__ ignores the zone parameter
1705 obj = class_createInstance(cls, 0);
1708 obj = class_createInstance(cls, 0);
1711 obj = class_createInstanceFromZone(cls, 0, zone);
1715 if (slowpath(!obj)) obj = callBadAllocHandler(cls);
1720 // Call [cls alloc] or [cls allocWithZone:nil], with appropriate
1721 // shortcutting optimizations.
1722 static ALWAYS_INLINE id
1723 callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
1725 if (slowpath(checkNil && !cls)) return nil;
1728 if (fastpath(!cls->ISA()->hasCustomAWZ())) {
1729 // No alloc/allocWithZone implementation. Go straight to the allocator.
1730 // fixme store hasCustomAWZ in the non-meta class and
1731 // add it to canAllocFast's summary
1732 if (fastpath(cls->canAllocFast())) {
1733 // No ctors, raw isa, etc. Go straight to the metal.
1734 bool dtor = cls->hasCxxDtor();
1735 id obj = (id)calloc(1, cls->bits.fastInstanceSize());
1736 if (slowpath(!obj)) return callBadAllocHandler(cls);
1737 obj->initInstanceIsa(cls, dtor);
1741 // Has ctor or raw isa or something. Use the slower path.
1742 id obj = class_createInstance(cls, 0);
1743 if (slowpath(!obj)) return callBadAllocHandler(cls);
1749 // No shortcuts available.
1750 if (allocWithZone) return [cls allocWithZone:nil];
1755 // Base class implementation of +alloc. cls is not nil.
1756 // Calls [cls allocWithZone:nil].
1758 _objc_rootAlloc(Class cls)
1760 return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
1763 // Calls [cls alloc].
1765 objc_alloc(Class cls)
1767 return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
1770 // Calls [cls allocWithZone:nil].
1772 objc_allocWithZone(Class cls)
1774 return callAlloc(cls, true/*checkNil*/, true/*allocWithZone*/);
1779 _objc_rootDealloc(id obj)
1787 _objc_rootFinalize(id obj __unused)
1790 _objc_fatal("_objc_rootFinalize called with garbage collection off");
1795 _objc_rootInit(id obj)
1797 // In practice, it will be hard to rely on this function.
1798 // Many classes do not properly chain -init calls.
1804 _objc_rootZone(id obj)
1808 // allocWithZone under __OBJC2__ ignores the zone parameter
1809 return malloc_default_zone();
1811 malloc_zone_t *rval = malloc_zone_from_ptr(obj);
1812 return rval ? rval : malloc_default_zone();
1817 _objc_rootHash(id obj)
1819 return (uintptr_t)obj;
1823 objc_autoreleasePoolPush(void)
1825 return AutoreleasePoolPage::push();
1829 objc_autoreleasePoolPop(void *ctxt)
1831 AutoreleasePoolPage::pop(ctxt);
1836 _objc_autoreleasePoolPush(void)
1838 return objc_autoreleasePoolPush();
1842 _objc_autoreleasePoolPop(void *ctxt)
1844 objc_autoreleasePoolPop(ctxt);
1848 _objc_autoreleasePoolPrint(void)
1850 AutoreleasePoolPage::printAll();
1854 // Same as objc_release but suitable for tail-calling
1855 // if you need the value back and don't want to push a frame before this point.
1856 __attribute__((noinline))
1858 objc_releaseAndReturn(id obj)
1864 // Same as objc_retainAutorelease but suitable for tail-calling
1865 // if you don't want to push a frame before this point.
1866 __attribute__((noinline))
1868 objc_retainAutoreleaseAndReturn(id obj)
1870 return objc_retainAutorelease(obj);
1874 // Prepare a value at +1 for return through a +0 autoreleasing convention.
1876 objc_autoreleaseReturnValue(id obj)
1878 if (prepareOptimizedReturn(ReturnAtPlus1)) return obj;
1880 return objc_autorelease(obj);
1883 // Prepare a value at +0 for return through a +0 autoreleasing convention.
1885 objc_retainAutoreleaseReturnValue(id obj)
1887 if (prepareOptimizedReturn(ReturnAtPlus0)) return obj;
1889 // not objc_autoreleaseReturnValue(objc_retain(obj))
1890 // because we don't need another optimization attempt
1891 return objc_retainAutoreleaseAndReturn(obj);
1894 // Accept a value returned through a +0 autoreleasing convention for use at +1.
1896 objc_retainAutoreleasedReturnValue(id obj)
1898 if (acceptOptimizedReturn() == ReturnAtPlus1) return obj;
1900 return objc_retain(obj);
1903 // Accept a value returned through a +0 autoreleasing convention for use at +0.
1905 objc_unsafeClaimAutoreleasedReturnValue(id obj)
1907 if (acceptOptimizedReturn() == ReturnAtPlus0) return obj;
1909 return objc_releaseAndReturn(obj);
1913 objc_retainAutorelease(id obj)
1915 return objc_autorelease(objc_retain(obj));
1919 _objc_deallocOnMainThreadHelper(void *context)
1921 id obj = (id)context;
1925 // convert objc_objectptr_t to id, callee must take ownership.
1926 id objc_retainedObject(objc_objectptr_t pointer) { return (id)pointer; }
1928 // convert objc_objectptr_t to id, without ownership transfer.
1929 id objc_unretainedObject(objc_objectptr_t pointer) { return (id)pointer; }
1931 // convert id to objc_objectptr_t, no ownership transfer.
1932 objc_objectptr_t objc_unretainedPointer(id object) { return object; }
1937 AutoreleasePoolPage::init();
1942 #if SUPPORT_TAGGED_POINTERS
1944 // Placeholder for old debuggers. When they inspect an
1945 // extended tagged pointer object they will see this isa.
1947 @interface __NSUnrecognizedTaggedPointer : NSObject
1950 @implementation __NSUnrecognizedTaggedPointer
1952 -(id) retain { return self; }
1953 -(oneway void) release { }
1954 -(id) autorelease { return self; }
1960 @implementation NSObject
1965 + (void)initialize {
1981 return object_getClass(self);
1984 + (Class)superclass {
1985 return self->superclass;
1988 - (Class)superclass {
1989 return [self class]->superclass;
1992 + (BOOL)isMemberOfClass:(Class)cls {
1993 return object_getClass((id)self) == cls;
1996 - (BOOL)isMemberOfClass:(Class)cls {
1997 return [self class] == cls;
2000 + (BOOL)isKindOfClass:(Class)cls {
2001 for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
2002 if (tcls == cls) return YES;
2007 - (BOOL)isKindOfClass:(Class)cls {
2008 for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
2009 if (tcls == cls) return YES;
2014 + (BOOL)isSubclassOfClass:(Class)cls {
2015 for (Class tcls = self; tcls; tcls = tcls->superclass) {
2016 if (tcls == cls) return YES;
2021 + (BOOL)isAncestorOfObject:(NSObject *)obj {
2022 for (Class tcls = [obj class]; tcls; tcls = tcls->superclass) {
2023 if (tcls == self) return YES;
2028 + (BOOL)instancesRespondToSelector:(SEL)sel {
2029 if (!sel) return NO;
2030 return class_respondsToSelector(self, sel);
2033 + (BOOL)respondsToSelector:(SEL)sel {
2034 if (!sel) return NO;
2035 return class_respondsToSelector_inst(object_getClass(self), sel, self);
2038 - (BOOL)respondsToSelector:(SEL)sel {
2039 if (!sel) return NO;
2040 return class_respondsToSelector_inst([self class], sel, self);
2043 + (BOOL)conformsToProtocol:(Protocol *)protocol {
2044 if (!protocol) return NO;
2045 for (Class tcls = self; tcls; tcls = tcls->superclass) {
2046 if (class_conformsToProtocol(tcls, protocol)) return YES;
2051 - (BOOL)conformsToProtocol:(Protocol *)protocol {
2052 if (!protocol) return NO;
2053 for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
2054 if (class_conformsToProtocol(tcls, protocol)) return YES;
2059 + (NSUInteger)hash {
2060 return _objc_rootHash(self);
2063 - (NSUInteger)hash {
2064 return _objc_rootHash(self);
2067 + (BOOL)isEqual:(id)obj {
2068 return obj == (id)self;
2071 - (BOOL)isEqual:(id)obj {
2093 + (IMP)instanceMethodForSelector:(SEL)sel {
2094 if (!sel) [self doesNotRecognizeSelector:sel];
2095 return class_getMethodImplementation(self, sel);
2098 + (IMP)methodForSelector:(SEL)sel {
2099 if (!sel) [self doesNotRecognizeSelector:sel];
2100 return object_getMethodImplementation((id)self, sel);
2103 - (IMP)methodForSelector:(SEL)sel {
2104 if (!sel) [self doesNotRecognizeSelector:sel];
2105 return object_getMethodImplementation(self, sel);
2108 + (BOOL)resolveClassMethod:(SEL)sel {
2112 + (BOOL)resolveInstanceMethod:(SEL)sel {
2116 // Replaced by CF (throws an NSException)
2117 + (void)doesNotRecognizeSelector:(SEL)sel {
2118 _objc_fatal("+[%s %s]: unrecognized selector sent to instance %p",
2119 class_getName(self), sel_getName(sel), self);
2122 // Replaced by CF (throws an NSException)
2123 - (void)doesNotRecognizeSelector:(SEL)sel {
2124 _objc_fatal("-[%s %s]: unrecognized selector sent to instance %p",
2125 object_getClassName(self), sel_getName(sel), self);
2129 + (id)performSelector:(SEL)sel {
2130 if (!sel) [self doesNotRecognizeSelector:sel];
2131 return ((id(*)(id, SEL))objc_msgSend)((id)self, sel);
2134 + (id)performSelector:(SEL)sel withObject:(id)obj {
2135 if (!sel) [self doesNotRecognizeSelector:sel];
2136 return ((id(*)(id, SEL, id))objc_msgSend)((id)self, sel, obj);
2139 + (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
2140 if (!sel) [self doesNotRecognizeSelector:sel];
2141 return ((id(*)(id, SEL, id, id))objc_msgSend)((id)self, sel, obj1, obj2);
2144 - (id)performSelector:(SEL)sel {
2145 if (!sel) [self doesNotRecognizeSelector:sel];
2146 return ((id(*)(id, SEL))objc_msgSend)(self, sel);
2149 - (id)performSelector:(SEL)sel withObject:(id)obj {
2150 if (!sel) [self doesNotRecognizeSelector:sel];
2151 return ((id(*)(id, SEL, id))objc_msgSend)(self, sel, obj);
2154 - (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
2155 if (!sel) [self doesNotRecognizeSelector:sel];
2156 return ((id(*)(id, SEL, id, id))objc_msgSend)(self, sel, obj1, obj2);
2160 // Replaced by CF (returns an NSMethodSignature)
2161 + (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)sel {
2162 _objc_fatal("+[NSObject instanceMethodSignatureForSelector:] "
2163 "not available without CoreFoundation");
2166 // Replaced by CF (returns an NSMethodSignature)
2167 + (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
2168 _objc_fatal("+[NSObject methodSignatureForSelector:] "
2169 "not available without CoreFoundation");
2172 // Replaced by CF (returns an NSMethodSignature)
2173 - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
2174 _objc_fatal("-[NSObject methodSignatureForSelector:] "
2175 "not available without CoreFoundation");
2178 + (void)forwardInvocation:(NSInvocation *)invocation {
2179 [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
2182 - (void)forwardInvocation:(NSInvocation *)invocation {
2183 [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
2186 + (id)forwardingTargetForSelector:(SEL)sel {
2190 - (id)forwardingTargetForSelector:(SEL)sel {
2195 // Replaced by CF (returns an NSString)
2196 + (NSString *)description {
2200 // Replaced by CF (returns an NSString)
2201 - (NSString *)description {
2205 + (NSString *)debugDescription {
2206 return [self description];
2209 - (NSString *)debugDescription {
2210 return [self description];
2215 return [callAlloc(self, false/*checkNil*/) init];
2222 // Replaced by ObjectAlloc
2224 return ((id)self)->rootRetain();
2228 + (BOOL)_tryRetain {
2232 // Replaced by ObjectAlloc
2233 - (BOOL)_tryRetain {
2234 return ((id)self)->rootTryRetain();
2237 + (BOOL)_isDeallocating {
2241 - (BOOL)_isDeallocating {
2242 return ((id)self)->rootIsDeallocating();
2245 + (BOOL)allowsWeakReference {
2249 + (BOOL)retainWeakReference {
2253 - (BOOL)allowsWeakReference {
2254 return ! [self _isDeallocating];
2257 - (BOOL)retainWeakReference {
2258 return [self _tryRetain];
2261 + (oneway void)release {
2264 // Replaced by ObjectAlloc
2265 - (oneway void)release {
2266 ((id)self)->rootRelease();
2273 // Replaced by ObjectAlloc
2275 return ((id)self)->rootAutorelease();
2278 + (NSUInteger)retainCount {
2282 - (NSUInteger)retainCount {
2283 return ((id)self)->rootRetainCount();
2287 return _objc_rootAlloc(self);
2290 // Replaced by ObjectAlloc
2291 + (id)allocWithZone:(struct _NSZone *)zone {
2292 return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
2295 // Replaced by CF (throws an NSException)
2301 return _objc_rootInit(self);
2304 // Replaced by CF (throws an NSException)
2309 // Replaced by NSZombies
2311 _objc_rootDealloc(self);
2314 // Previously used by GC. Now a placeholder for binary compatibility.
2318 + (struct _NSZone *)zone {
2319 return (struct _NSZone *)_objc_rootZone(self);
2322 - (struct _NSZone *)zone {
2323 return (struct _NSZone *)_objc_rootZone(self);
2330 + (id)copyWithZone:(struct _NSZone *)zone {
2335 return [(id)self copyWithZone:nil];
2342 + (id)mutableCopyWithZone:(struct _NSZone *)zone {
2347 return [(id)self mutableCopyWithZone:nil];