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;
139 // Template parameters.
140 enum HaveOld { DontHaveOld = false, DoHaveOld = true };
141 enum HaveNew { DontHaveNew = false, DoHaveNew = true };
146 weak_table_t weak_table;
149 memset(&weak_table, 0, sizeof(weak_table));
153 _objc_fatal("Do not delete SideTable.");
156 void lock() { slock.lock(); }
157 void unlock() { slock.unlock(); }
158 void forceReset() { slock.forceReset(); }
160 // Address-ordered lock discipline for a pair of side tables.
162 template<HaveOld, HaveNew>
163 static void lockTwo(SideTable *lock1, SideTable *lock2);
164 template<HaveOld, HaveNew>
165 static void unlockTwo(SideTable *lock1, SideTable *lock2);
170 void SideTable::lockTwo<DoHaveOld, DoHaveNew>
171 (SideTable *lock1, SideTable *lock2)
173 spinlock_t::lockTwo(&lock1->slock, &lock2->slock);
177 void SideTable::lockTwo<DoHaveOld, DontHaveNew>
178 (SideTable *lock1, SideTable *)
184 void SideTable::lockTwo<DontHaveOld, DoHaveNew>
185 (SideTable *, SideTable *lock2)
191 void SideTable::unlockTwo<DoHaveOld, DoHaveNew>
192 (SideTable *lock1, SideTable *lock2)
194 spinlock_t::unlockTwo(&lock1->slock, &lock2->slock);
198 void SideTable::unlockTwo<DoHaveOld, DontHaveNew>
199 (SideTable *lock1, SideTable *)
205 void SideTable::unlockTwo<DontHaveOld, DoHaveNew>
206 (SideTable *, SideTable *lock2)
212 // We cannot use a C++ static initializer to initialize SideTables because
213 // libc calls us before our C++ initializers run. We also don't want a global
214 // pointer to this struct because of the extra indirection.
215 // Do it the hard way.
216 alignas(StripedMap<SideTable>) static uint8_t
217 SideTableBuf[sizeof(StripedMap<SideTable>)];
219 static void SideTableInit() {
220 new (SideTableBuf) StripedMap<SideTable>();
223 static StripedMap<SideTable>& SideTables() {
224 return *reinterpret_cast<StripedMap<SideTable>*>(SideTableBuf);
227 // anonymous namespace
230 void SideTableLockAll() {
231 SideTables().lockAll();
234 void SideTableUnlockAll() {
235 SideTables().unlockAll();
238 void SideTableForceResetAll() {
239 SideTables().forceResetAll();
242 void SideTableDefineLockOrder() {
243 SideTables().defineLockOrder();
246 void SideTableLocksPrecedeLock(const void *newlock) {
247 SideTables().precedeLock(newlock);
250 void SideTableLocksSucceedLock(const void *oldlock) {
251 SideTables().succeedLock(oldlock);
255 // The -fobjc-arc flag causes the compiler to issue calls to objc_{retain/release/autorelease/retain_block}
258 id objc_retainBlock(id x) {
259 return (id)_Block_copy(x);
263 // The following SHOULD be called by the compiler directly, but the request hasn't been made yet :-)
266 BOOL objc_should_deallocate(id object) {
271 objc_retain_autorelease(id obj)
273 return objc_autorelease(objc_retain(obj));
278 objc_storeStrong(id *location, id obj)
290 // Update a weak variable.
291 // If HaveOld is true, the variable has an existing value
292 // that needs to be cleaned up. This value might be nil.
293 // If HaveNew is true, there is a new value that needs to be
294 // assigned into the variable. This value might be nil.
295 // If CrashIfDeallocating is true, the process is halted if newObj is
296 // deallocating or newObj's class does not support weak references.
297 // If CrashIfDeallocating is false, nil is stored instead.
298 enum CrashIfDeallocating {
299 DontCrashIfDeallocating = false, DoCrashIfDeallocating = true
301 template <HaveOld haveOld, HaveNew haveNew,
302 CrashIfDeallocating crashIfDeallocating>
304 storeWeak(id *location, objc_object *newObj)
306 assert(haveOld || haveNew);
307 if (!haveNew) assert(newObj == nil);
309 Class previouslyInitializedClass = nil;
314 // Acquire locks for old and new values.
315 // Order by lock address to prevent lock ordering problems.
316 // Retry if the old value changes underneath us.
320 oldTable = &SideTables()[oldObj];
325 newTable = &SideTables()[newObj];
330 SideTable::lockTwo<haveOld, haveNew>(oldTable, newTable);
332 if (haveOld && *location != oldObj) {
333 SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
337 // Prevent a deadlock between the weak reference machinery
338 // and the +initialize machinery by ensuring that no
339 // weakly-referenced object has an un-+initialized isa.
340 if (haveNew && newObj) {
341 Class cls = newObj->getIsa();
342 if (cls != previouslyInitializedClass &&
343 !((objc_class *)cls)->isInitialized())
345 SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
346 _class_initialize(_class_getNonMetaClass(cls, (id)newObj));
348 // If this class is finished with +initialize then we're good.
349 // If this class is still running +initialize on this thread
350 // (i.e. +initialize called storeWeak on an instance of itself)
351 // then we may proceed but it will appear initializing and
352 // not yet initialized to the check above.
353 // Instead set previouslyInitializedClass to recognize it on retry.
354 previouslyInitializedClass = cls;
360 // Clean up old value, if any.
362 weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
365 // Assign new value, if any.
367 newObj = (objc_object *)
368 weak_register_no_lock(&newTable->weak_table, (id)newObj, location,
369 crashIfDeallocating);
370 // weak_register_no_lock returns nil if weak store should be rejected
372 // Set is-weakly-referenced bit in refcount table.
373 if (newObj && !newObj->isTaggedPointer()) {
374 newObj->setWeaklyReferenced_nolock();
377 // Do not set *location anywhere else. That would introduce a race.
378 *location = (id)newObj;
381 // No new value. The storage is not changed.
384 SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
391 * This function stores a new value into a __weak variable. It would
392 * be used anywhere a __weak variable is the target of an assignment.
394 * @param location The address of the weak pointer itself
395 * @param newObj The new object this weak ptr should now point to
400 objc_storeWeak(id *location, id newObj)
402 return storeWeak<DoHaveOld, DoHaveNew, DoCrashIfDeallocating>
403 (location, (objc_object *)newObj);
408 * This function stores a new value into a __weak variable.
409 * If the new object is deallocating or the new object's class
410 * does not support weak references, stores nil instead.
412 * @param location The address of the weak pointer itself
413 * @param newObj The new object this weak ptr should now point to
415 * @return The value stored (either the new object or nil)
418 objc_storeWeakOrNil(id *location, id newObj)
420 return storeWeak<DoHaveOld, DoHaveNew, DontCrashIfDeallocating>
421 (location, (objc_object *)newObj);
426 * Initialize a fresh weak pointer to some object location.
427 * It would be used for code like:
433 * __weak id weakPtr = o;
435 * This function IS NOT thread-safe with respect to concurrent
436 * modifications to the weak variable. (Concurrent weak clear is safe.)
438 * @param location Address of __weak ptr.
439 * @param newObj Object ptr.
442 objc_initWeak(id *location, id newObj)
449 return storeWeak<DontHaveOld, DoHaveNew, DoCrashIfDeallocating>
450 (location, (objc_object*)newObj);
454 objc_initWeakOrNil(id *location, id newObj)
461 return storeWeak<DontHaveOld, DoHaveNew, DontCrashIfDeallocating>
462 (location, (objc_object*)newObj);
467 * Destroys the relationship between a weak pointer
468 * and the object it is referencing in the internal weak
469 * table. If the weak pointer is not referencing anything,
470 * there is no need to edit the weak table.
472 * This function IS NOT thread-safe with respect to concurrent
473 * modifications to the weak variable. (Concurrent weak clear is safe.)
475 * @param location The weak pointer address.
478 objc_destroyWeak(id *location)
480 (void)storeWeak<DoHaveOld, DontHaveNew, DontCrashIfDeallocating>
486 Once upon a time we eagerly cleared *location if we saw the object
487 was deallocating. This confuses code like NSPointerFunctions which
488 tries to pre-flight the raw storage and assumes if the storage is
489 zero then the weak system is done interfering. That is false: the
490 weak system is still going to check and clear the storage later.
491 This can cause objc_weak_error complaints and crashes.
492 So we now don't touch the storage until deallocation completes.
496 objc_loadWeakRetained(id *location)
505 // fixme std::atomic this load
507 if (!obj) return nil;
508 if (obj->isTaggedPointer()) return obj;
510 table = &SideTables()[obj];
513 if (*location != obj) {
521 if (! cls->hasCustomRR()) {
522 // Fast case. We know +initialize is complete because
523 // default-RR can never be set before then.
524 assert(cls->isInitialized());
525 if (! obj->rootTryRetain()) {
530 // Slow case. We must check for +initialize and call it outside
531 // the lock if necessary in order to avoid deadlocks.
532 if (cls->isInitialized() || _thisThreadIsInitializingClass(cls)) {
533 BOOL (*tryRetain)(id, SEL) = (BOOL(*)(id, SEL))
534 class_getMethodImplementation(cls, SEL_retainWeakReference);
535 if ((IMP)tryRetain == _objc_msgForward) {
538 else if (! (*tryRetain)(obj, SEL_retainWeakReference)) {
544 _class_initialize(cls);
554 * This loads the object referenced by a weak pointer and returns it, after
555 * retaining and autoreleasing the object to ensure that it stays alive
556 * long enough for the caller to use it. This function would be used
557 * anywhere a __weak variable is used in an expression.
559 * @param location The weak pointer address
561 * @return The object pointed to by \e location, or \c nil if \e location is \c nil.
564 objc_loadWeak(id *location)
566 if (!*location) return nil;
567 return objc_autorelease(objc_loadWeakRetained(location));
572 * This function copies a weak pointer from one location to another,
573 * when the destination doesn't already contain a weak pointer. It
574 * would be used for code like:
576 * __weak id src = ...;
577 * __weak id dst = src;
579 * This function IS NOT thread-safe with respect to concurrent
580 * modifications to the destination variable. (Concurrent weak clear is safe.)
582 * @param dst The destination variable.
583 * @param src The source variable.
586 objc_copyWeak(id *dst, id *src)
588 id obj = objc_loadWeakRetained(src);
589 objc_initWeak(dst, obj);
594 * Move a weak pointer from one location to another.
595 * Before the move, the destination must be uninitialized.
596 * After the move, the source is nil.
598 * This function IS NOT thread-safe with respect to concurrent
599 * modifications to either weak variable. (Concurrent weak clear is safe.)
603 objc_moveWeak(id *dst, id *src)
605 objc_copyWeak(dst, src);
606 objc_destroyWeak(src);
611 /***********************************************************************
612 Autorelease pool implementation
614 A thread's autorelease pool is a stack of pointers.
615 Each pointer is either an object to release, or POOL_BOUNDARY which is
616 an autorelease pool boundary.
617 A pool token is a pointer to the POOL_BOUNDARY for that pool. When
618 the pool is popped, every object hotter than the sentinel is released.
619 The stack is divided into a doubly-linked list of pages. Pages are added
620 and deleted as necessary.
621 Thread-local storage points to the hot page, where newly autoreleased
623 **********************************************************************/
625 // Set this to 1 to mprotect() autorelease pool contents
626 #define PROTECT_AUTORELEASEPOOL 0
628 // Set this to 1 to validate the entire autorelease pool header all the time
629 // (i.e. use check() instead of fastcheck() everywhere)
630 #define CHECK_AUTORELEASEPOOL (DEBUG)
632 BREAKPOINT_FUNCTION(void objc_autoreleaseNoPool(id obj));
633 BREAKPOINT_FUNCTION(void objc_autoreleasePoolInvalid(const void *token));
638 static const uint32_t M0 = 0xA1A1A1A1;
639 # define M1 "AUTORELEASE!"
640 static const size_t M1_len = 12;
644 assert(M1_len == strlen(M1));
645 assert(M1_len == 3 * sizeof(m[1]));
648 strncpy((char *)&m[1], M1, M1_len);
652 m[0] = m[1] = m[2] = m[3] = 0;
656 return (m[0] == M0 && 0 == strncmp((char *)&m[1], M1, M1_len));
659 bool fastcheck() const {
660 #if CHECK_AUTORELEASEPOOL
671 class AutoreleasePoolPage
673 // EMPTY_POOL_PLACEHOLDER is stored in TLS when exactly one pool is
674 // pushed and it has never contained any objects. This saves memory
675 // when the top level (i.e. libdispatch) pushes and pops pools but
677 # define EMPTY_POOL_PLACEHOLDER ((id*)1)
679 # define POOL_BOUNDARY nil
680 static pthread_key_t const key = AUTORELEASE_POOL_KEY;
681 static uint8_t const SCRIBBLE = 0xA3; // 0xA3A3A3A3 after releasing
682 static size_t const SIZE =
683 #if PROTECT_AUTORELEASEPOOL
684 PAGE_MAX_SIZE; // must be multiple of vm page size
686 PAGE_MAX_SIZE; // size and alignment, power of 2
688 static size_t const COUNT = SIZE / sizeof(id);
692 pthread_t const thread;
693 AutoreleasePoolPage * const parent;
694 AutoreleasePoolPage *child;
695 uint32_t const depth;
698 // SIZE-sizeof(*this) bytes of contents follow
700 static void * operator new(size_t size) {
701 return malloc_zone_memalign(malloc_default_zone(), SIZE, SIZE);
703 static void operator delete(void * p) {
707 inline void protect() {
708 #if PROTECT_AUTORELEASEPOOL
709 mprotect(this, SIZE, PROT_READ);
714 inline void unprotect() {
715 #if PROTECT_AUTORELEASEPOOL
717 mprotect(this, SIZE, PROT_READ | PROT_WRITE);
721 AutoreleasePoolPage(AutoreleasePoolPage *newParent)
722 : magic(), next(begin()), thread(pthread_self()),
723 parent(newParent), child(nil),
724 depth(parent ? 1+parent->depth : 0),
725 hiwat(parent ? parent->hiwat : 0)
729 assert(!parent->child);
731 parent->child = this;
737 ~AutoreleasePoolPage()
743 // Not recursive: we don't want to blow out the stack
744 // if a thread accumulates a stupendous amount of garbage
749 void busted(bool die = true)
752 (die ? _objc_fatal : _objc_inform)
753 ("autorelease pool page %p corrupted\n"
754 " magic 0x%08x 0x%08x 0x%08x 0x%08x\n"
755 " should be 0x%08x 0x%08x 0x%08x 0x%08x\n"
759 magic.m[0], magic.m[1], magic.m[2], magic.m[3],
760 right.m[0], right.m[1], right.m[2], right.m[3],
761 this->thread, pthread_self());
764 void check(bool die = true)
766 if (!magic.check() || !pthread_equal(thread, pthread_self())) {
771 void fastcheck(bool die = true)
773 #if CHECK_AUTORELEASEPOOL
776 if (! magic.fastcheck()) {
784 return (id *) ((uint8_t *)this+sizeof(*this));
788 return (id *) ((uint8_t *)this+SIZE);
792 return next == begin();
796 return next == end();
799 bool lessThanHalfFull() {
800 return (next - begin() < (end() - begin()) / 2);
807 id *ret = next; // faster than `return next-1` because of aliasing
815 releaseUntil(begin());
818 void releaseUntil(id *stop)
820 // Not recursive: we don't want to blow out the stack
821 // if a thread accumulates a stupendous amount of garbage
823 while (this->next != stop) {
824 // Restart from hotPage() every time, in case -release
825 // autoreleased more objects
826 AutoreleasePoolPage *page = hotPage();
828 // fixme I think this `while` can be `if`, but I can't prove it
829 while (page->empty()) {
835 id obj = *--page->next;
836 memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
839 if (obj != POOL_BOUNDARY) {
847 // we expect any children to be completely empty
848 for (AutoreleasePoolPage *page = child; page; page = page->child) {
849 assert(page->empty());
856 // Not recursive: we don't want to blow out the stack
857 // if a thread accumulates a stupendous amount of garbage
858 AutoreleasePoolPage *page = this;
859 while (page->child) page = page->child;
861 AutoreleasePoolPage *deathptr;
871 } while (deathptr != this);
874 static void tls_dealloc(void *p)
876 if (p == (void*)EMPTY_POOL_PLACEHOLDER) {
877 // No objects or pool pages to clean up here.
881 // reinstate TLS value while we work
882 setHotPage((AutoreleasePoolPage *)p);
884 if (AutoreleasePoolPage *page = coldPage()) {
885 if (!page->empty()) pop(page->begin()); // pop all of the pools
886 if (DebugMissingPools || DebugPoolAllocation) {
887 // pop() killed the pages already
889 page->kill(); // free all of the pages
893 // clear TLS value so TLS destruction doesn't loop
897 static AutoreleasePoolPage *pageForPointer(const void *p)
899 return pageForPointer((uintptr_t)p);
902 static AutoreleasePoolPage *pageForPointer(uintptr_t p)
904 AutoreleasePoolPage *result;
905 uintptr_t offset = p % SIZE;
907 assert(offset >= sizeof(AutoreleasePoolPage));
909 result = (AutoreleasePoolPage *)(p - offset);
916 static inline bool haveEmptyPoolPlaceholder()
918 id *tls = (id *)tls_get_direct(key);
919 return (tls == EMPTY_POOL_PLACEHOLDER);
922 static inline id* setEmptyPoolPlaceholder()
924 assert(tls_get_direct(key) == nil);
925 tls_set_direct(key, (void *)EMPTY_POOL_PLACEHOLDER);
926 return EMPTY_POOL_PLACEHOLDER;
929 static inline AutoreleasePoolPage *hotPage()
931 AutoreleasePoolPage *result = (AutoreleasePoolPage *)
933 if ((id *)result == EMPTY_POOL_PLACEHOLDER) return nil;
934 if (result) result->fastcheck();
938 static inline void setHotPage(AutoreleasePoolPage *page)
940 if (page) page->fastcheck();
941 tls_set_direct(key, (void *)page);
944 static inline AutoreleasePoolPage *coldPage()
946 AutoreleasePoolPage *result = hotPage();
948 while (result->parent) {
949 result = result->parent;
957 static inline id *autoreleaseFast(id obj)
959 AutoreleasePoolPage *page = hotPage();
960 if (page && !page->full()) {
961 return page->add(obj);
963 return autoreleaseFullPage(obj, page);
965 return autoreleaseNoPage(obj);
969 static __attribute__((noinline))
970 id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page)
972 // The hot page is full.
973 // Step to the next non-full page, adding a new page if necessary.
974 // Then add the object to that page.
975 assert(page == hotPage());
976 assert(page->full() || DebugPoolAllocation);
979 if (page->child) page = page->child;
980 else page = new AutoreleasePoolPage(page);
981 } while (page->full());
984 return page->add(obj);
987 static __attribute__((noinline))
988 id *autoreleaseNoPage(id obj)
990 // "No page" could mean no pool has been pushed
991 // or an empty placeholder pool has been pushed and has no contents yet
994 bool pushExtraBoundary = false;
995 if (haveEmptyPoolPlaceholder()) {
996 // We are pushing a second pool over the empty placeholder pool
997 // or pushing the first object into the empty placeholder pool.
998 // Before doing that, push a pool boundary on behalf of the pool
999 // that is currently represented by the empty placeholder.
1000 pushExtraBoundary = true;
1002 else if (obj != POOL_BOUNDARY && DebugMissingPools) {
1003 // We are pushing an object with no pool in place,
1004 // and no-pool debugging was requested by environment.
1005 _objc_inform("MISSING POOLS: (%p) Object %p of class %s "
1006 "autoreleased with no pool in place - "
1007 "just leaking - break on "
1008 "objc_autoreleaseNoPool() to debug",
1009 pthread_self(), (void*)obj, object_getClassName(obj));
1010 objc_autoreleaseNoPool(obj);
1013 else if (obj == POOL_BOUNDARY && !DebugPoolAllocation) {
1014 // We are pushing a pool with no pool in place,
1015 // and alloc-per-pool debugging was not requested.
1016 // Install and return the empty pool placeholder.
1017 return setEmptyPoolPlaceholder();
1020 // We are pushing an object or a non-placeholder'd pool.
1022 // Install the first page.
1023 AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
1026 // Push a boundary on behalf of the previously-placeholder'd pool.
1027 if (pushExtraBoundary) {
1028 page->add(POOL_BOUNDARY);
1031 // Push the requested object or pool.
1032 return page->add(obj);
1036 static __attribute__((noinline))
1037 id *autoreleaseNewPage(id obj)
1039 AutoreleasePoolPage *page = hotPage();
1040 if (page) return autoreleaseFullPage(obj, page);
1041 else return autoreleaseNoPage(obj);
1045 static inline id autorelease(id obj)
1048 assert(!obj->isTaggedPointer());
1049 id *dest __unused = autoreleaseFast(obj);
1050 assert(!dest || dest == EMPTY_POOL_PLACEHOLDER || *dest == obj);
1055 static inline void *push()
1058 if (DebugPoolAllocation) {
1059 // Each autorelease pool starts on a new pool page.
1060 dest = autoreleaseNewPage(POOL_BOUNDARY);
1062 dest = autoreleaseFast(POOL_BOUNDARY);
1064 assert(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
1068 static void badPop(void *token)
1070 // Error. For bincompat purposes this is not
1071 // fatal in executables built with old SDKs.
1073 if (DebugPoolAllocation || sdkIsAtLeast(10_12, 10_0, 10_0, 3_0)) {
1074 // OBJC_DEBUG_POOL_ALLOCATION or new SDK. Bad pop is fatal.
1076 ("Invalid or prematurely-freed autorelease pool %p.", token);
1079 // Old SDK. Bad pop is warned once.
1080 static bool complained = false;
1083 _objc_inform_now_and_on_crash
1084 ("Invalid or prematurely-freed autorelease pool %p. "
1085 "Set a breakpoint on objc_autoreleasePoolInvalid to debug. "
1086 "Proceeding anyway because the app is old "
1087 "(SDK version " SDK_FORMAT "). Memory errors are likely.",
1088 token, FORMAT_SDK(sdkVersion()));
1090 objc_autoreleasePoolInvalid(token);
1093 static inline void pop(void *token)
1095 AutoreleasePoolPage *page;
1098 if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
1099 // Popping the top-level placeholder pool.
1101 // Pool was used. Pop its contents normally.
1102 // Pool pages remain allocated for re-use as usual.
1103 pop(coldPage()->begin());
1105 // Pool was never used. Clear the placeholder.
1111 page = pageForPointer(token);
1113 if (*stop != POOL_BOUNDARY) {
1114 if (stop == page->begin() && !page->parent) {
1115 // Start of coldest page may correctly not be POOL_BOUNDARY:
1116 // 1. top-level pool is popped, leaving the cold page in place
1117 // 2. an object is autoreleased with no pool
1119 // Error. For bincompat purposes this is not
1120 // fatal in executables built with old SDKs.
1121 return badPop(token);
1125 if (PrintPoolHiwat) printHiwat();
1127 page->releaseUntil(stop);
1129 // memory: delete empty children
1130 if (DebugPoolAllocation && page->empty()) {
1131 // special case: delete everything during page-per-pool debugging
1132 AutoreleasePoolPage *parent = page->parent;
1135 } else if (DebugMissingPools && page->empty() && !page->parent) {
1136 // special case: delete everything for pop(top)
1137 // when debugging missing autorelease pools
1141 else if (page->child) {
1142 // hysteresis: keep one empty child if page is more than half full
1143 if (page->lessThanHalfFull()) {
1144 page->child->kill();
1146 else if (page->child->child) {
1147 page->child->child->kill();
1154 int r __unused = pthread_key_init_np(AutoreleasePoolPage::key,
1155 AutoreleasePoolPage::tls_dealloc);
1161 _objc_inform("[%p] ................ PAGE %s %s %s", this,
1162 full() ? "(full)" : "",
1163 this == hotPage() ? "(hot)" : "",
1164 this == coldPage() ? "(cold)" : "");
1166 for (id *p = begin(); p < next; p++) {
1167 if (*p == POOL_BOUNDARY) {
1168 _objc_inform("[%p] ################ POOL %p", p, p);
1170 _objc_inform("[%p] %#16lx %s",
1171 p, (unsigned long)*p, object_getClassName(*p));
1176 static void printAll()
1178 _objc_inform("##############");
1179 _objc_inform("AUTORELEASE POOLS for thread %p", pthread_self());
1181 AutoreleasePoolPage *page;
1182 ptrdiff_t objects = 0;
1183 for (page = coldPage(); page; page = page->child) {
1184 objects += page->next - page->begin();
1186 _objc_inform("%llu releases pending.", (unsigned long long)objects);
1188 if (haveEmptyPoolPlaceholder()) {
1189 _objc_inform("[%p] ................ PAGE (placeholder)",
1190 EMPTY_POOL_PLACEHOLDER);
1191 _objc_inform("[%p] ################ POOL (placeholder)",
1192 EMPTY_POOL_PLACEHOLDER);
1195 for (page = coldPage(); page; page = page->child) {
1200 _objc_inform("##############");
1203 static void printHiwat()
1205 // Check and propagate high water mark
1206 // Ignore high water marks under 256 to suppress noise.
1207 AutoreleasePoolPage *p = hotPage();
1208 uint32_t mark = p->depth*COUNT + (uint32_t)(p->next - p->begin());
1209 if (mark > p->hiwat && mark > 256) {
1210 for( ; p; p = p->parent) {
1216 _objc_inform("POOL HIGHWATER: new high water mark of %u "
1217 "pending releases for thread %p:",
1218 mark, pthread_self());
1221 int count = backtrace(stack, sizeof(stack)/sizeof(stack[0]));
1222 char **sym = backtrace_symbols(stack, count);
1223 for (int i = 0; i < count; i++) {
1224 _objc_inform("POOL HIGHWATER: %s", sym[i]);
1230 #undef POOL_BOUNDARY
1233 // anonymous namespace
1237 /***********************************************************************
1238 * Slow paths for inline control
1239 **********************************************************************/
1241 #if SUPPORT_NONPOINTER_ISA
1244 objc_object::rootRetain_overflow(bool tryRetain)
1246 return rootRetain(tryRetain, true);
1251 objc_object::rootRelease_underflow(bool performDealloc)
1253 return rootRelease(performDealloc, true);
1257 // Slow path of clearDeallocating()
1258 // for objects with nonpointer isa
1259 // that were ever weakly referenced
1260 // or whose retain count ever overflowed to the side table.
1262 objc_object::clearDeallocating_slow()
1264 assert(isa.nonpointer && (isa.weakly_referenced || isa.has_sidetable_rc));
1266 SideTable& table = SideTables()[this];
1268 if (isa.weakly_referenced) {
1269 weak_clear_no_lock(&table.weak_table, (id)this);
1271 if (isa.has_sidetable_rc) {
1272 table.refcnts.erase(this);
1279 __attribute__((noinline,used))
1281 objc_object::rootAutorelease2()
1283 assert(!isTaggedPointer());
1284 return AutoreleasePoolPage::autorelease((id)this);
1288 BREAKPOINT_FUNCTION(
1289 void objc_overrelease_during_dealloc_error(void)
1295 objc_object::overrelease_error()
1297 _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);
1298 objc_overrelease_during_dealloc_error();
1299 return false; // allow rootRelease() to tail-call this
1303 /***********************************************************************
1304 * Retain count operations for side table.
1305 **********************************************************************/
1309 // Used to assert that an object is not present in the side table.
1311 objc_object::sidetable_present()
1313 bool result = false;
1314 SideTable& table = SideTables()[this];
1318 RefcountMap::iterator it = table.refcnts.find(this);
1319 if (it != table.refcnts.end()) result = true;
1321 if (weak_is_registered_no_lock(&table.weak_table, (id)this)) result = true;
1329 #if SUPPORT_NONPOINTER_ISA
1332 objc_object::sidetable_lock()
1334 SideTable& table = SideTables()[this];
1339 objc_object::sidetable_unlock()
1341 SideTable& table = SideTables()[this];
1346 // Move the entire retain count to the side table,
1347 // as well as isDeallocating and weaklyReferenced.
1349 objc_object::sidetable_moveExtraRC_nolock(size_t extra_rc,
1350 bool isDeallocating,
1351 bool weaklyReferenced)
1353 assert(!isa.nonpointer); // should already be changed to raw pointer
1354 SideTable& table = SideTables()[this];
1356 size_t& refcntStorage = table.refcnts[this];
1357 size_t oldRefcnt = refcntStorage;
1358 // not deallocating - that was in the isa
1359 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1360 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1363 size_t refcnt = addc(oldRefcnt, extra_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
1364 if (carry) refcnt = SIDE_TABLE_RC_PINNED;
1365 if (isDeallocating) refcnt |= SIDE_TABLE_DEALLOCATING;
1366 if (weaklyReferenced) refcnt |= SIDE_TABLE_WEAKLY_REFERENCED;
1368 refcntStorage = refcnt;
1372 // Move some retain counts to the side table from the isa field.
1373 // Returns true if the object is now pinned.
1375 objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)
1377 assert(isa.nonpointer);
1378 SideTable& table = SideTables()[this];
1380 size_t& refcntStorage = table.refcnts[this];
1381 size_t oldRefcnt = refcntStorage;
1382 // isa-side bits should not be set here
1383 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1384 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1386 if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;
1390 addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
1393 SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK);
1397 refcntStorage = newRefcnt;
1403 // Move some retain counts from the side table to the isa field.
1404 // Returns the actual count subtracted, which may be less than the request.
1406 objc_object::sidetable_subExtraRC_nolock(size_t delta_rc)
1408 assert(isa.nonpointer);
1409 SideTable& table = SideTables()[this];
1411 RefcountMap::iterator it = table.refcnts.find(this);
1412 if (it == table.refcnts.end() || it->second == 0) {
1413 // Side table retain count is zero. Can't borrow.
1416 size_t oldRefcnt = it->second;
1418 // isa-side bits should not be set here
1419 assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
1420 assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
1422 size_t newRefcnt = oldRefcnt - (delta_rc << SIDE_TABLE_RC_SHIFT);
1423 assert(oldRefcnt > newRefcnt); // shouldn't underflow
1424 it->second = newRefcnt;
1430 objc_object::sidetable_getExtraRC_nolock()
1432 assert(isa.nonpointer);
1433 SideTable& table = SideTables()[this];
1434 RefcountMap::iterator it = table.refcnts.find(this);
1435 if (it == table.refcnts.end()) return 0;
1436 else return it->second >> SIDE_TABLE_RC_SHIFT;
1440 // SUPPORT_NONPOINTER_ISA
1445 objc_object::sidetable_retain()
1447 #if SUPPORT_NONPOINTER_ISA
1448 assert(!isa.nonpointer);
1450 SideTable& table = SideTables()[this];
1453 size_t& refcntStorage = table.refcnts[this];
1454 if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) {
1455 refcntStorage += SIDE_TABLE_RC_ONE;
1464 objc_object::sidetable_tryRetain()
1466 #if SUPPORT_NONPOINTER_ISA
1467 assert(!isa.nonpointer);
1469 SideTable& table = SideTables()[this];
1472 // _objc_rootTryRetain() is called exclusively by _objc_loadWeak(),
1473 // which already acquired the lock on our behalf.
1475 // fixme can't do this efficiently with os_lock_handoff_s
1476 // if (table.slock == 0) {
1477 // _objc_fatal("Do not call -_tryRetain.");
1481 RefcountMap::iterator it = table.refcnts.find(this);
1482 if (it == table.refcnts.end()) {
1483 table.refcnts[this] = SIDE_TABLE_RC_ONE;
1484 } else if (it->second & SIDE_TABLE_DEALLOCATING) {
1486 } else if (! (it->second & SIDE_TABLE_RC_PINNED)) {
1487 it->second += SIDE_TABLE_RC_ONE;
1495 objc_object::sidetable_retainCount()
1497 SideTable& table = SideTables()[this];
1499 size_t refcnt_result = 1;
1502 RefcountMap::iterator it = table.refcnts.find(this);
1503 if (it != table.refcnts.end()) {
1504 // this is valid for SIDE_TABLE_RC_PINNED too
1505 refcnt_result += it->second >> SIDE_TABLE_RC_SHIFT;
1508 return refcnt_result;
1513 objc_object::sidetable_isDeallocating()
1515 SideTable& table = SideTables()[this];
1518 // _objc_rootIsDeallocating() is called exclusively by _objc_storeWeak(),
1519 // which already acquired the lock on our behalf.
1522 // fixme can't do this efficiently with os_lock_handoff_s
1523 // if (table.slock == 0) {
1524 // _objc_fatal("Do not call -_isDeallocating.");
1527 RefcountMap::iterator it = table.refcnts.find(this);
1528 return (it != table.refcnts.end()) && (it->second & SIDE_TABLE_DEALLOCATING);
1533 objc_object::sidetable_isWeaklyReferenced()
1535 bool result = false;
1537 SideTable& table = SideTables()[this];
1540 RefcountMap::iterator it = table.refcnts.find(this);
1541 if (it != table.refcnts.end()) {
1542 result = it->second & SIDE_TABLE_WEAKLY_REFERENCED;
1552 objc_object::sidetable_setWeaklyReferenced_nolock()
1554 #if SUPPORT_NONPOINTER_ISA
1555 assert(!isa.nonpointer);
1558 SideTable& table = SideTables()[this];
1560 table.refcnts[this] |= SIDE_TABLE_WEAKLY_REFERENCED;
1565 // return uintptr_t instead of bool so that the various raw-isa
1566 // -release paths all return zero in eax
1568 objc_object::sidetable_release(bool performDealloc)
1570 #if SUPPORT_NONPOINTER_ISA
1571 assert(!isa.nonpointer);
1573 SideTable& table = SideTables()[this];
1575 bool do_dealloc = false;
1578 RefcountMap::iterator it = table.refcnts.find(this);
1579 if (it == table.refcnts.end()) {
1581 table.refcnts[this] = SIDE_TABLE_DEALLOCATING;
1582 } else if (it->second < SIDE_TABLE_DEALLOCATING) {
1583 // SIDE_TABLE_WEAKLY_REFERENCED may be set. Don't change it.
1585 it->second |= SIDE_TABLE_DEALLOCATING;
1586 } else if (! (it->second & SIDE_TABLE_RC_PINNED)) {
1587 it->second -= SIDE_TABLE_RC_ONE;
1590 if (do_dealloc && performDealloc) {
1591 ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
1598 objc_object::sidetable_clearDeallocating()
1600 SideTable& table = SideTables()[this];
1602 // clear any weak table items
1603 // clear extra retain count and deallocating bit
1604 // (fixme warn or abort if extra retain count == 0 ?)
1606 RefcountMap::iterator it = table.refcnts.find(this);
1607 if (it != table.refcnts.end()) {
1608 if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
1609 weak_clear_no_lock(&table.weak_table, (id)this);
1611 table.refcnts.erase(it);
1617 /***********************************************************************
1618 * Optimized retain/release/autorelease entrypoints
1619 **********************************************************************/
1624 __attribute__((aligned(16)))
1628 if (!obj) return obj;
1629 if (obj->isTaggedPointer()) return obj;
1630 return obj->retain();
1634 __attribute__((aligned(16)))
1636 objc_release(id obj)
1639 if (obj->isTaggedPointer()) return;
1640 return obj->release();
1644 __attribute__((aligned(16)))
1646 objc_autorelease(id obj)
1648 if (!obj) return obj;
1649 if (obj->isTaggedPointer()) return obj;
1650 return obj->autorelease();
1659 id objc_retain(id obj) { return [obj retain]; }
1660 void objc_release(id obj) { [obj release]; }
1661 id objc_autorelease(id obj) { return [obj autorelease]; }
1667 /***********************************************************************
1668 * Basic operations for root class implementations a.k.a. _objc_root*()
1669 **********************************************************************/
1672 _objc_rootTryRetain(id obj)
1676 return obj->rootTryRetain();
1680 _objc_rootIsDeallocating(id obj)
1684 return obj->rootIsDeallocating();
1689 objc_clear_deallocating(id obj)
1693 if (obj->isTaggedPointer()) return;
1694 obj->clearDeallocating();
1699 _objc_rootReleaseWasZero(id obj)
1703 return obj->rootReleaseShouldDealloc();
1708 _objc_rootAutorelease(id obj)
1711 return obj->rootAutorelease();
1715 _objc_rootRetainCount(id obj)
1719 return obj->rootRetainCount();
1724 _objc_rootRetain(id obj)
1728 return obj->rootRetain();
1732 _objc_rootRelease(id obj)
1741 _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
1746 // allocWithZone under __OBJC2__ ignores the zone parameter
1748 obj = class_createInstance(cls, 0);
1751 obj = class_createInstance(cls, 0);
1754 obj = class_createInstanceFromZone(cls, 0, zone);
1758 if (slowpath(!obj)) obj = callBadAllocHandler(cls);
1763 // Call [cls alloc] or [cls allocWithZone:nil], with appropriate
1764 // shortcutting optimizations.
1765 static ALWAYS_INLINE id
1766 callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
1768 if (slowpath(checkNil && !cls)) return nil;
1771 if (fastpath(!cls->ISA()->hasCustomAWZ())) {
1772 // No alloc/allocWithZone implementation. Go straight to the allocator.
1773 // fixme store hasCustomAWZ in the non-meta class and
1774 // add it to canAllocFast's summary
1775 if (fastpath(cls->canAllocFast())) {
1776 // No ctors, raw isa, etc. Go straight to the metal.
1777 bool dtor = cls->hasCxxDtor();
1778 id obj = (id)calloc(1, cls->bits.fastInstanceSize());
1779 if (slowpath(!obj)) return callBadAllocHandler(cls);
1780 obj->initInstanceIsa(cls, dtor);
1784 // Has ctor or raw isa or something. Use the slower path.
1785 id obj = class_createInstance(cls, 0);
1786 if (slowpath(!obj)) return callBadAllocHandler(cls);
1792 // No shortcuts available.
1793 if (allocWithZone) return [cls allocWithZone:nil];
1798 // Base class implementation of +alloc. cls is not nil.
1799 // Calls [cls allocWithZone:nil].
1801 _objc_rootAlloc(Class cls)
1803 return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
1806 // Calls [cls alloc].
1808 objc_alloc(Class cls)
1810 return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
1813 // Calls [cls allocWithZone:nil].
1815 objc_allocWithZone(Class cls)
1817 return callAlloc(cls, true/*checkNil*/, true/*allocWithZone*/);
1822 _objc_rootDealloc(id obj)
1830 _objc_rootFinalize(id obj __unused)
1833 _objc_fatal("_objc_rootFinalize called with garbage collection off");
1838 _objc_rootInit(id obj)
1840 // In practice, it will be hard to rely on this function.
1841 // Many classes do not properly chain -init calls.
1847 _objc_rootZone(id obj)
1851 // allocWithZone under __OBJC2__ ignores the zone parameter
1852 return malloc_default_zone();
1854 malloc_zone_t *rval = malloc_zone_from_ptr(obj);
1855 return rval ? rval : malloc_default_zone();
1860 _objc_rootHash(id obj)
1862 return (uintptr_t)obj;
1866 objc_autoreleasePoolPush(void)
1868 return AutoreleasePoolPage::push();
1872 objc_autoreleasePoolPop(void *ctxt)
1874 AutoreleasePoolPage::pop(ctxt);
1879 _objc_autoreleasePoolPush(void)
1881 return objc_autoreleasePoolPush();
1885 _objc_autoreleasePoolPop(void *ctxt)
1887 objc_autoreleasePoolPop(ctxt);
1891 _objc_autoreleasePoolPrint(void)
1893 AutoreleasePoolPage::printAll();
1897 // Same as objc_release but suitable for tail-calling
1898 // if you need the value back and don't want to push a frame before this point.
1899 __attribute__((noinline))
1901 objc_releaseAndReturn(id obj)
1907 // Same as objc_retainAutorelease but suitable for tail-calling
1908 // if you don't want to push a frame before this point.
1909 __attribute__((noinline))
1911 objc_retainAutoreleaseAndReturn(id obj)
1913 return objc_retainAutorelease(obj);
1917 // Prepare a value at +1 for return through a +0 autoreleasing convention.
1919 objc_autoreleaseReturnValue(id obj)
1921 if (prepareOptimizedReturn(ReturnAtPlus1)) return obj;
1923 return objc_autorelease(obj);
1926 // Prepare a value at +0 for return through a +0 autoreleasing convention.
1928 objc_retainAutoreleaseReturnValue(id obj)
1930 if (prepareOptimizedReturn(ReturnAtPlus0)) return obj;
1932 // not objc_autoreleaseReturnValue(objc_retain(obj))
1933 // because we don't need another optimization attempt
1934 return objc_retainAutoreleaseAndReturn(obj);
1937 // Accept a value returned through a +0 autoreleasing convention for use at +1.
1939 objc_retainAutoreleasedReturnValue(id obj)
1941 if (acceptOptimizedReturn() == ReturnAtPlus1) return obj;
1943 return objc_retain(obj);
1946 // Accept a value returned through a +0 autoreleasing convention for use at +0.
1948 objc_unsafeClaimAutoreleasedReturnValue(id obj)
1950 if (acceptOptimizedReturn() == ReturnAtPlus0) return obj;
1952 return objc_releaseAndReturn(obj);
1956 objc_retainAutorelease(id obj)
1958 return objc_autorelease(objc_retain(obj));
1962 _objc_deallocOnMainThreadHelper(void *context)
1964 id obj = (id)context;
1968 // convert objc_objectptr_t to id, callee must take ownership.
1969 id objc_retainedObject(objc_objectptr_t pointer) { return (id)pointer; }
1971 // convert objc_objectptr_t to id, without ownership transfer.
1972 id objc_unretainedObject(objc_objectptr_t pointer) { return (id)pointer; }
1974 // convert id to objc_objectptr_t, no ownership transfer.
1975 objc_objectptr_t objc_unretainedPointer(id object) { return object; }
1980 AutoreleasePoolPage::init();
1985 #if SUPPORT_TAGGED_POINTERS
1987 // Placeholder for old debuggers. When they inspect an
1988 // extended tagged pointer object they will see this isa.
1990 @interface __NSUnrecognizedTaggedPointer : NSObject
1993 @implementation __NSUnrecognizedTaggedPointer
1995 -(id) retain { return self; }
1996 -(oneway void) release { }
1997 -(id) autorelease { return self; }
2003 @implementation NSObject
2008 + (void)initialize {
2024 return object_getClass(self);
2027 + (Class)superclass {
2028 return self->superclass;
2031 - (Class)superclass {
2032 return [self class]->superclass;
2035 + (BOOL)isMemberOfClass:(Class)cls {
2036 return object_getClass((id)self) == cls;
2039 - (BOOL)isMemberOfClass:(Class)cls {
2040 return [self class] == cls;
2043 + (BOOL)isKindOfClass:(Class)cls {
2044 for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
2045 if (tcls == cls) return YES;
2050 - (BOOL)isKindOfClass:(Class)cls {
2051 for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
2052 if (tcls == cls) return YES;
2057 + (BOOL)isSubclassOfClass:(Class)cls {
2058 for (Class tcls = self; tcls; tcls = tcls->superclass) {
2059 if (tcls == cls) return YES;
2064 + (BOOL)isAncestorOfObject:(NSObject *)obj {
2065 for (Class tcls = [obj class]; tcls; tcls = tcls->superclass) {
2066 if (tcls == self) return YES;
2071 + (BOOL)instancesRespondToSelector:(SEL)sel {
2072 if (!sel) return NO;
2073 return class_respondsToSelector(self, sel);
2076 + (BOOL)respondsToSelector:(SEL)sel {
2077 if (!sel) return NO;
2078 return class_respondsToSelector_inst(object_getClass(self), sel, self);
2081 - (BOOL)respondsToSelector:(SEL)sel {
2082 if (!sel) return NO;
2083 return class_respondsToSelector_inst([self class], sel, self);
2086 + (BOOL)conformsToProtocol:(Protocol *)protocol {
2087 if (!protocol) return NO;
2088 for (Class tcls = self; tcls; tcls = tcls->superclass) {
2089 if (class_conformsToProtocol(tcls, protocol)) return YES;
2094 - (BOOL)conformsToProtocol:(Protocol *)protocol {
2095 if (!protocol) return NO;
2096 for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
2097 if (class_conformsToProtocol(tcls, protocol)) return YES;
2102 + (NSUInteger)hash {
2103 return _objc_rootHash(self);
2106 - (NSUInteger)hash {
2107 return _objc_rootHash(self);
2110 + (BOOL)isEqual:(id)obj {
2111 return obj == (id)self;
2114 - (BOOL)isEqual:(id)obj {
2136 + (IMP)instanceMethodForSelector:(SEL)sel {
2137 if (!sel) [self doesNotRecognizeSelector:sel];
2138 return class_getMethodImplementation(self, sel);
2141 + (IMP)methodForSelector:(SEL)sel {
2142 if (!sel) [self doesNotRecognizeSelector:sel];
2143 return object_getMethodImplementation((id)self, sel);
2146 - (IMP)methodForSelector:(SEL)sel {
2147 if (!sel) [self doesNotRecognizeSelector:sel];
2148 return object_getMethodImplementation(self, sel);
2151 + (BOOL)resolveClassMethod:(SEL)sel {
2155 + (BOOL)resolveInstanceMethod:(SEL)sel {
2159 // Replaced by CF (throws an NSException)
2160 + (void)doesNotRecognizeSelector:(SEL)sel {
2161 _objc_fatal("+[%s %s]: unrecognized selector sent to instance %p",
2162 class_getName(self), sel_getName(sel), self);
2165 // Replaced by CF (throws an NSException)
2166 - (void)doesNotRecognizeSelector:(SEL)sel {
2167 _objc_fatal("-[%s %s]: unrecognized selector sent to instance %p",
2168 object_getClassName(self), sel_getName(sel), self);
2172 + (id)performSelector:(SEL)sel {
2173 if (!sel) [self doesNotRecognizeSelector:sel];
2174 return ((id(*)(id, SEL))objc_msgSend)((id)self, sel);
2177 + (id)performSelector:(SEL)sel withObject:(id)obj {
2178 if (!sel) [self doesNotRecognizeSelector:sel];
2179 return ((id(*)(id, SEL, id))objc_msgSend)((id)self, sel, obj);
2182 + (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
2183 if (!sel) [self doesNotRecognizeSelector:sel];
2184 return ((id(*)(id, SEL, id, id))objc_msgSend)((id)self, sel, obj1, obj2);
2187 - (id)performSelector:(SEL)sel {
2188 if (!sel) [self doesNotRecognizeSelector:sel];
2189 return ((id(*)(id, SEL))objc_msgSend)(self, sel);
2192 - (id)performSelector:(SEL)sel withObject:(id)obj {
2193 if (!sel) [self doesNotRecognizeSelector:sel];
2194 return ((id(*)(id, SEL, id))objc_msgSend)(self, sel, obj);
2197 - (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
2198 if (!sel) [self doesNotRecognizeSelector:sel];
2199 return ((id(*)(id, SEL, id, id))objc_msgSend)(self, sel, obj1, obj2);
2203 // Replaced by CF (returns an NSMethodSignature)
2204 + (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)sel {
2205 _objc_fatal("+[NSObject instanceMethodSignatureForSelector:] "
2206 "not available without CoreFoundation");
2209 // Replaced by CF (returns an NSMethodSignature)
2210 + (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
2211 _objc_fatal("+[NSObject methodSignatureForSelector:] "
2212 "not available without CoreFoundation");
2215 // Replaced by CF (returns an NSMethodSignature)
2216 - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
2217 _objc_fatal("-[NSObject methodSignatureForSelector:] "
2218 "not available without CoreFoundation");
2221 + (void)forwardInvocation:(NSInvocation *)invocation {
2222 [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
2225 - (void)forwardInvocation:(NSInvocation *)invocation {
2226 [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
2229 + (id)forwardingTargetForSelector:(SEL)sel {
2233 - (id)forwardingTargetForSelector:(SEL)sel {
2238 // Replaced by CF (returns an NSString)
2239 + (NSString *)description {
2243 // Replaced by CF (returns an NSString)
2244 - (NSString *)description {
2248 + (NSString *)debugDescription {
2249 return [self description];
2252 - (NSString *)debugDescription {
2253 return [self description];
2258 return [callAlloc(self, false/*checkNil*/) init];
2265 // Replaced by ObjectAlloc
2267 return ((id)self)->rootRetain();
2271 + (BOOL)_tryRetain {
2275 // Replaced by ObjectAlloc
2276 - (BOOL)_tryRetain {
2277 return ((id)self)->rootTryRetain();
2280 + (BOOL)_isDeallocating {
2284 - (BOOL)_isDeallocating {
2285 return ((id)self)->rootIsDeallocating();
2288 + (BOOL)allowsWeakReference {
2292 + (BOOL)retainWeakReference {
2296 - (BOOL)allowsWeakReference {
2297 return ! [self _isDeallocating];
2300 - (BOOL)retainWeakReference {
2301 return [self _tryRetain];
2304 + (oneway void)release {
2307 // Replaced by ObjectAlloc
2308 - (oneway void)release {
2309 ((id)self)->rootRelease();
2316 // Replaced by ObjectAlloc
2318 return ((id)self)->rootAutorelease();
2321 + (NSUInteger)retainCount {
2325 - (NSUInteger)retainCount {
2326 return ((id)self)->rootRetainCount();
2330 return _objc_rootAlloc(self);
2333 // Replaced by ObjectAlloc
2334 + (id)allocWithZone:(struct _NSZone *)zone {
2335 return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
2338 // Replaced by CF (throws an NSException)
2344 return _objc_rootInit(self);
2347 // Replaced by CF (throws an NSException)
2352 // Replaced by NSZombies
2354 _objc_rootDealloc(self);
2357 // Previously used by GC. Now a placeholder for binary compatibility.
2361 + (struct _NSZone *)zone {
2362 return (struct _NSZone *)_objc_rootZone(self);
2365 - (struct _NSZone *)zone {
2366 return (struct _NSZone *)_objc_rootZone(self);
2373 + (id)copyWithZone:(struct _NSZone *)zone {
2378 return [(id)self copyWithZone:nil];
2385 + (id)mutableCopyWithZone:(struct _NSZone *)zone {
2390 return [(id)self mutableCopyWithZone:nil];