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
49 /***********************************************************************
51 **********************************************************************/
53 static id defaultBadAllocHandler(Class cls)
55 _objc_fatal("attempt to allocate object of class '%s' failed",
56 cls->nameForLogging());
59 static id(*badAllocHandler)(Class) = &defaultBadAllocHandler;
61 static id callBadAllocHandler(Class cls)
63 // fixme add re-entrancy protection in case allocation fails inside handler
64 return (*badAllocHandler)(cls);
67 void _objc_setBadAllocHandler(id(*newHandler)(Class))
69 badAllocHandler = newHandler;
75 // The order of these bits is important.
76 #define SIDE_TABLE_WEAKLY_REFERENCED (1UL<<0)
77 #define SIDE_TABLE_DEALLOCATING (1UL<<1) // MSB-ward of weak bit
78 #define SIDE_TABLE_RC_ONE (1UL<<2) // MSB-ward of deallocating bit
79 #define SIDE_TABLE_RC_PINNED (1UL<<(WORD_BITS-1))
81 #define SIDE_TABLE_RC_SHIFT 2
82 #define SIDE_TABLE_FLAG_MASK (SIDE_TABLE_RC_ONE-1)
84 // RefcountMap disguises its pointers because we
85 // don't want the table to act as a root for `leaks`.
86 typedef objc::DenseMap<DisguisedPtr<objc_object>,size_t,true> RefcountMap;
88 // Template parameters.
89 enum HaveOld { DontHaveOld = false, DoHaveOld = true };
90 enum HaveNew { DontHaveNew = false, DoHaveNew = true };
95 weak_table_t weak_table;
98 memset(&weak_table, 0, sizeof(weak_table));
102 _objc_fatal("Do not delete SideTable.");
105 void lock() { slock.lock(); }
106 void unlock() { slock.unlock(); }
107 void forceReset() { slock.forceReset(); }
109 // Address-ordered lock discipline for a pair of side tables.
111 template<HaveOld, HaveNew>
112 static void lockTwo(SideTable *lock1, SideTable *lock2);
113 template<HaveOld, HaveNew>
114 static void unlockTwo(SideTable *lock1, SideTable *lock2);
119 void SideTable::lockTwo<DoHaveOld, DoHaveNew>
120 (SideTable *lock1, SideTable *lock2)
122 spinlock_t::lockTwo(&lock1->slock, &lock2->slock);
126 void SideTable::lockTwo<DoHaveOld, DontHaveNew>
127 (SideTable *lock1, SideTable *)
133 void SideTable::lockTwo<DontHaveOld, DoHaveNew>
134 (SideTable *, SideTable *lock2)
140 void SideTable::unlockTwo<DoHaveOld, DoHaveNew>
141 (SideTable *lock1, SideTable *lock2)
143 spinlock_t::unlockTwo(&lock1->slock, &lock2->slock);
147 void SideTable::unlockTwo<DoHaveOld, DontHaveNew>
148 (SideTable *lock1, SideTable *)
154 void SideTable::unlockTwo<DontHaveOld, DoHaveNew>
155 (SideTable *, SideTable *lock2)
161 // We cannot use a C++ static initializer to initialize SideTables because
162 // libc calls us before our C++ initializers run. We also don't want a global
163 // pointer to this struct because of the extra indirection.
164 // Do it the hard way.
165 alignas(StripedMap<SideTable>) static uint8_t
166 SideTableBuf[sizeof(StripedMap<SideTable>)];
168 static void SideTableInit() {
169 new (SideTableBuf) StripedMap<SideTable>();
172 static StripedMap<SideTable>& SideTables() {
173 return *reinterpret_cast<StripedMap<SideTable>*>(SideTableBuf);
176 // anonymous namespace
179 void SideTableLockAll() {
180 SideTables().lockAll();
183 void SideTableUnlockAll() {
184 SideTables().unlockAll();
187 void SideTableForceResetAll() {
188 SideTables().forceResetAll();
191 void SideTableDefineLockOrder() {
192 SideTables().defineLockOrder();
195 void SideTableLocksPrecedeLock(const void *newlock) {
196 SideTables().precedeLock(newlock);
199 void SideTableLocksSucceedLock(const void *oldlock) {
200 SideTables().succeedLock(oldlock);
203 void SideTableLocksPrecedeLocks(StripedMap<spinlock_t>& newlocks) {
206 while ((newlock = newlocks.getLock(i++))) {
207 SideTables().precedeLock(newlock);
211 void SideTableLocksSucceedLocks(StripedMap<spinlock_t>& oldlocks) {
214 while ((oldlock = oldlocks.getLock(i++))) {
215 SideTables().succeedLock(oldlock);
220 // The -fobjc-arc flag causes the compiler to issue calls to objc_{retain/release/autorelease/retain_block}
223 id objc_retainBlock(id x) {
224 return (id)_Block_copy(x);
228 // The following SHOULD be called by the compiler directly, but the request hasn't been made yet :-)
231 BOOL objc_should_deallocate(id object) {
236 objc_retain_autorelease(id obj)
238 return objc_autorelease(objc_retain(obj));
243 objc_storeStrong(id *location, id obj)
255 // Update a weak variable.
256 // If HaveOld is true, the variable has an existing value
257 // that needs to be cleaned up. This value might be nil.
258 // If HaveNew is true, there is a new value that needs to be
259 // assigned into the variable. This value might be nil.
260 // If CrashIfDeallocating is true, the process is halted if newObj is
261 // deallocating or newObj's class does not support weak references.
262 // If CrashIfDeallocating is false, nil is stored instead.
263 enum CrashIfDeallocating {
264 DontCrashIfDeallocating = false, DoCrashIfDeallocating = true
266 template <HaveOld haveOld, HaveNew haveNew,
267 CrashIfDeallocating crashIfDeallocating>
269 storeWeak(id *location, objc_object *newObj)
271 assert(haveOld || haveNew);
272 if (!haveNew) assert(newObj == nil);
274 Class previouslyInitializedClass = nil;
279 // Acquire locks for old and new values.
280 // Order by lock address to prevent lock ordering problems.
281 // Retry if the old value changes underneath us.
285 oldTable = &SideTables()[oldObj];
290 newTable = &SideTables()[newObj];
295 SideTable::lockTwo<haveOld, haveNew>(oldTable, newTable);
297 if (haveOld && *location != oldObj) {
298 SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
302 // Prevent a deadlock between the weak reference machinery
303 // and the +initialize machinery by ensuring that no
304 // weakly-referenced object has an un-+initialized isa.
305 if (haveNew && newObj) {
306 Class cls = newObj->getIsa();
307 if (cls != previouslyInitializedClass &&
308 !((objc_class *)cls)->isInitialized())
310 SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
311 class_initialize(cls, (id)newObj);
313 // If this class is finished with +initialize then we're good.
314 // If this class is still running +initialize on this thread
315 // (i.e. +initialize called storeWeak on an instance of itself)
316 // then we may proceed but it will appear initializing and
317 // not yet initialized to the check above.
318 // Instead set previouslyInitializedClass to recognize it on retry.
319 previouslyInitializedClass = cls;
325 // Clean up old value, if any.
327 weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
330 // Assign new value, if any.
332 newObj = (objc_object *)
333 weak_register_no_lock(&newTable->weak_table, (id)newObj, location,
334 crashIfDeallocating);
335 // weak_register_no_lock returns nil if weak store should be rejected
337 // Set is-weakly-referenced bit in refcount table.
338 if (newObj && !newObj->isTaggedPointer()) {
339 newObj->setWeaklyReferenced_nolock();
342 // Do not set *location anywhere else. That would introduce a race.
343 *location = (id)newObj;
346 // No new value. The storage is not changed.
349 SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
356 * This function stores a new value into a __weak variable. It would
357 * be used anywhere a __weak variable is the target of an assignment.
359 * @param location The address of the weak pointer itself
360 * @param newObj The new object this weak ptr should now point to
365 objc_storeWeak(id *location, id newObj)
367 return storeWeak<DoHaveOld, DoHaveNew, DoCrashIfDeallocating>
368 (location, (objc_object *)newObj);
373 * This function stores a new value into a __weak variable.
374 * If the new object is deallocating or the new object's class
375 * does not support weak references, stores nil instead.
377 * @param location The address of the weak pointer itself
378 * @param newObj The new object this weak ptr should now point to
380 * @return The value stored (either the new object or nil)
383 objc_storeWeakOrNil(id *location, id newObj)
385 return storeWeak<DoHaveOld, DoHaveNew, DontCrashIfDeallocating>
386 (location, (objc_object *)newObj);
391 * Initialize a fresh weak pointer to some object location.
392 * It would be used for code like:
398 * __weak id weakPtr = o;
400 * This function IS NOT thread-safe with respect to concurrent
401 * modifications to the weak variable. (Concurrent weak clear is safe.)
403 * @param location Address of __weak ptr.
404 * @param newObj Object ptr.
407 objc_initWeak(id *location, id newObj)
414 return storeWeak<DontHaveOld, DoHaveNew, DoCrashIfDeallocating>
415 (location, (objc_object*)newObj);
419 objc_initWeakOrNil(id *location, id newObj)
426 return storeWeak<DontHaveOld, DoHaveNew, DontCrashIfDeallocating>
427 (location, (objc_object*)newObj);
432 * Destroys the relationship between a weak pointer
433 * and the object it is referencing in the internal weak
434 * table. If the weak pointer is not referencing anything,
435 * there is no need to edit the weak table.
437 * This function IS NOT thread-safe with respect to concurrent
438 * modifications to the weak variable. (Concurrent weak clear is safe.)
440 * @param location The weak pointer address.
443 objc_destroyWeak(id *location)
445 (void)storeWeak<DoHaveOld, DontHaveNew, DontCrashIfDeallocating>
451 Once upon a time we eagerly cleared *location if we saw the object
452 was deallocating. This confuses code like NSPointerFunctions which
453 tries to pre-flight the raw storage and assumes if the storage is
454 zero then the weak system is done interfering. That is false: the
455 weak system is still going to check and clear the storage later.
456 This can cause objc_weak_error complaints and crashes.
457 So we now don't touch the storage until deallocation completes.
461 objc_loadWeakRetained(id *location)
470 // fixme std::atomic this load
472 if (!obj) return nil;
473 if (obj->isTaggedPointer()) return obj;
475 table = &SideTables()[obj];
478 if (*location != obj) {
486 if (! cls->hasCustomRR()) {
487 // Fast case. We know +initialize is complete because
488 // default-RR can never be set before then.
489 assert(cls->isInitialized());
490 if (! obj->rootTryRetain()) {
495 // Slow case. We must check for +initialize and call it outside
496 // the lock if necessary in order to avoid deadlocks.
497 if (cls->isInitialized() || _thisThreadIsInitializingClass(cls)) {
498 BOOL (*tryRetain)(id, SEL) = (BOOL(*)(id, SEL))
499 class_getMethodImplementation(cls, SEL_retainWeakReference);
500 if ((IMP)tryRetain == _objc_msgForward) {
503 else if (! (*tryRetain)(obj, SEL_retainWeakReference)) {
509 class_initialize(cls, obj);
519 * This loads the object referenced by a weak pointer and returns it, after
520 * retaining and autoreleasing the object to ensure that it stays alive
521 * long enough for the caller to use it. This function would be used
522 * anywhere a __weak variable is used in an expression.
524 * @param location The weak pointer address
526 * @return The object pointed to by \e location, or \c nil if \e location is \c nil.
529 objc_loadWeak(id *location)
531 if (!*location) return nil;
532 return objc_autorelease(objc_loadWeakRetained(location));
537 * This function copies a weak pointer from one location to another,
538 * when the destination doesn't already contain a weak pointer. It
539 * would be used for code like:
541 * __weak id src = ...;
542 * __weak id dst = src;
544 * This function IS NOT thread-safe with respect to concurrent
545 * modifications to the destination variable. (Concurrent weak clear is safe.)
547 * @param dst The destination variable.
548 * @param src The source variable.
551 objc_copyWeak(id *dst, id *src)
553 id obj = objc_loadWeakRetained(src);
554 objc_initWeak(dst, obj);
559 * Move a weak pointer from one location to another.
560 * Before the move, the destination must be uninitialized.
561 * After the move, the source is nil.
563 * This function IS NOT thread-safe with respect to concurrent
564 * modifications to either weak variable. (Concurrent weak clear is safe.)
568 objc_moveWeak(id *dst, id *src)
570 objc_copyWeak(dst, src);
571 objc_destroyWeak(src);
576 /***********************************************************************
577 Autorelease pool implementation
579 A thread's autorelease pool is a stack of pointers.
580 Each pointer is either an object to release, or POOL_BOUNDARY which is
581 an autorelease pool boundary.
582 A pool token is a pointer to the POOL_BOUNDARY for that pool. When
583 the pool is popped, every object hotter than the sentinel is released.
584 The stack is divided into a doubly-linked list of pages. Pages are added
585 and deleted as necessary.
586 Thread-local storage points to the hot page, where newly autoreleased
588 **********************************************************************/
590 // Set this to 1 to mprotect() autorelease pool contents
591 #define PROTECT_AUTORELEASEPOOL 0
593 // Set this to 1 to validate the entire autorelease pool header all the time
594 // (i.e. use check() instead of fastcheck() everywhere)
595 #define CHECK_AUTORELEASEPOOL (DEBUG)
597 BREAKPOINT_FUNCTION(void objc_autoreleaseNoPool(id obj));
598 BREAKPOINT_FUNCTION(void objc_autoreleasePoolInvalid(const void *token));
603 static const uint32_t M0 = 0xA1A1A1A1;
604 # define M1 "AUTORELEASE!"
605 static const size_t M1_len = 12;
609 assert(M1_len == strlen(M1));
610 assert(M1_len == 3 * sizeof(m[1]));
613 strncpy((char *)&m[1], M1, M1_len);
617 // Clear magic before deallocation.
618 // This prevents some false positives in memory debugging tools.
619 // fixme semantically this should be memset_s(), but the
620 // compiler doesn't optimize that at all (rdar://44856676).
621 volatile uint64_t *p = (volatile uint64_t *)m;
626 return (m[0] == M0 && 0 == strncmp((char *)&m[1], M1, M1_len));
629 bool fastcheck() const {
630 #if CHECK_AUTORELEASEPOOL
641 class AutoreleasePoolPage
643 // EMPTY_POOL_PLACEHOLDER is stored in TLS when exactly one pool is
644 // pushed and it has never contained any objects. This saves memory
645 // when the top level (i.e. libdispatch) pushes and pops pools but
647 # define EMPTY_POOL_PLACEHOLDER ((id*)1)
649 # define POOL_BOUNDARY nil
650 static pthread_key_t const key = AUTORELEASE_POOL_KEY;
651 static uint8_t const SCRIBBLE = 0xA3; // 0xA3A3A3A3 after releasing
652 static size_t const SIZE =
653 #if PROTECT_AUTORELEASEPOOL
654 PAGE_MAX_SIZE; // must be multiple of vm page size
656 PAGE_MAX_SIZE; // size and alignment, power of 2
658 static size_t const COUNT = SIZE / sizeof(id);
662 pthread_t const thread;
663 AutoreleasePoolPage * const parent;
664 AutoreleasePoolPage *child;
665 uint32_t const depth;
668 // SIZE-sizeof(*this) bytes of contents follow
670 static void * operator new(size_t size) {
671 return malloc_zone_memalign(malloc_default_zone(), SIZE, SIZE);
673 static void operator delete(void * p) {
677 inline void protect() {
678 #if PROTECT_AUTORELEASEPOOL
679 mprotect(this, SIZE, PROT_READ);
684 inline void unprotect() {
685 #if PROTECT_AUTORELEASEPOOL
687 mprotect(this, SIZE, PROT_READ | PROT_WRITE);
691 AutoreleasePoolPage(AutoreleasePoolPage *newParent)
692 : magic(), next(begin()), thread(pthread_self()),
693 parent(newParent), child(nil),
694 depth(parent ? 1+parent->depth : 0),
695 hiwat(parent ? parent->hiwat : 0)
699 assert(!parent->child);
701 parent->child = this;
707 ~AutoreleasePoolPage()
713 // Not recursive: we don't want to blow out the stack
714 // if a thread accumulates a stupendous amount of garbage
719 void busted(bool die = true)
722 (die ? _objc_fatal : _objc_inform)
723 ("autorelease pool page %p corrupted\n"
724 " magic 0x%08x 0x%08x 0x%08x 0x%08x\n"
725 " should be 0x%08x 0x%08x 0x%08x 0x%08x\n"
729 magic.m[0], magic.m[1], magic.m[2], magic.m[3],
730 right.m[0], right.m[1], right.m[2], right.m[3],
731 this->thread, pthread_self());
734 void check(bool die = true)
736 if (!magic.check() || !pthread_equal(thread, pthread_self())) {
741 void fastcheck(bool die = true)
743 #if CHECK_AUTORELEASEPOOL
746 if (! magic.fastcheck()) {
754 return (id *) ((uint8_t *)this+sizeof(*this));
758 return (id *) ((uint8_t *)this+SIZE);
762 return next == begin();
766 return next == end();
769 bool lessThanHalfFull() {
770 return (next - begin() < (end() - begin()) / 2);
777 id *ret = next; // faster than `return next-1` because of aliasing
785 releaseUntil(begin());
788 void releaseUntil(id *stop)
790 // Not recursive: we don't want to blow out the stack
791 // if a thread accumulates a stupendous amount of garbage
793 while (this->next != stop) {
794 // Restart from hotPage() every time, in case -release
795 // autoreleased more objects
796 AutoreleasePoolPage *page = hotPage();
798 // fixme I think this `while` can be `if`, but I can't prove it
799 while (page->empty()) {
805 id obj = *--page->next;
806 memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
809 if (obj != POOL_BOUNDARY) {
817 // we expect any children to be completely empty
818 for (AutoreleasePoolPage *page = child; page; page = page->child) {
819 assert(page->empty());
826 // Not recursive: we don't want to blow out the stack
827 // if a thread accumulates a stupendous amount of garbage
828 AutoreleasePoolPage *page = this;
829 while (page->child) page = page->child;
831 AutoreleasePoolPage *deathptr;
841 } while (deathptr != this);
844 static void tls_dealloc(void *p)
846 if (p == (void*)EMPTY_POOL_PLACEHOLDER) {
847 // No objects or pool pages to clean up here.
851 // reinstate TLS value while we work
852 setHotPage((AutoreleasePoolPage *)p);
854 if (AutoreleasePoolPage *page = coldPage()) {
855 if (!page->empty()) pop(page->begin()); // pop all of the pools
856 if (DebugMissingPools || DebugPoolAllocation) {
857 // pop() killed the pages already
859 page->kill(); // free all of the pages
863 // clear TLS value so TLS destruction doesn't loop
867 static AutoreleasePoolPage *pageForPointer(const void *p)
869 return pageForPointer((uintptr_t)p);
872 static AutoreleasePoolPage *pageForPointer(uintptr_t p)
874 AutoreleasePoolPage *result;
875 uintptr_t offset = p % SIZE;
877 assert(offset >= sizeof(AutoreleasePoolPage));
879 result = (AutoreleasePoolPage *)(p - offset);
886 static inline bool haveEmptyPoolPlaceholder()
888 id *tls = (id *)tls_get_direct(key);
889 return (tls == EMPTY_POOL_PLACEHOLDER);
892 static inline id* setEmptyPoolPlaceholder()
894 assert(tls_get_direct(key) == nil);
895 tls_set_direct(key, (void *)EMPTY_POOL_PLACEHOLDER);
896 return EMPTY_POOL_PLACEHOLDER;
899 static inline AutoreleasePoolPage *hotPage()
901 AutoreleasePoolPage *result = (AutoreleasePoolPage *)
903 if ((id *)result == EMPTY_POOL_PLACEHOLDER) return nil;
904 if (result) result->fastcheck();
908 static inline void setHotPage(AutoreleasePoolPage *page)
910 if (page) page->fastcheck();
911 tls_set_direct(key, (void *)page);
914 static inline AutoreleasePoolPage *coldPage()
916 AutoreleasePoolPage *result = hotPage();
918 while (result->parent) {
919 result = result->parent;
927 static inline id *autoreleaseFast(id obj)
929 AutoreleasePoolPage *page = hotPage();
930 if (page && !page->full()) {
931 return page->add(obj);
933 return autoreleaseFullPage(obj, page);
935 return autoreleaseNoPage(obj);
939 static __attribute__((noinline))
940 id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page)
942 // The hot page is full.
943 // Step to the next non-full page, adding a new page if necessary.
944 // Then add the object to that page.
945 assert(page == hotPage());
946 assert(page->full() || DebugPoolAllocation);
949 if (page->child) page = page->child;
950 else page = new AutoreleasePoolPage(page);
951 } while (page->full());
954 return page->add(obj);
957 static __attribute__((noinline))
958 id *autoreleaseNoPage(id obj)
960 // "No page" could mean no pool has been pushed
961 // or an empty placeholder pool has been pushed and has no contents yet
964 bool pushExtraBoundary = false;
965 if (haveEmptyPoolPlaceholder()) {
966 // We are pushing a second pool over the empty placeholder pool
967 // or pushing the first object into the empty placeholder pool.
968 // Before doing that, push a pool boundary on behalf of the pool
969 // that is currently represented by the empty placeholder.
970 pushExtraBoundary = true;
972 else if (obj != POOL_BOUNDARY && DebugMissingPools) {
973 // We are pushing an object with no pool in place,
974 // and no-pool debugging was requested by environment.
975 _objc_inform("MISSING POOLS: (%p) Object %p of class %s "
976 "autoreleased with no pool in place - "
977 "just leaking - break on "
978 "objc_autoreleaseNoPool() to debug",
979 pthread_self(), (void*)obj, object_getClassName(obj));
980 objc_autoreleaseNoPool(obj);
983 else if (obj == POOL_BOUNDARY && !DebugPoolAllocation) {
984 // We are pushing a pool with no pool in place,
985 // and alloc-per-pool debugging was not requested.
986 // Install and return the empty pool placeholder.
987 return setEmptyPoolPlaceholder();
990 // We are pushing an object or a non-placeholder'd pool.
992 // Install the first page.
993 AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
996 // Push a boundary on behalf of the previously-placeholder'd pool.
997 if (pushExtraBoundary) {
998 page->add(POOL_BOUNDARY);
1001 // Push the requested object or pool.
1002 return page->add(obj);
1006 static __attribute__((noinline))
1007 id *autoreleaseNewPage(id obj)
1009 AutoreleasePoolPage *page = hotPage();
1010 if (page) return autoreleaseFullPage(obj, page);
1011 else return autoreleaseNoPage(obj);
1015 static inline id autorelease(id obj)
1018 assert(!obj->isTaggedPointer());
1019 id *dest __unused = autoreleaseFast(obj);
1020 assert(!dest || dest == EMPTY_POOL_PLACEHOLDER || *dest == obj);
1025 static inline void *push()
1028 if (DebugPoolAllocation) {
1029 // Each autorelease pool starts on a new pool page.
1030 dest = autoreleaseNewPage(POOL_BOUNDARY);
1032 dest = autoreleaseFast(POOL_BOUNDARY);
1034 assert(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
1038 static void badPop(void *token)
1040 // Error. For bincompat purposes this is not
1041 // fatal in executables built with old SDKs.
1043 if (DebugPoolAllocation || sdkIsAtLeast(10_12, 10_0, 10_0, 3_0, 2_0)) {
1044 // OBJC_DEBUG_POOL_ALLOCATION or new SDK. Bad pop is fatal.
1046 ("Invalid or prematurely-freed autorelease pool %p.", token);
1049 // Old SDK. Bad pop is warned once.
1050 static bool complained = false;
1053 _objc_inform_now_and_on_crash
1054 ("Invalid or prematurely-freed autorelease pool %p. "
1055 "Set a breakpoint on objc_autoreleasePoolInvalid to debug. "
1056 "Proceeding anyway because the app is old "
1057 "(SDK version " SDK_FORMAT "). Memory errors are likely.",
1058 token, FORMAT_SDK(sdkVersion()));
1060 objc_autoreleasePoolInvalid(token);
1063 static inline void pop(void *token)
1065 AutoreleasePoolPage *page;
1068 if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
1069 // Popping the top-level placeholder pool.
1071 // Pool was used. Pop its contents normally.
1072 // Pool pages remain allocated for re-use as usual.
1073 pop(coldPage()->begin());
1075 // Pool was never used. Clear the placeholder.
1081 page = pageForPointer(token);
1083 if (*stop != POOL_BOUNDARY) {
1084 if (stop == page->begin() && !page->parent) {
1085 // Start of coldest page may correctly not be POOL_BOUNDARY:
1086 // 1. top-level pool is popped, leaving the cold page in place
1087 // 2. an object is autoreleased with no pool
1089 // Error. For bincompat purposes this is not
1090 // fatal in executables built with old SDKs.
1091 return badPop(token);
1095 if (PrintPoolHiwat) printHiwat();
1097 page->releaseUntil(stop);
1099 // memory: delete empty children
1100 if (DebugPoolAllocation && page->empty()) {
1101 // special case: delete everything during page-per-pool debugging
1102 AutoreleasePoolPage *parent = page->parent;
1105 } else if (DebugMissingPools && page->empty() && !page->parent) {
1106 // special case: delete everything for pop(top)
1107 // when debugging missing autorelease pools
1111 else if (page->child) {
1112 // hysteresis: keep one empty child if page is more than half full
1113 if (page->lessThanHalfFull()) {
1114 page->child->kill();
1116 else if (page->child->child) {
1117 page->child->child->kill();
1124 int r __unused = pthread_key_init_np(AutoreleasePoolPage::key,
1125 AutoreleasePoolPage::tls_dealloc);
1131 _objc_inform("[%p] ................ PAGE %s %s %s", this,
1132 full() ? "(full)" : "",
1133 this == hotPage() ? "(hot)" : "",
1134 this == coldPage() ? "(cold)" : "");
1136 for (id *p = begin(); p < next; p++) {
1137 if (*p == POOL_BOUNDARY) {
1138 _objc_inform("[%p] ################ POOL %p", p, p);
1140 _objc_inform("[%p] %#16lx %s",
1141 p, (unsigned long)*p, object_getClassName(*p));
1146 static void printAll()
1148 _objc_inform("##############");
1149 _objc_inform("AUTORELEASE POOLS for thread %p", pthread_self());
1151 AutoreleasePoolPage *page;
1152 ptrdiff_t objects = 0;
1153 for (page = coldPage(); page; page = page->child) {
1154 objects += page->next - page->begin();
1156 _objc_inform("%llu releases pending.", (unsigned long long)objects);
1158 if (haveEmptyPoolPlaceholder()) {
1159 _objc_inform("[%p] ................ PAGE (placeholder)",
1160 EMPTY_POOL_PLACEHOLDER);
1161 _objc_inform("[%p] ################ POOL (placeholder)",
1162 EMPTY_POOL_PLACEHOLDER);
1165 for (page = coldPage(); page; page = page->child) {
1170 _objc_inform("##############");
1173 static void printHiwat()
1175 // Check and propagate high water mark
1176 // Ignore high water marks under 256 to suppress noise.
1177 AutoreleasePoolPage *p = hotPage();
1178 uint32_t mark = p->depth*COUNT + (uint32_t)(p->next - p->begin());
1179 if (mark > p->hiwat && mark > 256) {
1180 for( ; p; p = p->parent) {
1186 _objc_inform("POOL HIGHWATER: new high water mark of %u "
1187 "pending releases for thread %p:",
1188 mark, pthread_self());
1191 int count = backtrace(stack, sizeof(stack)/sizeof(stack[0]));
1192 char **sym = backtrace_symbols(stack, count);
1193 for (int i = 0; i < count; i++) {
1194 _objc_inform("POOL HIGHWATER: %s", sym[i]);
1200 #undef POOL_BOUNDARY
1203 // anonymous namespace
1207 /***********************************************************************
1208 * Slow paths for inline control
1209 **********************************************************************/
1211 #if SUPPORT_NONPOINTER_ISA
1214 objc_object::rootRetain_overflow(bool tryRetain)
1216 return rootRetain(tryRetain, true);
1221 objc_object::rootRelease_underflow(bool performDealloc)
1223 return rootRelease(performDealloc, true);
1227 // Slow path of clearDeallocating()
1228 // for objects with nonpointer isa
1229 // that were ever weakly referenced
1230 // or whose retain count ever overflowed to the side table.
1232 objc_object::clearDeallocating_slow()
1234 assert(isa.nonpointer && (isa.weakly_referenced || isa.has_sidetable_rc));
1236 SideTable& table = SideTables()[this];
1238 if (isa.weakly_referenced) {
1239 weak_clear_no_lock(&table.weak_table, (id)this);
1241 if (isa.has_sidetable_rc) {
1242 table.refcnts.erase(this);
1249 __attribute__((noinline,used))
1251 objc_object::rootAutorelease2()
1253 assert(!isTaggedPointer());
1254 return AutoreleasePoolPage::autorelease((id)this);
1258 BREAKPOINT_FUNCTION(
1259 void objc_overrelease_during_dealloc_error(void)
1265 objc_object::overrelease_error()
1267 _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);
1268 objc_overrelease_during_dealloc_error();
1269 return false; // allow rootRelease() to tail-call this
1273 /***********************************************************************
1274 * Retain count operations for side table.
1275 **********************************************************************/
1279 // Used to assert that an object is not present in the side table.
1281 objc_object::sidetable_present()
1283 bool result = false;
1284 SideTable& table = SideTables()[this];
1288 RefcountMap::iterator it = table.refcnts.find(this);
1289 if (it != table.refcnts.end()) result = true;
1291 if (weak_is_registered_no_lock(&table.weak_table, (id)this)) result = true;
1299 #if SUPPORT_NONPOINTER_ISA
1302 objc_object::sidetable_lock()
1304 SideTable& table = SideTables()[this];
1309 objc_object::sidetable_unlock()
1311 SideTable& table = SideTables()[this];
1316 // Move the entire retain count to the side table,
1317 // as well as isDeallocating and weaklyReferenced.
1319 objc_object::sidetable_moveExtraRC_nolock(size_t extra_rc,
1320 bool isDeallocating,
1321 bool weaklyReferenced)
1323 assert(!isa.nonpointer); // should already be changed to raw pointer
1324 SideTable& table = SideTables()[this];
1326 size_t& refcntStorage = table.refcnts[this];
1327 size_t oldRefcnt = refcntStorage;
1328 // not deallocating - that was in the isa
1329 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1330 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1333 size_t refcnt = addc(oldRefcnt, extra_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
1334 if (carry) refcnt = SIDE_TABLE_RC_PINNED;
1335 if (isDeallocating) refcnt |= SIDE_TABLE_DEALLOCATING;
1336 if (weaklyReferenced) refcnt |= SIDE_TABLE_WEAKLY_REFERENCED;
1338 refcntStorage = refcnt;
1342 // Move some retain counts to the side table from the isa field.
1343 // Returns true if the object is now pinned.
1345 objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)
1347 assert(isa.nonpointer);
1348 SideTable& table = SideTables()[this];
1350 size_t& refcntStorage = table.refcnts[this];
1351 size_t oldRefcnt = refcntStorage;
1352 // isa-side bits should not be set here
1353 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1354 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1356 if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;
1360 addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
1363 SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK);
1367 refcntStorage = newRefcnt;
1373 // Move some retain counts from the side table to the isa field.
1374 // Returns the actual count subtracted, which may be less than the request.
1376 objc_object::sidetable_subExtraRC_nolock(size_t delta_rc)
1378 assert(isa.nonpointer);
1379 SideTable& table = SideTables()[this];
1381 RefcountMap::iterator it = table.refcnts.find(this);
1382 if (it == table.refcnts.end() || it->second == 0) {
1383 // Side table retain count is zero. Can't borrow.
1386 size_t oldRefcnt = it->second;
1388 // isa-side bits should not be set here
1389 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1390 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1392 size_t newRefcnt = oldRefcnt - (delta_rc << SIDE_TABLE_RC_SHIFT);
1393 assert(oldRefcnt > newRefcnt); // shouldn't underflow
1394 it->second = newRefcnt;
1400 objc_object::sidetable_getExtraRC_nolock()
1402 assert(isa.nonpointer);
1403 SideTable& table = SideTables()[this];
1404 RefcountMap::iterator it = table.refcnts.find(this);
1405 if (it == table.refcnts.end()) return 0;
1406 else return it->second >> SIDE_TABLE_RC_SHIFT;
1410 // SUPPORT_NONPOINTER_ISA
1415 objc_object::sidetable_retain()
1417 #if SUPPORT_NONPOINTER_ISA
1418 assert(!isa.nonpointer);
1420 SideTable& table = SideTables()[this];
1423 size_t& refcntStorage = table.refcnts[this];
1424 if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) {
1425 refcntStorage += SIDE_TABLE_RC_ONE;
1434 objc_object::sidetable_tryRetain()
1436 #if SUPPORT_NONPOINTER_ISA
1437 assert(!isa.nonpointer);
1439 SideTable& table = SideTables()[this];
1442 // _objc_rootTryRetain() is called exclusively by _objc_loadWeak(),
1443 // which already acquired the lock on our behalf.
1445 // fixme can't do this efficiently with os_lock_handoff_s
1446 // if (table.slock == 0) {
1447 // _objc_fatal("Do not call -_tryRetain.");
1451 RefcountMap::iterator it = table.refcnts.find(this);
1452 if (it == table.refcnts.end()) {
1453 table.refcnts[this] = SIDE_TABLE_RC_ONE;
1454 } else if (it->second & SIDE_TABLE_DEALLOCATING) {
1456 } else if (! (it->second & SIDE_TABLE_RC_PINNED)) {
1457 it->second += SIDE_TABLE_RC_ONE;
1465 objc_object::sidetable_retainCount()
1467 SideTable& table = SideTables()[this];
1469 size_t refcnt_result = 1;
1472 RefcountMap::iterator it = table.refcnts.find(this);
1473 if (it != table.refcnts.end()) {
1474 // this is valid for SIDE_TABLE_RC_PINNED too
1475 refcnt_result += it->second >> SIDE_TABLE_RC_SHIFT;
1478 return refcnt_result;
1483 objc_object::sidetable_isDeallocating()
1485 SideTable& table = SideTables()[this];
1488 // _objc_rootIsDeallocating() is called exclusively by _objc_storeWeak(),
1489 // which already acquired the lock on our behalf.
1492 // fixme can't do this efficiently with os_lock_handoff_s
1493 // if (table.slock == 0) {
1494 // _objc_fatal("Do not call -_isDeallocating.");
1497 RefcountMap::iterator it = table.refcnts.find(this);
1498 return (it != table.refcnts.end()) && (it->second & SIDE_TABLE_DEALLOCATING);
1503 objc_object::sidetable_isWeaklyReferenced()
1505 bool result = false;
1507 SideTable& table = SideTables()[this];
1510 RefcountMap::iterator it = table.refcnts.find(this);
1511 if (it != table.refcnts.end()) {
1512 result = it->second & SIDE_TABLE_WEAKLY_REFERENCED;
1522 objc_object::sidetable_setWeaklyReferenced_nolock()
1524 #if SUPPORT_NONPOINTER_ISA
1525 assert(!isa.nonpointer);
1528 SideTable& table = SideTables()[this];
1530 table.refcnts[this] |= SIDE_TABLE_WEAKLY_REFERENCED;
1535 // return uintptr_t instead of bool so that the various raw-isa
1536 // -release paths all return zero in eax
1538 objc_object::sidetable_release(bool performDealloc)
1540 #if SUPPORT_NONPOINTER_ISA
1541 assert(!isa.nonpointer);
1543 SideTable& table = SideTables()[this];
1545 bool do_dealloc = false;
1548 RefcountMap::iterator it = table.refcnts.find(this);
1549 if (it == table.refcnts.end()) {
1551 table.refcnts[this] = SIDE_TABLE_DEALLOCATING;
1552 } else if (it->second < SIDE_TABLE_DEALLOCATING) {
1553 // SIDE_TABLE_WEAKLY_REFERENCED may be set. Don't change it.
1555 it->second |= SIDE_TABLE_DEALLOCATING;
1556 } else if (! (it->second & SIDE_TABLE_RC_PINNED)) {
1557 it->second -= SIDE_TABLE_RC_ONE;
1560 if (do_dealloc && performDealloc) {
1561 ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
1568 objc_object::sidetable_clearDeallocating()
1570 SideTable& table = SideTables()[this];
1572 // clear any weak table items
1573 // clear extra retain count and deallocating bit
1574 // (fixme warn or abort if extra retain count == 0 ?)
1576 RefcountMap::iterator it = table.refcnts.find(this);
1577 if (it != table.refcnts.end()) {
1578 if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
1579 weak_clear_no_lock(&table.weak_table, (id)this);
1581 table.refcnts.erase(it);
1587 /***********************************************************************
1588 * Optimized retain/release/autorelease entrypoints
1589 **********************************************************************/
1594 __attribute__((aligned(16)))
1598 if (!obj) return obj;
1599 if (obj->isTaggedPointer()) return obj;
1600 return obj->retain();
1604 __attribute__((aligned(16)))
1606 objc_release(id obj)
1609 if (obj->isTaggedPointer()) return;
1610 return obj->release();
1614 __attribute__((aligned(16)))
1616 objc_autorelease(id obj)
1618 if (!obj) return obj;
1619 if (obj->isTaggedPointer()) return obj;
1620 return obj->autorelease();
1629 id objc_retain(id obj) { return [obj retain]; }
1630 void objc_release(id obj) { [obj release]; }
1631 id objc_autorelease(id obj) { return [obj autorelease]; }
1637 /***********************************************************************
1638 * Basic operations for root class implementations a.k.a. _objc_root*()
1639 **********************************************************************/
1642 _objc_rootTryRetain(id obj)
1646 return obj->rootTryRetain();
1650 _objc_rootIsDeallocating(id obj)
1654 return obj->rootIsDeallocating();
1659 objc_clear_deallocating(id obj)
1663 if (obj->isTaggedPointer()) return;
1664 obj->clearDeallocating();
1669 _objc_rootReleaseWasZero(id obj)
1673 return obj->rootReleaseShouldDealloc();
1678 _objc_rootAutorelease(id obj)
1681 return obj->rootAutorelease();
1685 _objc_rootRetainCount(id obj)
1689 return obj->rootRetainCount();
1694 _objc_rootRetain(id obj)
1698 return obj->rootRetain();
1702 _objc_rootRelease(id obj)
1711 _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
1716 // allocWithZone under __OBJC2__ ignores the zone parameter
1718 obj = class_createInstance(cls, 0);
1721 obj = class_createInstance(cls, 0);
1724 obj = class_createInstanceFromZone(cls, 0, zone);
1728 if (slowpath(!obj)) obj = callBadAllocHandler(cls);
1733 // Call [cls alloc] or [cls allocWithZone:nil], with appropriate
1734 // shortcutting optimizations.
1735 static ALWAYS_INLINE id
1736 callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
1738 if (slowpath(checkNil && !cls)) return nil;
1741 if (fastpath(!cls->ISA()->hasCustomAWZ())) {
1742 // No alloc/allocWithZone implementation. Go straight to the allocator.
1743 // fixme store hasCustomAWZ in the non-meta class and
1744 // add it to canAllocFast's summary
1745 if (fastpath(cls->canAllocFast())) {
1746 // No ctors, raw isa, etc. Go straight to the metal.
1747 bool dtor = cls->hasCxxDtor();
1748 id obj = (id)calloc(1, cls->bits.fastInstanceSize());
1749 if (slowpath(!obj)) return callBadAllocHandler(cls);
1750 obj->initInstanceIsa(cls, dtor);
1754 // Has ctor or raw isa or something. Use the slower path.
1755 id obj = class_createInstance(cls, 0);
1756 if (slowpath(!obj)) return callBadAllocHandler(cls);
1762 // No shortcuts available.
1763 if (allocWithZone) return [cls allocWithZone:nil];
1768 // Base class implementation of +alloc. cls is not nil.
1769 // Calls [cls allocWithZone:nil].
1771 _objc_rootAlloc(Class cls)
1773 return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
1776 // Calls [cls alloc].
1778 objc_alloc(Class cls)
1780 return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
1783 // Calls [cls allocWithZone:nil].
1785 objc_allocWithZone(Class cls)
1787 return callAlloc(cls, true/*checkNil*/, true/*allocWithZone*/);
1790 // Calls [[cls alloc] init].
1792 objc_alloc_init(Class cls)
1794 return [callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/) init];
1799 _objc_rootDealloc(id obj)
1807 _objc_rootFinalize(id obj __unused)
1810 _objc_fatal("_objc_rootFinalize called with garbage collection off");
1815 _objc_rootInit(id obj)
1817 // In practice, it will be hard to rely on this function.
1818 // Many classes do not properly chain -init calls.
1824 _objc_rootZone(id obj)
1828 // allocWithZone under __OBJC2__ ignores the zone parameter
1829 return malloc_default_zone();
1831 malloc_zone_t *rval = malloc_zone_from_ptr(obj);
1832 return rval ? rval : malloc_default_zone();
1837 _objc_rootHash(id obj)
1839 return (uintptr_t)obj;
1843 objc_autoreleasePoolPush(void)
1845 return AutoreleasePoolPage::push();
1849 objc_autoreleasePoolPop(void *ctxt)
1851 AutoreleasePoolPage::pop(ctxt);
1856 _objc_autoreleasePoolPush(void)
1858 return objc_autoreleasePoolPush();
1862 _objc_autoreleasePoolPop(void *ctxt)
1864 objc_autoreleasePoolPop(ctxt);
1868 _objc_autoreleasePoolPrint(void)
1870 AutoreleasePoolPage::printAll();
1874 // Same as objc_release but suitable for tail-calling
1875 // if you need the value back and don't want to push a frame before this point.
1876 __attribute__((noinline))
1878 objc_releaseAndReturn(id obj)
1884 // Same as objc_retainAutorelease but suitable for tail-calling
1885 // if you don't want to push a frame before this point.
1886 __attribute__((noinline))
1888 objc_retainAutoreleaseAndReturn(id obj)
1890 return objc_retainAutorelease(obj);
1894 // Prepare a value at +1 for return through a +0 autoreleasing convention.
1896 objc_autoreleaseReturnValue(id obj)
1898 if (prepareOptimizedReturn(ReturnAtPlus1)) return obj;
1900 return objc_autorelease(obj);
1903 // Prepare a value at +0 for return through a +0 autoreleasing convention.
1905 objc_retainAutoreleaseReturnValue(id obj)
1907 if (prepareOptimizedReturn(ReturnAtPlus0)) return obj;
1909 // not objc_autoreleaseReturnValue(objc_retain(obj))
1910 // because we don't need another optimization attempt
1911 return objc_retainAutoreleaseAndReturn(obj);
1914 // Accept a value returned through a +0 autoreleasing convention for use at +1.
1916 objc_retainAutoreleasedReturnValue(id obj)
1918 if (acceptOptimizedReturn() == ReturnAtPlus1) return obj;
1920 return objc_retain(obj);
1923 // Accept a value returned through a +0 autoreleasing convention for use at +0.
1925 objc_unsafeClaimAutoreleasedReturnValue(id obj)
1927 if (acceptOptimizedReturn() == ReturnAtPlus0) return obj;
1929 return objc_releaseAndReturn(obj);
1933 objc_retainAutorelease(id obj)
1935 return objc_autorelease(objc_retain(obj));
1939 _objc_deallocOnMainThreadHelper(void *context)
1941 id obj = (id)context;
1945 // convert objc_objectptr_t to id, callee must take ownership.
1946 id objc_retainedObject(objc_objectptr_t pointer) { return (id)pointer; }
1948 // convert objc_objectptr_t to id, without ownership transfer.
1949 id objc_unretainedObject(objc_objectptr_t pointer) { return (id)pointer; }
1951 // convert id to objc_objectptr_t, no ownership transfer.
1952 objc_objectptr_t objc_unretainedPointer(id object) { return object; }
1957 AutoreleasePoolPage::init();
1962 #if SUPPORT_TAGGED_POINTERS
1964 // Placeholder for old debuggers. When they inspect an
1965 // extended tagged pointer object they will see this isa.
1967 @interface __NSUnrecognizedTaggedPointer : NSObject
1970 @implementation __NSUnrecognizedTaggedPointer
1972 -(id) retain { return self; }
1973 -(oneway void) release { }
1974 -(id) autorelease { return self; }
1980 @implementation NSObject
1985 + (void)initialize {
2001 return object_getClass(self);
2004 + (Class)superclass {
2005 return self->superclass;
2008 - (Class)superclass {
2009 return [self class]->superclass;
2012 + (BOOL)isMemberOfClass:(Class)cls {
2013 return object_getClass((id)self) == cls;
2016 - (BOOL)isMemberOfClass:(Class)cls {
2017 return [self class] == cls;
2020 + (BOOL)isKindOfClass:(Class)cls {
2021 for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
2022 if (tcls == cls) return YES;
2027 - (BOOL)isKindOfClass:(Class)cls {
2028 for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
2029 if (tcls == cls) return YES;
2034 + (BOOL)isSubclassOfClass:(Class)cls {
2035 for (Class tcls = self; tcls; tcls = tcls->superclass) {
2036 if (tcls == cls) return YES;
2041 + (BOOL)isAncestorOfObject:(NSObject *)obj {
2042 for (Class tcls = [obj class]; tcls; tcls = tcls->superclass) {
2043 if (tcls == self) return YES;
2048 + (BOOL)instancesRespondToSelector:(SEL)sel {
2049 if (!sel) return NO;
2050 return class_respondsToSelector(self, sel);
2053 + (BOOL)respondsToSelector:(SEL)sel {
2054 if (!sel) return NO;
2055 return class_respondsToSelector_inst(object_getClass(self), sel, self);
2058 - (BOOL)respondsToSelector:(SEL)sel {
2059 if (!sel) return NO;
2060 return class_respondsToSelector_inst([self class], sel, self);
2063 + (BOOL)conformsToProtocol:(Protocol *)protocol {
2064 if (!protocol) return NO;
2065 for (Class tcls = self; tcls; tcls = tcls->superclass) {
2066 if (class_conformsToProtocol(tcls, protocol)) return YES;
2071 - (BOOL)conformsToProtocol:(Protocol *)protocol {
2072 if (!protocol) return NO;
2073 for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
2074 if (class_conformsToProtocol(tcls, protocol)) return YES;
2079 + (NSUInteger)hash {
2080 return _objc_rootHash(self);
2083 - (NSUInteger)hash {
2084 return _objc_rootHash(self);
2087 + (BOOL)isEqual:(id)obj {
2088 return obj == (id)self;
2091 - (BOOL)isEqual:(id)obj {
2113 + (IMP)instanceMethodForSelector:(SEL)sel {
2114 if (!sel) [self doesNotRecognizeSelector:sel];
2115 return class_getMethodImplementation(self, sel);
2118 + (IMP)methodForSelector:(SEL)sel {
2119 if (!sel) [self doesNotRecognizeSelector:sel];
2120 return object_getMethodImplementation((id)self, sel);
2123 - (IMP)methodForSelector:(SEL)sel {
2124 if (!sel) [self doesNotRecognizeSelector:sel];
2125 return object_getMethodImplementation(self, sel);
2128 + (BOOL)resolveClassMethod:(SEL)sel {
2132 + (BOOL)resolveInstanceMethod:(SEL)sel {
2136 // Replaced by CF (throws an NSException)
2137 + (void)doesNotRecognizeSelector:(SEL)sel {
2138 _objc_fatal("+[%s %s]: unrecognized selector sent to instance %p",
2139 class_getName(self), sel_getName(sel), self);
2142 // Replaced by CF (throws an NSException)
2143 - (void)doesNotRecognizeSelector:(SEL)sel {
2144 _objc_fatal("-[%s %s]: unrecognized selector sent to instance %p",
2145 object_getClassName(self), sel_getName(sel), self);
2149 + (id)performSelector:(SEL)sel {
2150 if (!sel) [self doesNotRecognizeSelector:sel];
2151 return ((id(*)(id, SEL))objc_msgSend)((id)self, sel);
2154 + (id)performSelector:(SEL)sel withObject:(id)obj {
2155 if (!sel) [self doesNotRecognizeSelector:sel];
2156 return ((id(*)(id, SEL, id))objc_msgSend)((id)self, sel, obj);
2159 + (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
2160 if (!sel) [self doesNotRecognizeSelector:sel];
2161 return ((id(*)(id, SEL, id, id))objc_msgSend)((id)self, sel, obj1, obj2);
2164 - (id)performSelector:(SEL)sel {
2165 if (!sel) [self doesNotRecognizeSelector:sel];
2166 return ((id(*)(id, SEL))objc_msgSend)(self, sel);
2169 - (id)performSelector:(SEL)sel withObject:(id)obj {
2170 if (!sel) [self doesNotRecognizeSelector:sel];
2171 return ((id(*)(id, SEL, id))objc_msgSend)(self, sel, obj);
2174 - (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
2175 if (!sel) [self doesNotRecognizeSelector:sel];
2176 return ((id(*)(id, SEL, id, id))objc_msgSend)(self, sel, obj1, obj2);
2180 // Replaced by CF (returns an NSMethodSignature)
2181 + (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)sel {
2182 _objc_fatal("+[NSObject instanceMethodSignatureForSelector:] "
2183 "not available without CoreFoundation");
2186 // Replaced by CF (returns an NSMethodSignature)
2187 + (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
2188 _objc_fatal("+[NSObject methodSignatureForSelector:] "
2189 "not available without CoreFoundation");
2192 // Replaced by CF (returns an NSMethodSignature)
2193 - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
2194 _objc_fatal("-[NSObject methodSignatureForSelector:] "
2195 "not available without CoreFoundation");
2198 + (void)forwardInvocation:(NSInvocation *)invocation {
2199 [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
2202 - (void)forwardInvocation:(NSInvocation *)invocation {
2203 [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
2206 + (id)forwardingTargetForSelector:(SEL)sel {
2210 - (id)forwardingTargetForSelector:(SEL)sel {
2215 // Replaced by CF (returns an NSString)
2216 + (NSString *)description {
2220 // Replaced by CF (returns an NSString)
2221 - (NSString *)description {
2225 + (NSString *)debugDescription {
2226 return [self description];
2229 - (NSString *)debugDescription {
2230 return [self description];
2235 return [callAlloc(self, false/*checkNil*/) init];
2242 // Replaced by ObjectAlloc
2244 return ((id)self)->rootRetain();
2248 + (BOOL)_tryRetain {
2252 // Replaced by ObjectAlloc
2253 - (BOOL)_tryRetain {
2254 return ((id)self)->rootTryRetain();
2257 + (BOOL)_isDeallocating {
2261 - (BOOL)_isDeallocating {
2262 return ((id)self)->rootIsDeallocating();
2265 + (BOOL)allowsWeakReference {
2269 + (BOOL)retainWeakReference {
2273 - (BOOL)allowsWeakReference {
2274 return ! [self _isDeallocating];
2277 - (BOOL)retainWeakReference {
2278 return [self _tryRetain];
2281 + (oneway void)release {
2284 // Replaced by ObjectAlloc
2285 - (oneway void)release {
2286 ((id)self)->rootRelease();
2293 // Replaced by ObjectAlloc
2295 return ((id)self)->rootAutorelease();
2298 + (NSUInteger)retainCount {
2302 - (NSUInteger)retainCount {
2303 return ((id)self)->rootRetainCount();
2307 return _objc_rootAlloc(self);
2310 // Replaced by ObjectAlloc
2311 + (id)allocWithZone:(struct _NSZone *)zone {
2312 return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
2315 // Replaced by CF (throws an NSException)
2321 return _objc_rootInit(self);
2324 // Replaced by CF (throws an NSException)
2329 // Replaced by NSZombies
2331 _objc_rootDealloc(self);
2334 // Previously used by GC. Now a placeholder for binary compatibility.
2338 + (struct _NSZone *)zone {
2339 return (struct _NSZone *)_objc_rootZone(self);
2342 - (struct _NSZone *)zone {
2343 return (struct _NSZone *)_objc_rootZone(self);
2350 + (id)copyWithZone:(struct _NSZone *)zone {
2355 return [(id)self copyWithZone:nil];
2362 + (id)mutableCopyWithZone:(struct _NSZone *)zone {
2367 return [(id)self mutableCopyWithZone:nil];