2 * Copyright (c) 2005-2009 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 /***********************************************************************
26 * Support for new-ABI classes and images.
27 **********************************************************************/
31 #include "objc-private.h"
32 #include "objc-runtime-new.h"
33 #include "objc-file.h"
34 #include "objc-cache.h"
36 #include <objc/message.h>
37 #include <mach/shared_region.h>
39 #define newprotocol(p) ((protocol_t *)p)
41 static void disableTaggedPointers();
42 static void detach_class(Class cls, BOOL isMeta);
43 static void free_class(Class cls);
44 static Class setSuperclass(Class cls, Class newSuper);
45 static Class realizeClass(Class cls);
46 static method_t *getMethodNoSuper_nolock(Class cls, SEL sel);
47 static method_t *getMethod_nolock(Class cls, SEL sel);
48 static IMP _method_getImplementation(method_t *m);
49 static IMP addMethod(Class cls, SEL name, IMP imp, const char *types, BOOL replace);
50 static NXHashTable *realizedClasses(void);
51 static bool isRRSelector(SEL sel);
52 static bool isAWZSelector(SEL sel);
53 static bool methodListImplementsRR(const method_list_t *mlist);
54 static bool methodListImplementsAWZ(const method_list_t *mlist);
55 static void updateCustomRR_AWZ(Class cls, method_t *meth);
56 static method_t *search_method_list(const method_list_t *mlist, SEL sel);
58 static void fixupMessageRef(message_ref_t *msg);
61 static bool MetaclassNSObjectAWZSwizzled;
62 static bool ClassNSObjectRRSwizzled;
65 id objc_noop_imp(id self, SEL _cmd __unused) {
70 /***********************************************************************
72 **********************************************************************/
75 mutex_t cacheUpdateLock = MUTEX_INITIALIZER;
76 recursive_mutex_t loadMethodLock = RECURSIVE_MUTEX_INITIALIZER;
80 rwlock_init(&selLock);
81 rwlock_init(&runtimeLock);
82 recursive_mutex_init(&loadMethodLock);
86 /***********************************************************************
87 * Non-pointer isa decoding
88 **********************************************************************/
89 #if SUPPORT_NONPOINTER_ISA
91 const uintptr_t objc_debug_isa_class_mask = ISA_MASK;
92 const uintptr_t objc_debug_isa_magic_mask = ISA_MAGIC_MASK;
93 const uintptr_t objc_debug_isa_magic_value = ISA_MAGIC_VALUE;
95 // die if masks overlap
96 STATIC_ASSERT((ISA_MASK & ISA_MAGIC_MASK) == 0);
98 // die if magic is wrong
99 STATIC_ASSERT((~ISA_MAGIC_MASK & ISA_MAGIC_VALUE) == 0);
101 // die if virtual address space bound goes up
102 STATIC_ASSERT((~ISA_MASK & MACH_VM_MAX_ADDRESS) == 0);
106 // These variables exist but enforce pointer alignment only.
107 const uintptr_t objc_debug_isa_class_mask = (~WORD_MASK);
108 const uintptr_t objc_debug_isa_magic_mask = WORD_MASK;
109 const uintptr_t objc_debug_isa_magic_value = 0;
121 category_pair_t list[0]; // variable-size
124 #define FOREACH_METHOD_LIST(_mlist, _cls, code) \
126 class_rw_t *_data = _cls->data(); \
127 const method_list_t *_mlist; \
128 if (_data->method_lists) { \
129 if (_data->flags & RW_METHOD_ARRAY) { \
130 method_list_t **_mlistp; \
131 for (_mlistp=_data->method_lists; _mlistp[0]; _mlistp++){ \
132 _mlist = _mlistp[0]; \
136 _mlist = _data->method_list; \
143 // As above, but skips the class's base method list.
144 #define FOREACH_CATEGORY_METHOD_LIST(_mlist, _cls, code) \
146 class_rw_t *_data = _cls->data(); \
147 const method_list_t *_mlist; \
148 if (_data->method_lists) { \
149 if (_data->flags & RW_METHOD_ARRAY) { \
150 if (_data->ro->baseMethods) { \
151 /* has base methods: use all mlists except the last */ \
152 method_list_t **_mlistp; \
153 for (_mlistp=_data->method_lists; _mlistp[0] && _mlistp[1]; _mlistp++){ \
154 _mlist = _mlistp[0]; \
158 /* no base methods: use all mlists including the last */ \
159 method_list_t **_mlistp; \
160 for (_mlistp=_data->method_lists; _mlistp[0]; _mlistp++){ \
161 _mlist = _mlistp[0]; \
165 } else if (!_data->ro->baseMethods) { \
166 /* no base methods: use all mlists including the last */ \
167 _mlist = _data->method_list; \
175 Low two bits of mlist->entsize is used as the fixed-up marker.
176 PREOPTIMIZED VERSION:
177 Method lists from shared cache are 1 (uniqued) or 3 (uniqued and sorted).
178 (Protocol method lists are not sorted because of their extra parallel data)
179 Runtime fixed-up method lists get 3.
180 UN-PREOPTIMIZED VERSION:
181 Method lists from shared cache are 1 (uniqued) or 3 (uniqued and sorted)
182 Shared cache's sorting and uniquing are not trusted, but do affect the
183 location of the selector name string.
184 Runtime fixed-up method lists get 2.
187 static uint32_t fixed_up_method_list = 3;
190 disableSharedCacheOptimizations(void)
192 fixed_up_method_list = 2;
196 isMethodListFixedUp(const method_list_t *mlist)
198 return (mlist->entsize_NEVER_USE & 3) == fixed_up_method_list;
202 static const char *sel_cname(SEL sel)
204 return (const char *)(void *)sel;
209 setMethodListFixedUp(method_list_t *mlist)
211 rwlock_assert_writing(&runtimeLock);
212 assert(!isMethodListFixedUp(mlist));
213 mlist->entsize_NEVER_USE =
214 (mlist->entsize_NEVER_USE & ~3) | fixed_up_method_list;
218 static size_t chained_property_list_size(const chained_property_list *plist)
220 return sizeof(chained_property_list) +
221 plist->count * sizeof(property_t);
225 static size_t protocol_list_size(const protocol_list_t *plist)
227 return sizeof(protocol_list_t) + plist->count * sizeof(protocol_t *);
231 // low bit used by dyld shared cache
232 static uint32_t method_list_entsize(const method_list_t *mlist)
234 return mlist->entsize_NEVER_USE & ~3;
237 static size_t method_list_size(const method_list_t *mlist)
239 return sizeof(method_list_t) + (mlist->count-1)*method_list_entsize(mlist);
242 static method_t *method_list_nth(const method_list_t *mlist, uint32_t i)
244 return &mlist->get(i);
247 static uint32_t method_list_count(const method_list_t *mlist)
249 return mlist ? mlist->count : 0;
252 static void method_list_swap(method_list_t *mlist, uint32_t i, uint32_t j)
254 size_t entsize = method_list_entsize(mlist);
256 memcpy(temp, method_list_nth(mlist, i), entsize);
257 memcpy(method_list_nth(mlist, i), method_list_nth(mlist, j), entsize);
258 memcpy(method_list_nth(mlist, j), temp, entsize);
261 static uint32_t method_list_index(const method_list_t *mlist,const method_t *m)
263 uint32_t i = (uint32_t)(((uintptr_t)m - (uintptr_t)mlist) / method_list_entsize(mlist));
264 assert(i < mlist->count);
269 static size_t ivar_list_size(const ivar_list_t *ilist)
271 return sizeof(ivar_list_t) + (ilist->count-1) * ilist->entsize;
274 static ivar_t *ivar_list_nth(const ivar_list_t *ilist, uint32_t i)
276 return (ivar_t *)(i*ilist->entsize + (char *)&ilist->first);
280 static method_list_t *cat_method_list(const category_t *cat, BOOL isMeta)
282 if (!cat) return nil;
284 if (isMeta) return cat->classMethods;
285 else return cat->instanceMethods;
288 static uint32_t cat_method_count(const category_t *cat, BOOL isMeta)
290 method_list_t *cmlist = cat_method_list(cat, isMeta);
291 return cmlist ? cmlist->count : 0;
294 static method_t *cat_method_nth(const category_t *cat, BOOL isMeta, uint32_t i)
296 method_list_t *cmlist = cat_method_list(cat, isMeta);
297 if (!cmlist) return nil;
299 return method_list_nth(cmlist, i);
304 property_list_nth(const property_list_t *plist, uint32_t i)
306 return (property_t *)(i*plist->entsize + (char *)&plist->first);
309 // fixme don't chain property lists
310 typedef struct chained_property_list {
311 struct chained_property_list *next;
313 property_t list[0]; // variable-size
314 } chained_property_list;
317 static void try_free(const void *p)
319 if (p && malloc_size(p)) free((void *)p);
324 alloc_class_for_subclass(Class supercls, size_t extraBytes)
326 if (!supercls || !supercls->isSwift()) {
327 return _calloc_class(sizeof(objc_class) + extraBytes);
330 // Superclass is a Swift class. New subclass must duplicate its extra bits.
332 // Allocate the new class, with space for super's prefix and suffix
333 // and self's extraBytes.
334 swift_class_t *swiftSupercls = (swift_class_t *)supercls;
335 size_t superSize = swiftSupercls->classSize;
336 void *superBits = swiftSupercls->baseAddress();
337 void *bits = _malloc_internal(superSize + extraBytes);
339 // Copy all of the superclass's data to the new class.
340 memcpy(bits, superBits, superSize);
342 // Erase the objc data and the Swift description in the new class.
343 swift_class_t *swcls = (swift_class_t *)
344 ((uint8_t *)bits + swiftSupercls->classAddressOffset);
345 bzero(swcls, sizeof(objc_class));
346 swcls->description = nil;
348 // Mark this class as Swift-enhanced.
349 swcls->bits.setIsSwift();
355 /***********************************************************************
356 * object_getIndexedIvars.
357 **********************************************************************/
358 void *object_getIndexedIvars(id obj)
360 uint8_t *base = (uint8_t *)obj;
362 if (!obj) return nil;
363 if (obj->isTaggedPointer()) return nil;
365 if (!obj->isClass()) return base + obj->ISA()->alignedInstanceSize();
367 Class cls = (Class)obj;
368 if (!cls->isSwift()) return base + sizeof(objc_class);
370 swift_class_t *swcls = (swift_class_t *)cls;
371 return base - swcls->classAddressOffset + word_align(swcls->classSize);
375 /***********************************************************************
377 * Reallocates rw->ro if necessary to make it writeable.
378 * Locking: runtimeLock must be held by the caller.
379 **********************************************************************/
380 static class_ro_t *make_ro_writeable(class_rw_t *rw)
382 rwlock_assert_writing(&runtimeLock);
384 if (rw->flags & RW_COPIED_RO) {
385 // already writeable, do nothing
387 class_ro_t *ro = (class_ro_t *)
388 _memdup_internal(rw->ro, sizeof(*rw->ro));
390 rw->flags |= RW_COPIED_RO;
392 return (class_ro_t *)rw->ro;
396 /***********************************************************************
397 * unattachedCategories
398 * Returns the class => categories map of unattached categories.
399 * Locking: runtimeLock must be held by the caller.
400 **********************************************************************/
401 static NXMapTable *unattachedCategories(void)
403 rwlock_assert_writing(&runtimeLock);
405 static NXMapTable *category_map = nil;
407 if (category_map) return category_map;
409 // fixme initial map size
410 category_map = NXCreateMapTableFromZone(NXPtrValueMapPrototype, 16,
411 _objc_internal_zone());
417 /***********************************************************************
418 * addUnattachedCategoryForClass
419 * Records an unattached category.
420 * Locking: runtimeLock must be held by the caller.
421 **********************************************************************/
422 static void addUnattachedCategoryForClass(category_t *cat, Class cls,
423 header_info *catHeader)
425 rwlock_assert_writing(&runtimeLock);
427 BOOL catFromBundle = (catHeader->mhdr->filetype == MH_BUNDLE) ? YES: NO;
429 // DO NOT use cat->cls! cls may be cat->cls->isa instead
430 NXMapTable *cats = unattachedCategories();
433 list = (category_list *)NXMapGet(cats, cls);
435 list = (category_list *)
436 _calloc_internal(sizeof(*list) + sizeof(list->list[0]), 1);
438 list = (category_list *)
439 _realloc_internal(list, sizeof(*list) + sizeof(list->list[0]) * (list->count + 1));
441 list->list[list->count++] = (category_pair_t){cat, catFromBundle};
442 NXMapInsert(cats, cls, list);
446 /***********************************************************************
447 * removeUnattachedCategoryForClass
448 * Removes an unattached category.
449 * Locking: runtimeLock must be held by the caller.
450 **********************************************************************/
451 static void removeUnattachedCategoryForClass(category_t *cat, Class cls)
453 rwlock_assert_writing(&runtimeLock);
455 // DO NOT use cat->cls! cls may be cat->cls->isa instead
456 NXMapTable *cats = unattachedCategories();
459 list = (category_list *)NXMapGet(cats, cls);
463 for (i = 0; i < list->count; i++) {
464 if (list->list[i].cat == cat) {
465 // shift entries to preserve list order
466 memmove(&list->list[i], &list->list[i+1],
467 (list->count-i-1) * sizeof(list->list[i]));
475 /***********************************************************************
476 * unattachedCategoriesForClass
477 * Returns the list of unattached categories for a class, and
478 * deletes them from the list.
479 * The result must be freed by the caller.
480 * Locking: runtimeLock must be held by the caller.
481 **********************************************************************/
482 static category_list *unattachedCategoriesForClass(Class cls)
484 rwlock_assert_writing(&runtimeLock);
485 return (category_list *)NXMapRemove(unattachedCategories(), cls);
489 /***********************************************************************
491 * Returns class NSObject.
493 **********************************************************************/
494 static Class classNSObject(void)
496 extern objc_class OBJC_CLASS_$_NSObject;
497 return (Class)&OBJC_CLASS_$_NSObject;
501 /***********************************************************************
503 * Implementation of PrintReplacedMethods / OBJC_PRINT_REPLACED_METHODS.
504 * Warn about methods from cats that override other methods in cats or cls.
505 * Assumes no methods from cats have been added to cls yet.
506 **********************************************************************/
507 static void printReplacements(Class cls, category_list *cats)
510 BOOL isMeta = cls->isMetaClass();
514 // Newest categories are LAST in cats
515 // Later categories override earlier ones.
516 for (c = 0; c < cats->count; c++) {
517 category_t *cat = cats->list[c].cat;
518 uint32_t cmCount = cat_method_count(cat, isMeta);
520 for (m = 0; m < cmCount; m++) {
522 method_t *meth2 = nil;
523 method_t *meth = cat_method_nth(cat, isMeta, m);
524 SEL s = sel_registerName(sel_cname(meth->name));
526 // Don't warn about GC-ignored selectors
527 if (ignoreSelector(s)) continue;
529 // Look for method in earlier categories
530 for (c2 = 0; c2 < c; c2++) {
531 category_t *cat2 = cats->list[c2].cat;
532 uint32_t cm2Count = cat_method_count(cat2, isMeta);
533 for (m2 = 0; m2 < cm2Count; m2++) {
534 meth2 = cat_method_nth(cat2, isMeta, m2);
535 SEL s2 = sel_registerName(sel_cname(meth2->name));
536 if (s == s2) goto whine;
540 // Look for method in cls
541 FOREACH_METHOD_LIST(mlist, cls, {
542 for (m2 = 0; m2 < mlist->count; m2++) {
543 meth2 = method_list_nth(mlist, m2);
544 SEL s2 = sel_registerName(sel_cname(meth2->name));
545 if (s == s2) goto whine;
549 // Didn't find any override.
553 // Found an override.
554 logReplacedMethod(cls->nameForLogging(), s,
555 cls->isMetaClass(), cat->name,
556 _method_getImplementation(meth2),
557 _method_getImplementation(meth));
563 static BOOL isBundleClass(Class cls)
565 return (cls->data()->ro->flags & RO_FROM_BUNDLE) ? YES : NO;
569 static method_list_t *
570 fixupMethodList(method_list_t *mlist, bool bundleCopy, bool sort)
572 rwlock_assert_writing(&runtimeLock);
573 assert(!isMethodListFixedUp(mlist));
575 mlist = (method_list_t *)
576 _memdup_internal(mlist, method_list_size(mlist));
578 // fixme lock less in attachMethodLists ?
581 // Unique selectors in list.
583 for (m = 0; m < mlist->count; m++) {
584 method_t *meth = method_list_nth(mlist, m);
586 const char *name = sel_cname(meth->name);
588 SEL sel = sel_registerNameNoLock(name, bundleCopy);
591 if (ignoreSelector(sel)) {
592 meth->imp = (IMP)&_objc_ignored_method;
598 // Sort by selector address.
600 method_t::SortBySELAddress sorter;
601 std::stable_sort(mlist->begin(), mlist->end(), sorter);
604 // Mark method list as uniqued and sorted
605 setMethodListFixedUp(mlist);
612 attachMethodLists(Class cls, method_list_t **addedLists, int addedCount,
613 bool baseMethods, bool methodsFromBundle,
616 rwlock_assert_writing(&runtimeLock);
618 // Don't scan redundantly
619 bool scanForCustomRR = !UseGC && !cls->hasCustomRR();
620 bool scanForCustomAWZ = !UseGC && !cls->hasCustomAWZ();
622 // There exist RR/AWZ special cases for some class's base methods.
623 // But this code should never need to scan base methods for RR/AWZ:
624 // default RR/AWZ cannot be set before setInitialized().
625 // Therefore we need not handle any special cases here.
627 assert(!scanForCustomRR && !scanForCustomAWZ);
630 // Method list array is nil-terminated.
631 // Some elements of lists are nil; we must filter them out.
633 method_list_t *oldBuf[2];
634 method_list_t **oldLists;
636 if (cls->data()->flags & RW_METHOD_ARRAY) {
637 oldLists = cls->data()->method_lists;
639 oldBuf[0] = cls->data()->method_list;
644 while (oldLists[oldCount]) oldCount++;
647 int newCount = oldCount;
648 for (int i = 0; i < addedCount; i++) {
649 if (addedLists[i]) newCount++; // only non-nil entries get added
652 method_list_t *newBuf[2];
653 method_list_t **newLists;
655 newLists = (method_list_t **)
656 _malloc_internal((1 + newCount) * sizeof(*newLists));
661 // Add method lists to array.
662 // Reallocate un-fixed method lists.
663 // The new methods are PREPENDED to the method list array.
667 for (i = 0; i < addedCount; i++) {
668 method_list_t *mlist = addedLists[i];
669 if (!mlist) continue;
671 // Fixup selectors if necessary
672 if (!isMethodListFixedUp(mlist)) {
673 mlist = fixupMethodList(mlist, methodsFromBundle, true/*sort*/);
676 // Scan for method implementations tracked by the class's flags
677 if (scanForCustomRR && methodListImplementsRR(mlist)) {
678 cls->setHasCustomRR();
679 scanForCustomRR = false;
681 if (scanForCustomAWZ && methodListImplementsAWZ(mlist)) {
682 cls->setHasCustomAWZ();
683 scanForCustomAWZ = false;
686 // Update method caches
688 cache_eraseMethods(cls, mlist);
691 // Fill method list array
692 newLists[newCount++] = mlist;
695 // Copy old methods to the method list array
696 for (i = 0; i < oldCount; i++) {
697 newLists[newCount++] = oldLists[i];
699 if (oldLists && oldLists != oldBuf) free(oldLists);
702 newLists[newCount] = nil;
705 assert(newLists != newBuf);
706 cls->data()->method_lists = newLists;
707 cls->setInfo(RW_METHOD_ARRAY);
709 assert(newLists == newBuf);
710 cls->data()->method_list = newLists[0];
711 assert(!(cls->data()->flags & RW_METHOD_ARRAY));
716 attachCategoryMethods(Class cls, category_list *cats, bool flushCaches)
719 if (PrintReplacedMethods) printReplacements(cls, cats);
721 bool isMeta = cls->isMetaClass();
722 method_list_t **mlists = (method_list_t **)
723 _malloc_internal(cats->count * sizeof(*mlists));
725 // Count backwards through cats to get newest categories first
728 BOOL fromBundle = NO;
730 method_list_t *mlist = cat_method_list(cats->list[i].cat, isMeta);
732 mlists[mcount++] = mlist;
733 fromBundle |= cats->list[i].fromBundle;
737 attachMethodLists(cls, mlists, mcount, NO, fromBundle, flushCaches);
739 _free_internal(mlists);
743 static chained_property_list *
744 buildPropertyList(const property_list_t *plist, category_list *cats, BOOL isMeta)
746 chained_property_list *newlist;
750 // Count properties in all lists.
751 if (plist) count = plist->count;
753 for (c = 0; c < cats->count; c++) {
754 category_t *cat = cats->list[c].cat;
756 if (isMeta && cat->classProperties) {
757 count += cat->classProperties->count;
760 if (!isMeta && cat->instanceProperties) {
761 count += cat->instanceProperties->count;
766 if (count == 0) return nil;
768 // Allocate new list.
769 newlist = (chained_property_list *)
770 _malloc_internal(sizeof(*newlist) + count * sizeof(property_t));
774 // Copy properties; newest categories first, then ordinary properties
778 property_list_t *cplist;
779 category_t *cat = cats->list[c].cat;
782 cplist = cat->classProperties;
785 cplist = cat->instanceProperties;
788 for (p = 0; p < cplist->count; p++) {
789 newlist->list[newlist->count++] =
790 *property_list_nth(cplist, p);
796 for (p = 0; p < plist->count; p++) {
797 newlist->list[newlist->count++] = *property_list_nth(plist, p);
801 assert(newlist->count == count);
807 static const protocol_list_t **
808 buildProtocolList(category_list *cats, const protocol_list_t *base,
809 const protocol_list_t **protos)
811 const protocol_list_t **p, **newp;
812 const protocol_list_t **newprotos;
813 unsigned int count = 0;
816 // count protocol list in base
819 // count protocol lists in cats
820 if (cats) for (i = 0; i < cats->count; i++) {
821 category_t *cat = cats->list[i].cat;
822 if (cat->protocols) count++;
825 // no base or category protocols? return existing protocols unchanged
826 if (count == 0) return protos;
828 // count protocol lists in protos
829 for (p = protos; p && *p; p++) {
833 if (count == 0) return nil;
835 newprotos = (const protocol_list_t **)
836 _malloc_internal((count+1) * sizeof(protocol_list_t *));
843 for (p = protos; p && *p; p++) {
847 if (cats) for (i = 0; i < cats->count; i++) {
848 category_t *cat = cats->list[i].cat;
849 if (cat->protocols) {
850 *newp++ = cat->protocols;
860 /***********************************************************************
862 * Fixes up cls's method list, protocol list, and property list.
863 * Attaches any outstanding categories.
864 * Locking: runtimeLock must be held by the caller
865 **********************************************************************/
866 static void methodizeClass(Class cls)
871 rwlock_assert_writing(&runtimeLock);
873 isMeta = cls->isMetaClass();
875 // Methodizing for the first time
876 if (PrintConnecting) {
877 _objc_inform("CLASS: methodizing class '%s' %s",
878 cls->nameForLogging(), isMeta ? "(meta)" : "");
881 // Build method and protocol and property lists.
882 // Include methods and protocols and properties from categories, if any
884 attachMethodLists(cls, (method_list_t **)&cls->data()->ro->baseMethods, 1,
885 YES, isBundleClass(cls), NO);
887 // Root classes get bonus method implementations if they don't have
888 // them already. These apply before category replacements.
890 if (cls->isRootMetaclass()) {
892 addMethod(cls, SEL_initialize, (IMP)&objc_noop_imp, "", NO);
895 cats = unattachedCategoriesForClass(cls);
896 attachCategoryMethods(cls, cats, NO);
898 if (cats || cls->data()->ro->baseProperties) {
899 cls->data()->properties =
900 buildPropertyList(cls->data()->ro->baseProperties, cats, isMeta);
903 if (cats || cls->data()->ro->baseProtocols) {
904 cls->data()->protocols =
905 buildProtocolList(cats, cls->data()->ro->baseProtocols, nil);
908 if (PrintConnecting) {
911 for (i = 0; i < cats->count; i++) {
912 _objc_inform("CLASS: attached category %c%s(%s)",
914 cls->nameForLogging(), cats->list[i].cat->name);
919 if (cats) _free_internal(cats);
922 // Debug: sanity-check all SELs; log method list contents
923 FOREACH_METHOD_LIST(mlist, cls, {
924 method_list_t::method_iterator iter = mlist->begin();
925 method_list_t::method_iterator end = mlist->end();
926 for ( ; iter != end; ++iter) {
927 if (PrintConnecting) {
928 _objc_inform("METHOD %c[%s %s]", isMeta ? '+' : '-',
929 cls->nameForLogging(), sel_getName(iter->name));
931 assert(ignoreSelector(iter->name) || sel_registerName(sel_getName(iter->name))==iter->name);
938 /***********************************************************************
940 * Attach outstanding categories to an existing class.
941 * Fixes up cls's method list, protocol list, and property list.
942 * Updates method caches for cls and its subclasses.
943 * Locking: runtimeLock must be held by the caller
944 **********************************************************************/
945 static void remethodizeClass(Class cls)
950 rwlock_assert_writing(&runtimeLock);
952 isMeta = cls->isMetaClass();
954 // Re-methodizing: check for more categories
955 if ((cats = unattachedCategoriesForClass(cls))) {
956 chained_property_list *newproperties;
957 const protocol_list_t **newprotos;
959 if (PrintConnecting) {
960 _objc_inform("CLASS: attaching categories to class '%s' %s",
961 cls->nameForLogging(), isMeta ? "(meta)" : "");
964 // Update methods, properties, protocols
966 attachCategoryMethods(cls, cats, YES);
968 newproperties = buildPropertyList(nil, cats, isMeta);
970 newproperties->next = cls->data()->properties;
971 cls->data()->properties = newproperties;
974 newprotos = buildProtocolList(cats, nil, cls->data()->protocols);
975 if (cls->data()->protocols && cls->data()->protocols != newprotos) {
976 _free_internal(cls->data()->protocols);
978 cls->data()->protocols = newprotos;
980 _free_internal(cats);
985 /***********************************************************************
987 * Returns the secondary metaclass => class map
988 * Used for some cases of +initialize and +resolveClassMethod:.
989 * This map does not contain all class and metaclass pairs. It only
990 * contains metaclasses whose classes would be in the runtime-allocated
991 * named-class table, but are not because some other class with the same name
993 * Classes with no duplicates are not included.
994 * Classes in the preoptimized named-class table are not included.
995 * Classes whose duplicates are in the preoptimized table are not included.
996 * Most code should use getNonMetaClass() instead of reading this table.
997 * Locking: runtimeLock must be read- or write-locked by the caller
998 **********************************************************************/
999 static NXMapTable *nonmeta_class_map = nil;
1000 static NXMapTable *nonMetaClasses(void)
1002 rwlock_assert_locked(&runtimeLock);
1004 if (nonmeta_class_map) return nonmeta_class_map;
1006 // nonmeta_class_map is typically small
1007 INIT_ONCE_PTR(nonmeta_class_map,
1008 NXCreateMapTableFromZone(NXPtrValueMapPrototype, 32,
1009 _objc_internal_zone()),
1012 return nonmeta_class_map;
1016 /***********************************************************************
1018 * Adds metacls => cls to the secondary metaclass map
1019 * Locking: runtimeLock must be held by the caller
1020 **********************************************************************/
1021 static void addNonMetaClass(Class cls)
1023 rwlock_assert_writing(&runtimeLock);
1025 old = NXMapInsert(nonMetaClasses(), cls->ISA(), cls);
1027 assert(!cls->isMetaClass());
1028 assert(cls->ISA()->isMetaClass());
1033 static void removeNonMetaClass(Class cls)
1035 rwlock_assert_writing(&runtimeLock);
1036 NXMapRemove(nonMetaClasses(), cls->ISA());
1040 static bool scanMangledField(const char *&string, const char *end,
1041 const char *&field, int& length)
1043 // Leading zero not allowed.
1044 if (*string == '0') return false;
1048 while (field < end) {
1050 if (!isdigit(c)) break;
1052 if (__builtin_smul_overflow(length, 10, &length)) return false;
1053 if (__builtin_sadd_overflow(length, c - '0', &length)) return false;
1056 string = field + length;
1057 return length > 0 && string <= end;
1061 /***********************************************************************
1062 * copySwiftV1DemangledName
1063 * Returns the pretty form of the given Swift-v1-mangled class or protocol name.
1064 * Returns nil if the string doesn't look like a mangled Swift v1 name.
1065 * The result must be freed with free().
1066 **********************************************************************/
1067 static char *copySwiftV1DemangledName(const char *string, bool isProtocol = false)
1069 if (!string) return nil;
1071 // Swift mangling prefix.
1072 if (strncmp(string, isProtocol ? "_TtP" : "_TtC", 4) != 0) return nil;
1075 const char *end = string + strlen(string);
1080 if (strncmp(string, "Ss", 2) == 0) {
1085 if (! scanMangledField(string, end, prefix, prefixLength)) return nil;
1088 // Class or protocol name.
1091 if (! scanMangledField(string, end, suffix, suffixLength)) return nil;
1094 // Remainder must be "_".
1095 if (strcmp(string, "_") != 0) return nil;
1097 // Remainder must be empty.
1098 if (string != end) return nil;
1102 asprintf(&result, "%.*s.%.*s", prefixLength,prefix, suffixLength,suffix);
1107 /***********************************************************************
1108 * copySwiftV1MangledName
1109 * Returns the Swift 1.0 mangled form of the given class or protocol name.
1110 * Returns nil if the string doesn't look like an unmangled Swift name.
1111 * The result must be freed with free().
1112 **********************************************************************/
1113 static char *copySwiftV1MangledName(const char *string, bool isProtocol = false)
1115 if (!string) return nil;
1117 size_t dotCount = 0;
1120 for (s = string; *s; s++) {
1123 dotIndex = s - string;
1126 size_t stringLength = s - string;
1128 if (dotCount != 1 || dotIndex == 0 || dotIndex >= stringLength-1) {
1132 const char *prefix = string;
1133 size_t prefixLength = dotIndex;
1134 const char *suffix = string + dotIndex + 1;
1135 size_t suffixLength = stringLength - (dotIndex + 1);
1139 if (strncmp(prefix, "Swift", prefixLength) == 0) {
1140 asprintf(&name, "_Tt%cSs%zu%.*s%s",
1141 isProtocol ? 'P' : 'C',
1142 suffixLength, (int)suffixLength, suffix,
1143 isProtocol ? "_" : "");
1145 asprintf(&name, "_Tt%c%zu%.*s%zu%.*s%s",
1146 isProtocol ? 'P' : 'C',
1147 prefixLength, (int)prefixLength, prefix,
1148 suffixLength, (int)suffixLength, suffix,
1149 isProtocol ? "_" : "");
1155 /***********************************************************************
1157 * Looks up a class by name. The class MIGHT NOT be realized.
1158 * Demangled Swift names are recognized.
1159 * Locking: runtimeLock must be read- or write-locked by the caller.
1160 **********************************************************************/
1162 // This is a misnomer: gdb_objc_realized_classes is actually a list of
1163 // named classes not in the dyld shared cache, whether realized or not.
1164 NXMapTable *gdb_objc_realized_classes; // exported for debuggers in objc-gdb.h
1166 static Class getClass_impl(const char *name)
1168 rwlock_assert_locked(&runtimeLock);
1170 // allocated in _read_images
1171 assert(gdb_objc_realized_classes);
1173 // Try runtime-allocated table
1174 Class result = (Class)NXMapGet(gdb_objc_realized_classes, name);
1175 if (result) return result;
1177 // Try table from dyld shared cache
1178 return getPreoptimizedClass(name);
1181 static Class getClass(const char *name)
1183 rwlock_assert_locked(&runtimeLock);
1186 Class result = getClass_impl(name);
1187 if (result) return result;
1189 // Try Swift-mangled equivalent of the given name.
1190 if (char *swName = copySwiftV1MangledName(name)) {
1191 result = getClass_impl(swName);
1200 /***********************************************************************
1202 * Adds name => cls to the named non-meta class map.
1203 * Warns about duplicate class names and keeps the old mapping.
1204 * Locking: runtimeLock must be held by the caller
1205 **********************************************************************/
1206 static void addNamedClass(Class cls, const char *name)
1208 rwlock_assert_writing(&runtimeLock);
1210 if ((old = getClass(name))) {
1211 inform_duplicate(name, old, cls);
1213 // getNonMetaClass uses name lookups. Classes not found by name
1214 // lookup must be in the secondary meta->nonmeta table.
1215 addNonMetaClass(cls);
1217 NXMapInsert(gdb_objc_realized_classes, name, cls);
1219 assert(!(cls->data()->flags & RO_META));
1221 // wrong: constructed classes are already realized when they get here
1222 // assert(!cls->isRealized());
1226 /***********************************************************************
1228 * Removes cls from the name => cls map.
1229 * Locking: runtimeLock must be held by the caller
1230 **********************************************************************/
1231 static void removeNamedClass(Class cls, const char *name)
1233 rwlock_assert_writing(&runtimeLock);
1234 assert(!(cls->data()->flags & RO_META));
1235 if (cls == NXMapGet(gdb_objc_realized_classes, name)) {
1236 NXMapRemove(gdb_objc_realized_classes, name);
1238 // cls has a name collision with another class - don't remove the other
1239 // but do remove cls from the secondary metaclass->class map.
1240 removeNonMetaClass(cls);
1245 /***********************************************************************
1247 * Returns the class list for realized non-meta classes.
1248 * Locking: runtimeLock must be read- or write-locked by the caller
1249 **********************************************************************/
1250 static NXHashTable *realized_class_hash = nil;
1252 static NXHashTable *realizedClasses(void)
1254 rwlock_assert_locked(&runtimeLock);
1256 // allocated in _read_images
1257 assert(realized_class_hash);
1259 return realized_class_hash;
1263 /***********************************************************************
1264 * realizedMetaclasses
1265 * Returns the class list for realized metaclasses.
1266 * Locking: runtimeLock must be read- or write-locked by the caller
1267 **********************************************************************/
1268 static NXHashTable *realized_metaclass_hash = nil;
1269 static NXHashTable *realizedMetaclasses(void)
1271 rwlock_assert_locked(&runtimeLock);
1273 // allocated in _read_images
1274 assert(realized_metaclass_hash);
1276 return realized_metaclass_hash;
1280 /***********************************************************************
1282 * Adds cls to the realized non-meta class hash.
1283 * Locking: runtimeLock must be held by the caller
1284 **********************************************************************/
1285 static void addRealizedClass(Class cls)
1287 rwlock_assert_writing(&runtimeLock);
1289 old = NXHashInsert(realizedClasses(), cls);
1290 objc_addRegisteredClass(cls);
1291 assert(!cls->isMetaClass());
1296 /***********************************************************************
1297 * removeRealizedClass
1298 * Removes cls from the realized non-meta class hash.
1299 * Locking: runtimeLock must be held by the caller
1300 **********************************************************************/
1301 static void removeRealizedClass(Class cls)
1303 rwlock_assert_writing(&runtimeLock);
1304 if (cls->isRealized()) {
1305 assert(!cls->isMetaClass());
1306 NXHashRemove(realizedClasses(), cls);
1307 objc_removeRegisteredClass(cls);
1312 /***********************************************************************
1313 * addRealizedMetaclass
1314 * Adds cls to the realized metaclass hash.
1315 * Locking: runtimeLock must be held by the caller
1316 **********************************************************************/
1317 static void addRealizedMetaclass(Class cls)
1319 rwlock_assert_writing(&runtimeLock);
1321 old = NXHashInsert(realizedMetaclasses(), cls);
1322 assert(cls->isMetaClass());
1327 /***********************************************************************
1328 * removeRealizedMetaclass
1329 * Removes cls from the realized metaclass hash.
1330 * Locking: runtimeLock must be held by the caller
1331 **********************************************************************/
1332 static void removeRealizedMetaclass(Class cls)
1334 rwlock_assert_writing(&runtimeLock);
1335 if (cls->isRealized()) {
1336 assert(cls->isMetaClass());
1337 NXHashRemove(realizedMetaclasses(), cls);
1342 /***********************************************************************
1343 * futureNamedClasses
1344 * Returns the classname => future class map for unrealized future classes.
1345 * Locking: runtimeLock must be held by the caller
1346 **********************************************************************/
1347 static NXMapTable *futureNamedClasses(void)
1349 rwlock_assert_writing(&runtimeLock);
1351 static NXMapTable *future_named_class_map = nil;
1353 if (future_named_class_map) return future_named_class_map;
1355 // future_named_class_map is big enough for CF's classes and a few others
1356 future_named_class_map =
1357 NXCreateMapTableFromZone(NXStrValueMapPrototype, 32,
1358 _objc_internal_zone());
1360 return future_named_class_map;
1364 /***********************************************************************
1365 * addFutureNamedClass
1366 * Installs cls as the class structure to use for the named class if it appears.
1367 * Locking: runtimeLock must be held by the caller
1368 **********************************************************************/
1369 static void addFutureNamedClass(const char *name, Class cls)
1373 rwlock_assert_writing(&runtimeLock);
1376 _objc_inform("FUTURE: reserving %p for %s", (void*)cls, name);
1379 class_rw_t *rw = (class_rw_t *)_calloc_internal(sizeof(class_rw_t), 1);
1380 class_ro_t *ro = (class_ro_t *)_calloc_internal(sizeof(class_ro_t), 1);
1381 ro->name = _strdup_internal(name);
1384 cls->data()->flags = RO_FUTURE;
1386 old = NXMapKeyCopyingInsert(futureNamedClasses(), name, cls);
1391 /***********************************************************************
1392 * removeFutureNamedClass
1393 * Removes the named class from the unrealized future class list,
1394 * because it has been realized.
1395 * Locking: runtimeLock must be held by the caller
1396 **********************************************************************/
1397 static void removeFutureNamedClass(const char *name)
1399 rwlock_assert_writing(&runtimeLock);
1401 NXMapKeyFreeingRemove(futureNamedClasses(), name);
1405 /***********************************************************************
1407 * Returns the oldClass => newClass map for realized future classes.
1408 * Returns the oldClass => nil map for ignored weak-linked classes.
1409 * Locking: runtimeLock must be read- or write-locked by the caller
1410 **********************************************************************/
1411 static NXMapTable *remappedClasses(BOOL create)
1413 static NXMapTable *remapped_class_map = nil;
1415 rwlock_assert_locked(&runtimeLock);
1417 if (remapped_class_map) return remapped_class_map;
1418 if (!create) return nil;
1420 // remapped_class_map is big enough to hold CF's classes and a few others
1421 INIT_ONCE_PTR(remapped_class_map,
1422 NXCreateMapTableFromZone(NXPtrValueMapPrototype, 32,
1423 _objc_internal_zone()),
1426 return remapped_class_map;
1430 /***********************************************************************
1432 * Returns YES if no classes have been remapped
1433 * Locking: runtimeLock must be read- or write-locked by the caller
1434 **********************************************************************/
1435 static BOOL noClassesRemapped(void)
1437 rwlock_assert_locked(&runtimeLock);
1439 BOOL result = (remappedClasses(NO) == nil);
1444 /***********************************************************************
1446 * newcls is a realized future class, replacing oldcls.
1447 * OR newcls is nil, replacing ignored weak-linked class oldcls.
1448 * Locking: runtimeLock must be write-locked by the caller
1449 **********************************************************************/
1450 static void addRemappedClass(Class oldcls, Class newcls)
1452 rwlock_assert_writing(&runtimeLock);
1455 _objc_inform("FUTURE: using %p instead of %p for %s",
1456 (void*)oldcls, (void*)newcls, oldcls->nameForLogging());
1460 old = NXMapInsert(remappedClasses(YES), oldcls, newcls);
1465 /***********************************************************************
1467 * Returns the live class pointer for cls, which may be pointing to
1468 * a class struct that has been reallocated.
1469 * Returns nil if cls is ignored because of weak linking.
1470 * Locking: runtimeLock must be read- or write-locked by the caller
1471 **********************************************************************/
1472 static Class remapClass(Class cls)
1474 rwlock_assert_locked(&runtimeLock);
1478 if (!cls) return nil;
1480 if (NXMapMember(remappedClasses(YES), cls, (void**)&c2) == NX_MAPNOTAKEY) {
1487 static Class remapClass(classref_t cls)
1489 return remapClass((Class)cls);
1492 Class _class_remap(Class cls)
1494 rwlock_read(&runtimeLock);
1495 Class result = remapClass(cls);
1496 rwlock_unlock_read(&runtimeLock);
1500 /***********************************************************************
1502 * Fix up a class ref, in case the class referenced has been reallocated
1503 * or is an ignored weak-linked class.
1504 * Locking: runtimeLock must be read- or write-locked by the caller
1505 **********************************************************************/
1506 static void remapClassRef(Class *clsref)
1508 rwlock_assert_locked(&runtimeLock);
1510 Class newcls = remapClass(*clsref);
1511 if (*clsref != newcls) *clsref = newcls;
1515 /***********************************************************************
1517 * Return the ordinary class for this class or metaclass.
1518 * `inst` is an instance of `cls` or a subclass thereof, or nil.
1519 * Non-nil inst is faster.
1520 * Used by +initialize.
1521 * Locking: runtimeLock must be read- or write-locked by the caller
1522 **********************************************************************/
1523 static Class getNonMetaClass(Class metacls, id inst)
1525 static int total, named, secondary, sharedcache;
1526 rwlock_assert_locked(&runtimeLock);
1528 realizeClass(metacls);
1532 // return cls itself if it's already a non-meta class
1533 if (!metacls->isMetaClass()) return metacls;
1535 // metacls really is a metaclass
1537 // special case for root metaclass
1538 // where inst == inst->ISA() == metacls is possible
1539 if (metacls->ISA() == metacls) {
1540 Class cls = metacls->superclass;
1541 assert(cls->isRealized());
1542 assert(!cls->isMetaClass());
1543 assert(cls->ISA() == metacls);
1544 if (cls->ISA() == metacls) return cls;
1547 // use inst if available
1549 Class cls = (Class)inst;
1551 // cls may be a subclass - find the real class for metacls
1552 while (cls && cls->ISA() != metacls) {
1553 cls = cls->superclass;
1557 assert(!cls->isMetaClass());
1558 assert(cls->ISA() == metacls);
1562 _objc_fatal("cls is not an instance of metacls");
1564 // release build: be forgiving and fall through to slow lookups
1570 Class cls = getClass(metacls->mangledName());
1571 if (cls->ISA() == metacls) {
1573 if (PrintInitializing) {
1574 _objc_inform("INITIALIZE: %d/%d (%g%%) "
1575 "successful by-name metaclass lookups",
1576 named, total, named*100.0/total);
1584 // try secondary table
1586 Class cls = (Class)NXMapGet(nonMetaClasses(), metacls);
1589 if (PrintInitializing) {
1590 _objc_inform("INITIALIZE: %d/%d (%g%%) "
1591 "successful secondary metaclass lookups",
1592 secondary, total, secondary*100.0/total);
1595 assert(cls->ISA() == metacls);
1601 // try any duplicates in the dyld shared cache
1606 Class *classes = copyPreoptimizedClasses(metacls->mangledName(),&count);
1608 for (int i = 0; i < count; i++) {
1609 if (classes[i]->ISA() == metacls) {
1619 if (PrintInitializing) {
1620 _objc_inform("INITIALIZE: %d/%d (%g%%) "
1621 "successful shared cache metaclass lookups",
1622 sharedcache, total, sharedcache*100.0/total);
1630 _objc_fatal("no class for metaclass %p", (void*)metacls);
1634 /***********************************************************************
1635 * _class_getNonMetaClass
1636 * Return the ordinary class for this class or metaclass.
1637 * Used by +initialize.
1638 * Locking: acquires runtimeLock
1639 **********************************************************************/
1640 Class _class_getNonMetaClass(Class cls, id obj)
1642 rwlock_write(&runtimeLock);
1643 cls = getNonMetaClass(cls, obj);
1644 assert(cls->isRealized());
1645 rwlock_unlock_write(&runtimeLock);
1651 /***********************************************************************
1653 * Adds subcls as a subclass of supercls.
1654 * Locking: runtimeLock must be held by the caller.
1655 **********************************************************************/
1656 static void addSubclass(Class supercls, Class subcls)
1658 rwlock_assert_writing(&runtimeLock);
1660 if (supercls && subcls) {
1661 assert(supercls->isRealized());
1662 assert(subcls->isRealized());
1663 subcls->data()->nextSiblingClass = supercls->data()->firstSubclass;
1664 supercls->data()->firstSubclass = subcls;
1666 if (supercls->hasCxxCtor()) {
1667 subcls->setHasCxxCtor();
1670 if (supercls->hasCxxDtor()) {
1671 subcls->setHasCxxDtor();
1674 if (supercls->hasCustomRR()) {
1675 subcls->setHasCustomRR(true);
1678 if (supercls->hasCustomAWZ()) {
1679 subcls->setHasCustomAWZ(true);
1682 if (supercls->requiresRawIsa()) {
1683 subcls->setRequiresRawIsa(true);
1689 /***********************************************************************
1691 * Removes subcls as a subclass of supercls.
1692 * Locking: runtimeLock must be held by the caller.
1693 **********************************************************************/
1694 static void removeSubclass(Class supercls, Class subcls)
1696 rwlock_assert_writing(&runtimeLock);
1697 assert(supercls->isRealized());
1698 assert(subcls->isRealized());
1699 assert(subcls->superclass == supercls);
1702 for (cp = &supercls->data()->firstSubclass;
1703 *cp && *cp != subcls;
1704 cp = &(*cp)->data()->nextSiblingClass)
1706 assert(*cp == subcls);
1707 *cp = subcls->data()->nextSiblingClass;
1712 /***********************************************************************
1714 * Returns the protocol name => protocol map for protocols.
1715 * Locking: runtimeLock must read- or write-locked by the caller
1716 **********************************************************************/
1717 static NXMapTable *protocols(void)
1719 static NXMapTable *protocol_map = nil;
1721 rwlock_assert_locked(&runtimeLock);
1723 INIT_ONCE_PTR(protocol_map,
1724 NXCreateMapTableFromZone(NXStrValueMapPrototype, 16,
1725 _objc_internal_zone()),
1726 NXFreeMapTable(v) );
1728 return protocol_map;
1732 /***********************************************************************
1734 * Looks up a protocol by name. Demangled Swift names are recognized.
1735 * Locking: runtimeLock must be read- or write-locked by the caller.
1736 **********************************************************************/
1737 static Protocol *getProtocol_impl(const char *name)
1739 rwlock_assert_locked(&runtimeLock);
1741 return (Protocol *)NXMapGet(protocols(), name);
1744 static Protocol *getProtocol(const char *name)
1746 rwlock_assert_locked(&runtimeLock);
1749 Protocol *result = getProtocol_impl(name);
1750 if (result) return result;
1752 // Try Swift-mangled equivalent of the given name.
1753 if (char *swName = copySwiftV1MangledName(name, true/*isProtocol*/)) {
1754 result = getProtocol_impl(swName);
1763 /***********************************************************************
1765 * Returns the live protocol pointer for proto, which may be pointing to
1766 * a protocol struct that has been reallocated.
1767 * Locking: runtimeLock must be read- or write-locked by the caller
1768 **********************************************************************/
1769 static protocol_t *remapProtocol(protocol_ref_t proto)
1771 rwlock_assert_locked(&runtimeLock);
1773 protocol_t *newproto = (protocol_t *)
1774 getProtocol(((protocol_t *)proto)->mangledName);
1775 return newproto ? newproto : (protocol_t *)proto;
1779 /***********************************************************************
1781 * Fix up a protocol ref, in case the protocol referenced has been reallocated.
1782 * Locking: runtimeLock must be read- or write-locked by the caller
1783 **********************************************************************/
1784 static void remapProtocolRef(protocol_t **protoref)
1786 rwlock_assert_locked(&runtimeLock);
1788 protocol_t *newproto = remapProtocol((protocol_ref_t)*protoref);
1789 if (*protoref != newproto) *protoref = newproto;
1793 /***********************************************************************
1795 * Slides a class's ivars to accommodate the given superclass size.
1796 * Also slides ivar and weak GC layouts if provided.
1797 * Ivars are NOT compacted to compensate for a superclass that shrunk.
1798 * Locking: runtimeLock must be held by the caller.
1799 **********************************************************************/
1800 static void moveIvars(class_ro_t *ro, uint32_t superSize,
1801 layout_bitmap *ivarBitmap, layout_bitmap *weakBitmap)
1803 rwlock_assert_writing(&runtimeLock);
1808 assert(superSize > ro->instanceStart);
1809 diff = superSize - ro->instanceStart;
1812 // Find maximum alignment in this class's ivars
1813 uint32_t maxAlignment = 1;
1814 for (i = 0; i < ro->ivars->count; i++) {
1815 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
1816 if (!ivar->offset) continue; // anonymous bitfield
1818 uint32_t alignment = ivar->alignment();
1819 if (alignment > maxAlignment) maxAlignment = alignment;
1822 // Compute a slide value that preserves that alignment
1823 uint32_t alignMask = maxAlignment - 1;
1824 if (diff & alignMask) diff = (diff + alignMask) & ~alignMask;
1826 // Slide all of this class's ivars en masse
1827 for (i = 0; i < ro->ivars->count; i++) {
1828 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
1829 if (!ivar->offset) continue; // anonymous bitfield
1831 uint32_t oldOffset = (uint32_t)*ivar->offset;
1832 uint32_t newOffset = oldOffset + diff;
1833 *ivar->offset = newOffset;
1836 _objc_inform("IVARS: offset %u -> %u for %s (size %u, align %u)",
1837 oldOffset, newOffset, ivar->name,
1838 ivar->size, ivar->alignment());
1843 uint32_t oldOffset = ro->instanceStart;
1844 uint32_t newOffset = ro->instanceStart + diff;
1847 layout_bitmap_slide(ivarBitmap,
1848 oldOffset >> WORD_SHIFT,
1849 newOffset >> WORD_SHIFT);
1852 layout_bitmap_slide(weakBitmap,
1853 oldOffset >> WORD_SHIFT,
1854 newOffset >> WORD_SHIFT);
1858 *(uint32_t *)&ro->instanceStart += diff;
1859 *(uint32_t *)&ro->instanceSize += diff;
1862 // No ivars slid, but superclass changed size.
1863 // Expand bitmap in preparation for layout_bitmap_splat().
1864 if (ivarBitmap) layout_bitmap_grow(ivarBitmap, ro->instanceSize >> WORD_SHIFT);
1865 if (weakBitmap) layout_bitmap_grow(weakBitmap, ro->instanceSize >> WORD_SHIFT);
1870 /***********************************************************************
1872 * Look up an ivar by name.
1873 * Locking: runtimeLock must be read- or write-locked by the caller.
1874 **********************************************************************/
1875 static ivar_t *getIvar(Class cls, const char *name)
1877 rwlock_assert_locked(&runtimeLock);
1879 const ivar_list_t *ivars;
1880 assert(cls->isRealized());
1881 if ((ivars = cls->data()->ro->ivars)) {
1883 for (i = 0; i < ivars->count; i++) {
1884 ivar_t *ivar = ivar_list_nth(ivars, i);
1885 if (!ivar->offset) continue; // anonymous bitfield
1887 // ivar->name may be nil for anonymous bitfields etc.
1888 if (ivar->name && 0 == strcmp(name, ivar->name)) {
1898 static void reconcileInstanceVariables(Class cls, Class supercls, const class_ro_t*& ro)
1900 class_rw_t *rw = cls->data();
1903 assert(!cls->isMetaClass());
1905 /* debug: print them all before sliding
1908 for (i = 0; i < ro->ivars->count; i++) {
1909 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
1910 if (!ivar->offset) continue; // anonymous bitfield
1912 _objc_inform("IVARS: %s.%s (offset %u, size %u, align %u)",
1913 ro->name, ivar->name,
1914 *ivar->offset, ivar->size, ivar->alignment());
1919 // Non-fragile ivars - reconcile this class with its superclass
1920 layout_bitmap ivarBitmap;
1921 layout_bitmap weakBitmap;
1922 bool layoutsChanged = NO;
1923 bool mergeLayouts = UseGC;
1924 const class_ro_t *super_ro = supercls->data()->ro;
1926 if (DebugNonFragileIvars) {
1927 // Debugging: Force non-fragile ivars to slide.
1928 // Intended to find compiler, runtime, and program bugs.
1929 // If it fails with this and works without, you have a problem.
1931 // Operation: Reset everything to 0 + misalignment.
1932 // Then force the normal sliding logic to push everything back.
1934 // Exceptions: root classes, metaclasses, *NSCF* classes,
1935 // __CF* classes, NSConstantString, NSSimpleCString
1937 // (already know it's not root because supercls != nil)
1938 const char *clsname = cls->mangledName();
1939 if (!strstr(clsname, "NSCF") &&
1940 0 != strncmp(clsname, "__CF", 4) &&
1941 0 != strcmp(clsname, "NSConstantString") &&
1942 0 != strcmp(clsname, "NSSimpleCString"))
1944 uint32_t oldStart = ro->instanceStart;
1945 uint32_t oldSize = ro->instanceSize;
1946 class_ro_t *ro_w = make_ro_writeable(rw);
1949 // Find max ivar alignment in class.
1950 // default to word size to simplify ivar update
1951 uint32_t alignment = 1<<WORD_SHIFT;
1954 for (i = 0; i < ro->ivars->count; i++) {
1955 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
1956 if (ivar->alignment() > alignment) {
1957 alignment = ivar->alignment();
1961 uint32_t misalignment = ro->instanceStart % alignment;
1962 uint32_t delta = ro->instanceStart - misalignment;
1963 ro_w->instanceStart = misalignment;
1964 ro_w->instanceSize -= delta;
1967 _objc_inform("IVARS: DEBUG: forcing ivars for class '%s' "
1968 "to slide (instanceStart %zu -> %zu)",
1969 cls->nameForLogging(), (size_t)oldStart,
1970 (size_t)ro->instanceStart);
1975 for (i = 0; i < ro->ivars->count; i++) {
1976 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
1977 if (!ivar->offset) continue; // anonymous bitfield
1978 *ivar->offset -= delta;
1983 layout_bitmap layout;
1984 if (ro->ivarLayout) {
1985 layout = layout_bitmap_create(ro->ivarLayout,
1986 oldSize, oldSize, NO);
1987 layout_bitmap_slide_anywhere(&layout,
1988 delta >> WORD_SHIFT, 0);
1989 ro_w->ivarLayout = layout_string_create(layout);
1990 layout_bitmap_free(layout);
1992 if (ro->weakIvarLayout) {
1993 layout = layout_bitmap_create(ro->weakIvarLayout,
1994 oldSize, oldSize, YES);
1995 layout_bitmap_slide_anywhere(&layout,
1996 delta >> WORD_SHIFT, 0);
1997 ro_w->weakIvarLayout = layout_string_create(layout);
1998 layout_bitmap_free(layout);
2004 if (ro->instanceStart >= super_ro->instanceSize && !mergeLayouts) {
2005 // Superclass has not overgrown its space, and we don't
2006 // need to rebuild GC layouts. We're done here.
2009 // fixme can optimize for "class has no new ivars", etc
2012 // WARNING: gcc c++ sets instanceStart/Size=0 for classes with
2013 // no local ivars, but does provide a layout bitmap.
2014 // Handle that case specially so layout_bitmap_create doesn't die
2015 // The other ivar sliding code below still works fine, and
2016 // the final result is a good class.
2017 if (ro->instanceStart == 0 && ro->instanceSize == 0) {
2018 // We can't use ro->ivarLayout because we don't know
2019 // how long it is. Force a new layout to be created.
2021 _objc_inform("IVARS: instanceStart/Size==0 for class %s; "
2022 "disregarding ivar layout", cls->nameForLogging());
2024 ivarBitmap = layout_bitmap_create_empty(super_ro->instanceSize, NO);
2025 weakBitmap = layout_bitmap_create_empty(super_ro->instanceSize, YES);
2026 layoutsChanged = YES;
2030 layout_bitmap_create(ro->ivarLayout,
2032 ro->instanceSize, NO);
2034 layout_bitmap_create(ro->weakIvarLayout,
2036 ro->instanceSize, YES);
2040 if (ro->instanceStart < super_ro->instanceSize) {
2041 // Superclass has changed size. This class's ivars must move.
2042 // Also slide layout bits in parallel.
2043 // This code is incapable of compacting the subclass to
2044 // compensate for a superclass that shrunk, so don't do that.
2046 _objc_inform("IVARS: sliding ivars for class %s "
2047 "(superclass was %u bytes, now %u)",
2048 cls->nameForLogging(), ro->instanceStart,
2049 super_ro->instanceSize);
2051 class_ro_t *ro_w = make_ro_writeable(rw);
2053 moveIvars(ro_w, super_ro->instanceSize,
2054 mergeLayouts ? &ivarBitmap : nil,
2055 mergeLayouts ? &weakBitmap : nil);
2056 gdb_objc_class_changed(cls, OBJC_CLASS_IVARS_CHANGED, ro->name);
2057 layoutsChanged = YES;
2061 // Check superclass's layout against this class's layout.
2062 // This needs to be done even if the superclass is not bigger.
2063 layout_bitmap superBitmap;
2065 superBitmap = layout_bitmap_create(super_ro->ivarLayout,
2066 super_ro->instanceSize,
2067 super_ro->instanceSize, NO);
2068 layoutsChanged |= layout_bitmap_splat(ivarBitmap, superBitmap,
2070 layout_bitmap_free(superBitmap);
2072 // check the superclass' weak layout.
2073 superBitmap = layout_bitmap_create(super_ro->weakIvarLayout,
2074 super_ro->instanceSize,
2075 super_ro->instanceSize, YES);
2076 layoutsChanged |= layout_bitmap_splat(weakBitmap, superBitmap,
2078 layout_bitmap_free(superBitmap);
2080 // Rebuild layout strings if necessary.
2081 if (layoutsChanged) {
2083 _objc_inform("IVARS: gc layout changed for class %s",
2084 cls->nameForLogging());
2086 class_ro_t *ro_w = make_ro_writeable(rw);
2088 if (DebugNonFragileIvars) {
2089 try_free(ro_w->ivarLayout);
2090 try_free(ro_w->weakIvarLayout);
2092 ro_w->ivarLayout = layout_string_create(ivarBitmap);
2093 ro_w->weakIvarLayout = layout_string_create(weakBitmap);
2096 layout_bitmap_free(ivarBitmap);
2097 layout_bitmap_free(weakBitmap);
2102 /***********************************************************************
2104 * Performs first-time initialization on class cls,
2105 * including allocating its read-write data.
2106 * Returns the real class structure for the class.
2107 * Locking: runtimeLock must be write-locked by the caller
2108 **********************************************************************/
2109 static Class realizeClass(Class cls)
2111 rwlock_assert_writing(&runtimeLock);
2113 const class_ro_t *ro;
2119 if (!cls) return nil;
2120 if (cls->isRealized()) return cls;
2121 assert(cls == remapClass(cls));
2123 // fixme verify class is not in an un-dlopened part of the shared cache?
2125 ro = (const class_ro_t *)cls->data();
2126 if (ro->flags & RO_FUTURE) {
2127 // This was a future class. rw data is already allocated.
2129 ro = cls->data()->ro;
2130 cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
2132 // Normal class. Allocate writeable class data.
2133 rw = (class_rw_t *)_calloc_internal(sizeof(class_rw_t), 1);
2135 rw->flags = RW_REALIZED|RW_REALIZING;
2139 isMeta = (ro->flags & RO_META) ? YES : NO;
2141 rw->version = isMeta ? 7 : 0; // old runtime went up to 6
2143 if (PrintConnecting) {
2144 _objc_inform("CLASS: realizing class '%s' %s %p %p",
2145 cls->nameForLogging(), isMeta ? "(meta)" : "",
2149 // Realize superclass and metaclass, if they aren't already.
2150 // This needs to be done after RW_REALIZED is set above, for root classes.
2151 supercls = realizeClass(remapClass(cls->superclass));
2152 metacls = realizeClass(remapClass(cls->ISA()));
2154 // Update superclass and metaclass in case of remapping
2155 cls->superclass = supercls;
2156 cls->initClassIsa(metacls);
2158 // Reconcile instance variable offsets / layout.
2159 // This may reallocate class_ro_t, updating our ro variable.
2160 if (supercls && !isMeta) reconcileInstanceVariables(cls, supercls, ro);
2162 // Set fastInstanceSize if it wasn't set already.
2163 cls->setInstanceSize(ro->instanceSize);
2165 // Copy some flags from ro to rw
2166 if (ro->flags & RO_HAS_CXX_STRUCTORS) {
2167 cls->setHasCxxDtor();
2168 if (! (ro->flags & RO_HAS_CXX_DTOR_ONLY)) {
2169 cls->setHasCxxCtor();
2173 // Disable non-pointer isa for some classes and/or platforms.
2174 #if SUPPORT_NONPOINTER_ISA
2176 bool disable = false;
2177 static bool hackedDispatch = false;
2179 if (DisableIndexedIsa) {
2180 // Non-pointer isa disabled by environment or GC or app SDK version
2183 else if (!hackedDispatch && !(ro->flags & RO_META) &&
2184 0 == strcmp(ro->name, "OS_object"))
2186 // hack for libdispatch et al - isa also acts as vtable pointer
2187 hackedDispatch = true;
2192 cls->setRequiresRawIsa(false/*inherited*/);
2197 // Connect this class to its superclass's subclass lists
2199 addSubclass(supercls, cls);
2202 // Attach categories
2203 methodizeClass(cls);
2206 addRealizedClass(cls);
2208 addRealizedMetaclass(cls);
2215 /***********************************************************************
2216 * missingWeakSuperclass
2217 * Return YES if some superclass of cls was weak-linked and is missing.
2218 **********************************************************************/
2220 missingWeakSuperclass(Class cls)
2222 assert(!cls->isRealized());
2224 if (!cls->superclass) {
2225 // superclass nil. This is normal for root classes only.
2226 return (!(cls->data()->flags & RO_ROOT));
2228 // superclass not nil. Check if a higher superclass is missing.
2229 Class supercls = remapClass(cls->superclass);
2230 assert(cls != cls->superclass);
2231 assert(cls != supercls);
2232 if (!supercls) return YES;
2233 if (supercls->isRealized()) return NO;
2234 return missingWeakSuperclass(supercls);
2239 /***********************************************************************
2240 * realizeAllClassesInImage
2241 * Non-lazily realizes all unrealized classes in the given image.
2242 * Locking: runtimeLock must be held by the caller.
2243 **********************************************************************/
2244 static void realizeAllClassesInImage(header_info *hi)
2246 rwlock_assert_writing(&runtimeLock);
2249 classref_t *classlist;
2251 if (hi->allClassesRealized) return;
2253 classlist = _getObjc2ClassList(hi, &count);
2255 for (i = 0; i < count; i++) {
2256 realizeClass(remapClass(classlist[i]));
2259 hi->allClassesRealized = YES;
2263 /***********************************************************************
2265 * Non-lazily realizes all unrealized classes in all known images.
2266 * Locking: runtimeLock must be held by the caller.
2267 **********************************************************************/
2268 static void realizeAllClasses(void)
2270 rwlock_assert_writing(&runtimeLock);
2273 for (hi = FirstHeader; hi; hi = hi->next) {
2274 realizeAllClassesInImage(hi);
2279 /***********************************************************************
2280 * _objc_allocateFutureClass
2281 * Allocate an unresolved future class for the given class name.
2282 * Returns any existing allocation if one was already made.
2283 * Assumes the named class doesn't exist yet.
2284 * Locking: acquires runtimeLock
2285 **********************************************************************/
2286 Class _objc_allocateFutureClass(const char *name)
2288 rwlock_write(&runtimeLock);
2291 NXMapTable *future_named_class_map = futureNamedClasses();
2293 if ((cls = (Class)NXMapGet(future_named_class_map, name))) {
2294 // Already have a future class for this name.
2295 rwlock_unlock_write(&runtimeLock);
2299 cls = _calloc_class(sizeof(objc_class));
2300 addFutureNamedClass(name, cls);
2302 rwlock_unlock_write(&runtimeLock);
2307 /***********************************************************************
2308 * objc_getFutureClass. Return the id of the named class.
2309 * If the class does not exist, return an uninitialized class
2310 * structure that will be used for the class when and if it
2313 **********************************************************************/
2314 Class objc_getFutureClass(const char *name)
2318 // YES unconnected, NO class handler
2319 // (unconnected is OK because it will someday be the real class)
2320 cls = look_up_class(name, YES, NO);
2323 _objc_inform("FUTURE: found %p already in use for %s",
2330 // No class or future class with that name yet. Make one.
2331 // fixme not thread-safe with respect to
2332 // simultaneous library load or getFutureClass.
2333 return _objc_allocateFutureClass(name);
2337 /***********************************************************************
2339 **********************************************************************/
2340 void objc_setFutureClass(Class cls, const char *name)
2342 // fixme hack do nothing - NSCFString handled specially elsewhere
2346 BOOL _class_isFutureClass(Class cls)
2348 return cls && cls->isFuture();
2352 /***********************************************************************
2353 * _objc_flush_caches
2354 * Flushes all caches.
2355 * (Historical behavior: flush caches for cls, its metaclass,
2356 * and subclasses thereof. Nil flushes all classes.)
2357 * Locking: acquires runtimeLock
2358 **********************************************************************/
2359 static void flushCaches(Class cls)
2361 rwlock_assert_writing(&runtimeLock);
2363 mutex_lock(&cacheUpdateLock);
2366 foreach_realized_class_and_subclass(cls, ^(Class c){
2367 cache_erase_nolock(&c->cache);
2370 if (!cls->superclass) {
2371 // root; metaclasses are subclasses and were flushed above
2373 foreach_realized_class_and_subclass(cls->ISA(), ^(Class c){
2374 cache_erase_nolock(&c->cache);
2380 NXHashTable *classes = realizedClasses();
2381 NXHashState state = NXInitHashState(classes);
2382 while (NXNextHashState(classes, &state, (void **)&c)) {
2383 cache_erase_nolock(&c->cache);
2385 classes = realizedMetaclasses();
2386 state = NXInitHashState(classes);
2387 while (NXNextHashState(classes, &state, (void **)&c)) {
2388 cache_erase_nolock(&c->cache);
2392 mutex_unlock(&cacheUpdateLock);
2396 static void flushImps(Class cls, SEL sel1, IMP imp1, SEL sel2, IMP imp2)
2398 rwlock_assert_writing(&runtimeLock);
2400 mutex_lock(&cacheUpdateLock);
2403 foreach_realized_class_and_subclass(cls, ^(Class c){
2404 cache_eraseImp_nolock(c, sel1, imp1);
2405 if (sel2) cache_eraseImp_nolock(c, sel2, imp2);
2408 if (!cls->superclass) {
2409 // root; metaclasses are subclasses and were flushed above
2411 foreach_realized_class_and_subclass(cls->ISA(), ^(Class c){
2412 cache_eraseImp_nolock(c, sel1, imp1);
2413 if (sel2) cache_eraseImp_nolock(c, sel2, imp2);
2419 NXHashTable *classes = realizedClasses();
2420 NXHashState state = NXInitHashState(classes);
2421 while (NXNextHashState(classes, &state, (void **)&c)) {
2422 cache_eraseImp_nolock(c, sel1, imp1);
2423 if (sel2) cache_eraseImp_nolock(c, sel2, imp2);
2425 classes = realizedMetaclasses();
2426 state = NXInitHashState(classes);
2427 while (NXNextHashState(classes, &state, (void **)&c)) {
2428 cache_eraseImp_nolock(c, sel1, imp1);
2429 if (sel2) cache_eraseImp_nolock(c, sel2, imp2);
2433 mutex_unlock(&cacheUpdateLock);
2437 void _objc_flush_caches(Class cls)
2439 rwlock_write(&runtimeLock);
2441 rwlock_unlock_write(&runtimeLock);
2444 // collectALot if cls==nil
2445 mutex_lock(&cacheUpdateLock);
2446 cache_collect(true);
2447 mutex_unlock(&cacheUpdateLock);
2452 /***********************************************************************
2454 * Process the given images which are being mapped in by dyld.
2455 * Calls ABI-agnostic code after taking ABI-specific locks.
2457 * Locking: write-locks runtimeLock
2458 **********************************************************************/
2460 map_images(enum dyld_image_states state, uint32_t infoCount,
2461 const struct dyld_image_info infoList[])
2465 rwlock_write(&runtimeLock);
2466 err = map_images_nolock(state, infoCount, infoList);
2467 rwlock_unlock_write(&runtimeLock);
2472 /***********************************************************************
2474 * Process +load in the given images which are being mapped in by dyld.
2475 * Calls ABI-agnostic code after taking ABI-specific locks.
2477 * Locking: write-locks runtimeLock and loadMethodLock
2478 **********************************************************************/
2480 load_images(enum dyld_image_states state, uint32_t infoCount,
2481 const struct dyld_image_info infoList[])
2485 recursive_mutex_lock(&loadMethodLock);
2487 // Discover load methods
2488 rwlock_write(&runtimeLock);
2489 found = load_images_nolock(state, infoCount, infoList);
2490 rwlock_unlock_write(&runtimeLock);
2492 // Call +load methods (without runtimeLock - re-entrant)
2494 call_load_methods();
2497 recursive_mutex_unlock(&loadMethodLock);
2503 /***********************************************************************
2505 * Process the given image which is about to be unmapped by dyld.
2506 * mh is mach_header instead of headerType because that's what
2507 * dyld_priv.h says even for 64-bit.
2509 * Locking: write-locks runtimeLock and loadMethodLock
2510 **********************************************************************/
2512 unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide)
2514 recursive_mutex_lock(&loadMethodLock);
2515 rwlock_write(&runtimeLock);
2517 unmap_image_nolock(mh);
2519 rwlock_unlock_write(&runtimeLock);
2520 recursive_mutex_unlock(&loadMethodLock);
2526 /***********************************************************************
2528 * Read a class and metaclass as written by a compiler.
2529 * Returns the new class pointer. This could be:
2531 * - nil (cls has a missing weak-linked superclass)
2532 * - something else (space for this class was reserved by a future class)
2534 * Locking: runtimeLock acquired by map_images or objc_readClassPair
2535 **********************************************************************/
2536 static unsigned int PreoptTotalMethodLists;
2537 static unsigned int PreoptOptimizedMethodLists;
2538 static unsigned int PreoptTotalClasses;
2539 static unsigned int PreoptOptimizedClasses;
2541 Class readClass(Class cls, bool headerIsBundle, bool headerInSharedCache)
2543 const char *mangledName = cls->mangledName();
2545 if (missingWeakSuperclass(cls)) {
2546 // No superclass (probably weak-linked).
2547 // Disavow any knowledge of this subclass.
2548 if (PrintConnecting) {
2549 _objc_inform("CLASS: IGNORING class '%s' with "
2550 "missing weak-linked superclass",
2551 cls->nameForLogging());
2553 addRemappedClass(cls, nil);
2554 cls->superclass = nil;
2558 // Note: Class __ARCLite__'s hack does not go through here.
2559 // Class structure fixups that apply to it also need to be
2560 // performed in non-lazy realization below.
2562 // These fields should be set to zero because of the
2563 // binding of _objc_empty_vtable, but OS X 10.8's dyld
2564 // does not bind shared cache absolute symbols as expected.
2565 // This (and the __ARCLite__ hack below) can be removed
2566 // once the simulator drops 10.8 support.
2567 #if TARGET_IPHONE_SIMULATOR
2568 if (cls->cache._mask) cls->cache._mask = 0;
2569 if (cls->cache._occupied) cls->cache._occupied = 0;
2570 if (cls->ISA()->cache._mask) cls->ISA()->cache._mask = 0;
2571 if (cls->ISA()->cache._occupied) cls->ISA()->cache._occupied = 0;
2574 NXMapTable *future_named_class_map = futureNamedClasses();
2576 if (NXCountMapTable(future_named_class_map) > 0) {
2578 newCls = (Class)NXMapGet(future_named_class_map, mangledName);
2579 removeFutureNamedClass(mangledName);
2582 // Copy objc_class to future class's struct.
2583 // Preserve future's rw data block.
2585 if (newCls->isSwift()) {
2586 _objc_fatal("Can't complete future class request for '%s' "
2587 "because the real class is too big.",
2588 cls->nameForLogging());
2591 class_rw_t *rw = newCls->data();
2592 const class_ro_t *old_ro = rw->ro;
2593 memcpy(newCls, cls, sizeof(objc_class));
2594 rw->ro = (class_ro_t *)newCls->data();
2595 newCls->setData(rw);
2596 _free_internal((void *)old_ro->name);
2597 _free_internal((void *)old_ro);
2599 addRemappedClass(cls, newCls);
2605 PreoptTotalClasses++;
2606 if (headerInSharedCache && isPreoptimized()) {
2607 // class list built in shared cache
2608 // fixme strict assert doesn't work because of duplicates
2609 // assert(cls == getClass(name));
2610 assert(getClass(mangledName));
2611 PreoptOptimizedClasses++;
2613 addNamedClass(cls, mangledName);
2616 // for future reference: shared cache never contains MH_BUNDLEs
2617 if (headerIsBundle) {
2618 cls->data()->flags |= RO_FROM_BUNDLE;
2619 cls->ISA()->data()->flags |= RO_FROM_BUNDLE;
2623 const method_list_t *mlist;
2624 if ((mlist = ((class_ro_t *)cls->data())->baseMethods)) {
2625 PreoptTotalMethodLists++;
2626 if (isMethodListFixedUp(mlist)) PreoptOptimizedMethodLists++;
2628 if ((mlist = ((class_ro_t *)cls->ISA()->data())->baseMethods)) {
2629 PreoptTotalMethodLists++;
2630 if (isMethodListFixedUp(mlist)) PreoptOptimizedMethodLists++;
2638 /***********************************************************************
2640 * Perform initial processing of the headers in the linked
2641 * list beginning with headerList.
2643 * Called by: map_images_nolock
2645 * Locking: runtimeLock acquired by map_images
2646 **********************************************************************/
2647 void _read_images(header_info **hList, uint32_t hCount)
2653 Class *resolvedFutureClasses = nil;
2654 size_t resolvedFutureClassCount = 0;
2655 static BOOL doneOnce;
2657 rwlock_assert_writing(&runtimeLock);
2659 #define EACH_HEADER \
2661 crashlog_header_name(nil) && hIndex < hCount && (hi = hList[hIndex]) && crashlog_header_name(hi); \
2667 #if SUPPORT_NONPOINTER_ISA
2669 # if TARGET_OS_MAC && !TARGET_OS_IPHONE
2670 // Disable non-pointer isa if the app is too old.
2671 if (AppSDKVersion < INSERT VERSION HERE) {
2672 DisableIndexedIsa = true;
2674 _objc_inform("RAW ISA: disabling non-pointer isa because "
2675 "the app is too old (SDK version %hu.%hhu.%hhu)",
2676 (unsigned short)(AppSDKVersion>>16),
2677 (unsigned char)(AppSDKVersion>>8),
2678 (unsigned char)(AppSDKVersion));
2683 // Disable non-pointer isa for all GC apps.
2685 DisableIndexedIsa = true;
2687 _objc_inform("RAW ISA: disabling non-pointer isa because "
2694 if (DisableTaggedPointers) {
2695 disableTaggedPointers();
2698 // Count classes. Size various table based on the total.
2700 int unoptimizedTotal = 0;
2702 if (_getObjc2ClassList(hi, &count)) {
2703 total += (int)count;
2704 if (!hi->inSharedCache) unoptimizedTotal += count;
2708 if (PrintConnecting) {
2709 _objc_inform("CLASS: found %d classes during launch", total);
2712 // namedClasses (NOT realizedClasses)
2713 // Preoptimized classes don't go in this table.
2714 // 4/3 is NXMapTable's load factor
2715 int namedClassesSize =
2716 (isPreoptimized() ? unoptimizedTotal : total) * 4 / 3;
2717 gdb_objc_realized_classes =
2718 NXCreateMapTableFromZone(NXStrValueMapPrototype, namedClassesSize,
2719 _objc_internal_zone());
2721 // realizedClasses and realizedMetaclasses - less than the full total
2722 realized_class_hash =
2723 NXCreateHashTableFromZone(NXPtrPrototype, total / 8, nil,
2724 _objc_internal_zone());
2725 realized_metaclass_hash =
2726 NXCreateHashTableFromZone(NXPtrPrototype, total / 8, nil,
2727 _objc_internal_zone());
2731 // Discover classes. Fix up unresolved future classes. Mark bundle classes.
2734 bool headerIsBundle = (hi->mhdr->filetype == MH_BUNDLE);
2735 bool headerInSharedCache = hi->inSharedCache;
2737 classref_t *classlist = _getObjc2ClassList(hi, &count);
2738 for (i = 0; i < count; i++) {
2739 Class cls = (Class)classlist[i];
2740 Class newCls = readClass(cls, headerIsBundle, headerInSharedCache);
2742 if (newCls != cls && newCls) {
2743 // Class was moved but not deleted. Currently this occurs
2744 // only when the new class resolved a future class.
2745 // Non-lazily realize the class below.
2746 resolvedFutureClasses = (Class *)
2747 _realloc_internal(resolvedFutureClasses,
2748 (resolvedFutureClassCount+1)
2750 resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
2755 if (PrintPreopt && PreoptTotalMethodLists) {
2756 _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) method lists pre-sorted",
2757 PreoptOptimizedMethodLists, PreoptTotalMethodLists,
2758 100.0*PreoptOptimizedMethodLists/PreoptTotalMethodLists);
2760 if (PrintPreopt && PreoptTotalClasses) {
2761 _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) classes pre-registered",
2762 PreoptOptimizedClasses, PreoptTotalClasses,
2763 100.0*PreoptOptimizedClasses/PreoptTotalClasses);
2766 // Fix up remapped classes
2767 // Class list and nonlazy class list remain unremapped.
2768 // Class refs and super refs are remapped for message dispatching.
2770 if (!noClassesRemapped()) {
2772 Class *classrefs = _getObjc2ClassRefs(hi, &count);
2773 for (i = 0; i < count; i++) {
2774 remapClassRef(&classrefs[i]);
2776 // fixme why doesn't test future1 catch the absence of this?
2777 classrefs = _getObjc2SuperRefs(hi, &count);
2778 for (i = 0; i < count; i++) {
2779 remapClassRef(&classrefs[i]);
2785 // Fix up @selector references
2789 if (sel_preoptimizationValid(hi)) {
2790 _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors in %s",
2793 else if (_objcHeaderOptimizedByDyld(hi)) {
2794 _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors in %s",
2799 if (sel_preoptimizationValid(hi)) continue;
2801 bool isBundle = hi->mhdr->filetype == MH_BUNDLE;
2802 SEL *sels = _getObjc2SelectorRefs(hi, &count);
2803 for (i = 0; i < count; i++) {
2804 const char *name = sel_cname(sels[i]);
2805 sels[i] = sel_registerNameNoLock(name, isBundle);
2811 // Fix up old objc_msgSend_fixup call sites
2813 message_ref_t *refs = _getObjc2MessageRefs(hi, &count);
2814 if (count == 0) continue;
2817 _objc_inform("VTABLES: repairing %zu unsupported vtable dispatch "
2818 "call sites in %s", count, hi->fname);
2820 for (i = 0; i < count; i++) {
2821 fixupMessageRef(refs+i);
2826 // Discover protocols. Fix up protocol refs.
2828 extern objc_class OBJC_CLASS_$_Protocol;
2829 Class cls = (Class)&OBJC_CLASS_$_Protocol;
2831 protocol_t **protolist = _getObjc2ProtocolList(hi, &count);
2832 NXMapTable *protocol_map = protocols();
2833 // fixme duplicate protocols from unloadable bundle
2834 for (i = 0; i < count; i++) {
2835 protocol_t *oldproto = (protocol_t *)
2836 getProtocol(protolist[i]->mangledName);
2838 size_t size = max(sizeof(protocol_t),
2839 (size_t)protolist[i]->size);
2840 protocol_t *newproto = (protocol_t *)_calloc_internal(size, 1);
2841 memcpy(newproto, protolist[i], protolist[i]->size);
2842 newproto->size = (typeof(newproto->size))size;
2844 newproto->initIsa(cls); // fixme pinned
2845 NXMapKeyCopyingInsert(protocol_map,
2846 newproto->mangledName, newproto);
2847 if (PrintProtocols) {
2848 _objc_inform("PROTOCOLS: protocol at %p is %s",
2849 newproto, newproto->nameForLogging());
2852 if (PrintProtocols) {
2853 _objc_inform("PROTOCOLS: protocol at %p is %s (duplicate)",
2854 protolist[i], oldproto->nameForLogging());
2860 protocol_t **protolist;
2861 protolist = _getObjc2ProtocolRefs(hi, &count);
2862 for (i = 0; i < count; i++) {
2863 remapProtocolRef(&protolist[i]);
2867 // Realize non-lazy classes (for +load methods and static instances)
2869 classref_t *classlist =
2870 _getObjc2NonlazyClassList(hi, &count);
2871 for (i = 0; i < count; i++) {
2872 Class cls = remapClass(classlist[i]);
2875 // hack for class __ARCLite__, which didn't get this above
2876 #if TARGET_IPHONE_SIMULATOR
2877 if (cls->cache._buckets == (void*)&_objc_empty_cache &&
2878 (cls->cache._mask || cls->cache._occupied))
2880 cls->cache._mask = 0;
2881 cls->cache._occupied = 0;
2883 if (cls->ISA()->cache._buckets == (void*)&_objc_empty_cache &&
2884 (cls->ISA()->cache._mask || cls->ISA()->cache._occupied))
2886 cls->ISA()->cache._mask = 0;
2887 cls->ISA()->cache._occupied = 0;
2895 // Realize newly-resolved future classes, in case CF manipulates them
2896 if (resolvedFutureClasses) {
2897 for (i = 0; i < resolvedFutureClassCount; i++) {
2898 realizeClass(resolvedFutureClasses[i]);
2899 resolvedFutureClasses[i]->setRequiresRawIsa(false/*inherited*/);
2901 _free_internal(resolvedFutureClasses);
2904 // Discover categories.
2906 category_t **catlist =
2907 _getObjc2CategoryList(hi, &count);
2908 for (i = 0; i < count; i++) {
2909 category_t *cat = catlist[i];
2910 Class cls = remapClass(cat->cls);
2913 // Category's target class is missing (probably weak-linked).
2914 // Disavow any knowledge of this category.
2916 if (PrintConnecting) {
2917 _objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with "
2918 "missing weak-linked target class",
2924 // Process this category.
2925 // First, register the category with its target class.
2926 // Then, rebuild the class's method lists (etc) if
2927 // the class is realized.
2928 BOOL classExists = NO;
2929 if (cat->instanceMethods || cat->protocols
2930 || cat->instanceProperties)
2932 addUnattachedCategoryForClass(cat, cls, hi);
2933 if (cls->isRealized()) {
2934 remethodizeClass(cls);
2937 if (PrintConnecting) {
2938 _objc_inform("CLASS: found category -%s(%s) %s",
2939 cls->nameForLogging(), cat->name,
2940 classExists ? "on existing class" : "");
2944 if (cat->classMethods || cat->protocols
2945 /* || cat->classProperties */)
2947 addUnattachedCategoryForClass(cat, cls->ISA(), hi);
2948 if (cls->ISA()->isRealized()) {
2949 remethodizeClass(cls->ISA());
2951 if (PrintConnecting) {
2952 _objc_inform("CLASS: found category +%s(%s)",
2953 cls->nameForLogging(), cat->name);
2959 // Category discovery MUST BE LAST to avoid potential races
2960 // when other threads call the new category code before
2961 // this thread finishes its fixups.
2963 // +load handled by prepare_load_methods()
2965 if (DebugNonFragileIvars) {
2966 realizeAllClasses();
2973 /***********************************************************************
2974 * prepare_load_methods
2975 * Schedule +load for classes in this image, any un-+load-ed
2976 * superclasses in other images, and any categories in this image.
2977 **********************************************************************/
2978 // Recursively schedule +load for cls and any un-+load-ed superclasses.
2979 // cls must already be connected.
2980 static void schedule_class_load(Class cls)
2983 assert(cls->isRealized()); // _read_images should realize
2985 if (cls->data()->flags & RW_LOADED) return;
2987 // Ensure superclass-first ordering
2988 schedule_class_load(cls->superclass);
2990 add_class_to_loadable_list(cls);
2991 cls->setInfo(RW_LOADED);
2994 void prepare_load_methods(header_info *hi)
2998 rwlock_assert_writing(&runtimeLock);
3000 classref_t *classlist =
3001 _getObjc2NonlazyClassList(hi, &count);
3002 for (i = 0; i < count; i++) {
3003 schedule_class_load(remapClass(classlist[i]));
3006 category_t **categorylist = _getObjc2NonlazyCategoryList(hi, &count);
3007 for (i = 0; i < count; i++) {
3008 category_t *cat = categorylist[i];
3009 Class cls = remapClass(cat->cls);
3010 if (!cls) continue; // category for ignored weak-linked class
3012 assert(cls->ISA()->isRealized());
3013 add_category_to_loadable_list(cat);
3018 /***********************************************************************
3020 * Only handles MH_BUNDLE for now.
3021 * Locking: write-lock and loadMethodLock acquired by unmap_image
3022 **********************************************************************/
3023 void _unload_image(header_info *hi)
3027 recursive_mutex_assert_locked(&loadMethodLock);
3028 rwlock_assert_writing(&runtimeLock);
3030 // Unload unattached categories and categories waiting for +load.
3032 category_t **catlist = _getObjc2CategoryList(hi, &count);
3033 for (i = 0; i < count; i++) {
3034 category_t *cat = catlist[i];
3035 if (!cat) continue; // category for ignored weak-linked class
3036 Class cls = remapClass(cat->cls);
3037 assert(cls); // shouldn't have live category for dead class
3039 // fixme for MH_DYLIB cat's class may have been unloaded already
3042 removeUnattachedCategoryForClass(cat, cls);
3045 remove_category_from_loadable_list(cat);
3050 classref_t *classlist = _getObjc2ClassList(hi, &count);
3052 // First detach classes from each other. Then free each class.
3053 // This avoid bugs where this loop unloads a subclass before its superclass
3055 for (i = 0; i < count; i++) {
3056 Class cls = remapClass(classlist[i]);
3058 remove_class_from_loadable_list(cls);
3059 detach_class(cls->ISA(), YES);
3060 detach_class(cls, NO);
3064 for (i = 0; i < count; i++) {
3065 Class cls = remapClass(classlist[i]);
3067 free_class(cls->ISA());
3072 // XXX FIXME -- Clean up protocols:
3073 // <rdar://problem/9033191> Support unloading protocols at dylib/image unload time
3075 // fixme DebugUnload
3079 /***********************************************************************
3080 * method_getDescription
3081 * Returns a pointer to this method's objc_method_description.
3083 **********************************************************************/
3084 struct objc_method_description *
3085 method_getDescription(Method m)
3088 return (struct objc_method_description *)m;
3092 /***********************************************************************
3093 * method_getImplementation
3094 * Returns this method's IMP.
3096 **********************************************************************/
3098 _method_getImplementation(method_t *m)
3105 method_getImplementation(Method m)
3107 return _method_getImplementation(m);
3111 /***********************************************************************
3113 * Returns this method's selector.
3114 * The method must not be nil.
3115 * The method must already have been fixed-up.
3117 **********************************************************************/
3119 method_getName(Method m)
3123 assert(m->name == sel_registerName(sel_getName(m->name)));
3128 /***********************************************************************
3129 * method_getTypeEncoding
3130 * Returns this method's old-style type encoding string.
3131 * The method must not be nil.
3133 **********************************************************************/
3135 method_getTypeEncoding(Method m)
3142 /***********************************************************************
3143 * method_setImplementation
3144 * Sets this method's implementation to imp.
3145 * The previous implementation is returned.
3146 **********************************************************************/
3148 _method_setImplementation(Class cls, method_t *m, IMP imp)
3150 rwlock_assert_writing(&runtimeLock);
3153 if (!imp) return nil;
3155 if (ignoreSelector(m->name)) {
3156 // Ignored methods stay ignored
3160 IMP old = _method_getImplementation(m);
3163 // Class-side cache updates are slow if cls is nil (i.e. unknown)
3164 // RR/AWZ updates are slow if cls is nil (i.e. unknown)
3165 // fixme build list of classes whose Methods are known externally?
3167 // Scrub the old IMP from the cache.
3168 // Can't simply overwrite the new IMP because the cached value could be
3169 // the same IMP from a different Method.
3170 flushImps(cls, m->name, old, nil, nil);
3172 // Catch changes to retain/release and allocWithZone implementations
3173 updateCustomRR_AWZ(cls, m);
3179 method_setImplementation(Method m, IMP imp)
3181 // Don't know the class - will be slow if RR/AWZ are affected
3182 // fixme build list of classes whose Methods are known externally?
3184 rwlock_write(&runtimeLock);
3185 result = _method_setImplementation(Nil, m, imp);
3186 rwlock_unlock_write(&runtimeLock);
3191 void method_exchangeImplementations(Method m1, Method m2)
3193 if (!m1 || !m2) return;
3195 rwlock_write(&runtimeLock);
3197 if (ignoreSelector(m1->name) || ignoreSelector(m2->name)) {
3198 // Ignored methods stay ignored. Now they're both ignored.
3199 m1->imp = (IMP)&_objc_ignored_method;
3200 m2->imp = (IMP)&_objc_ignored_method;
3201 rwlock_unlock_write(&runtimeLock);
3205 IMP m1_imp = m1->imp;
3210 // RR/AWZ updates are slow because class is unknown
3211 // Class-side cache updates are slow because class is unknown
3212 // fixme build list of classes whose Methods are known externally?
3214 // Scrub the old IMPs from the caches.
3215 // Can't simply overwrite the new IMP because the cached value could be
3216 // the same IMP from a different Method.
3217 flushImps(nil, m1->name,m2->imp, m2->name,m1->imp);
3219 updateCustomRR_AWZ(nil, m1);
3220 updateCustomRR_AWZ(nil, m2);
3222 rwlock_unlock_write(&runtimeLock);
3226 /***********************************************************************
3230 **********************************************************************/
3232 ivar_getOffset(Ivar ivar)
3234 if (!ivar) return 0;
3235 return *ivar->offset;
3239 /***********************************************************************
3243 **********************************************************************/
3245 ivar_getName(Ivar ivar)
3247 if (!ivar) return nil;
3252 /***********************************************************************
3253 * ivar_getTypeEncoding
3256 **********************************************************************/
3258 ivar_getTypeEncoding(Ivar ivar)
3260 if (!ivar) return nil;
3266 const char *property_getName(objc_property_t prop)
3271 const char *property_getAttributes(objc_property_t prop)
3273 return prop->attributes;
3276 objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
3277 unsigned int *outCount)
3280 if (outCount) *outCount = 0;
3284 objc_property_attribute_t *result;
3285 rwlock_read(&runtimeLock);
3286 result = copyPropertyAttributeList(prop->attributes,outCount);
3287 rwlock_unlock_read(&runtimeLock);
3291 char * property_copyAttributeValue(objc_property_t prop, const char *name)
3293 if (!prop || !name || *name == '\0') return nil;
3296 rwlock_read(&runtimeLock);
3297 result = copyPropertyAttributeValue(prop->attributes, name);
3298 rwlock_unlock_read(&runtimeLock);
3303 /***********************************************************************
3304 * getExtendedTypesIndexesForMethod
3306 * a is the count of methods in all method lists before m's method list
3307 * b is the index of m in m's method list
3308 * a+b is the index of m's extended types in the extended types array
3309 **********************************************************************/
3310 static void getExtendedTypesIndexesForMethod(protocol_t *proto, const method_t *m, bool isRequiredMethod, bool isInstanceMethod, uint32_t& a, uint32_t &b)
3314 if (isRequiredMethod && isInstanceMethod) {
3315 b = method_list_index(proto->instanceMethods, m);
3318 a += method_list_count(proto->instanceMethods);
3320 if (isRequiredMethod && !isInstanceMethod) {
3321 b = method_list_index(proto->classMethods, m);
3324 a += method_list_count(proto->classMethods);
3326 if (!isRequiredMethod && isInstanceMethod) {
3327 b = method_list_index(proto->optionalInstanceMethods, m);
3330 a += method_list_count(proto->optionalInstanceMethods);
3332 if (!isRequiredMethod && !isInstanceMethod) {
3333 b = method_list_index(proto->optionalClassMethods, m);
3336 a += method_list_count(proto->optionalClassMethods);
3340 /***********************************************************************
3341 * getExtendedTypesIndexForMethod
3342 * Returns the index of m's extended types in proto's extended types array.
3343 **********************************************************************/
3344 static uint32_t getExtendedTypesIndexForMethod(protocol_t *proto, const method_t *m, bool isRequiredMethod, bool isInstanceMethod)
3348 getExtendedTypesIndexesForMethod(proto, m, isRequiredMethod,
3349 isInstanceMethod, a, b);
3354 /***********************************************************************
3355 * fixupProtocolMethodList
3356 * Fixes up a single method list in a protocol.
3357 **********************************************************************/
3359 fixupProtocolMethodList(protocol_t *proto, method_list_t **mlistp,
3360 bool required, bool instance)
3362 rwlock_assert_writing(&runtimeLock);
3364 if (!*mlistp) return;
3365 if (isMethodListFixedUp(*mlistp)) return;
3367 bool hasExtendedMethodTypes = proto->hasExtendedMethodTypes();
3368 *mlistp = fixupMethodList(*mlistp, true/*always copy for simplicity*/,
3369 !hasExtendedMethodTypes/*sort if no ext*/);
3371 method_list_t *mlist = *mlistp;
3373 if (hasExtendedMethodTypes) {
3374 // Sort method list and extended method types together.
3375 // fixupMethodList() can't do this.
3377 uint32_t count = method_list_count(mlist);
3380 getExtendedTypesIndexesForMethod(proto, method_list_nth(mlist, 0),
3381 required, instance, prefix, junk);
3382 const char **types = proto->extendedMethodTypes;
3383 for (uint32_t i = 0; i < count; i++) {
3384 for (uint32_t j = i+1; j < count; j++) {
3385 method_t *mi = method_list_nth(mlist, i);
3386 method_t *mj = method_list_nth(mlist, j);
3387 if (mi->name > mj->name) {
3388 method_list_swap(mlist, i, j);
3389 std::swap(types[prefix+i], types[prefix+j]);
3397 /***********************************************************************
3399 * Fixes up all of a protocol's method lists.
3400 **********************************************************************/
3402 fixupProtocol(protocol_t *proto)
3404 rwlock_assert_writing(&runtimeLock);
3406 if (proto->protocols) {
3407 for (uintptr_t i = 0; i < proto->protocols->count; i++) {
3408 protocol_t *sub = remapProtocol(proto->protocols->list[i]);
3409 if (!sub->isFixedUp()) fixupProtocol(sub);
3413 fixupProtocolMethodList(proto, &proto->instanceMethods, YES, YES);
3414 fixupProtocolMethodList(proto, &proto->classMethods, YES, NO);
3415 fixupProtocolMethodList(proto, &proto->optionalInstanceMethods, NO, YES);
3416 fixupProtocolMethodList(proto, &proto->optionalClassMethods, NO, NO);
3418 // fixme memory barrier so we can check this with no lock
3419 proto->flags |= PROTOCOL_FIXED_UP;
3423 /***********************************************************************
3424 * fixupProtocolIfNeeded
3425 * Fixes up all of a protocol's method lists if they aren't fixed up already.
3426 * Locking: write-locks runtimeLock.
3427 **********************************************************************/
3429 fixupProtocolIfNeeded(protocol_t *proto)
3431 rwlock_assert_unlocked(&runtimeLock);
3434 if (!proto->isFixedUp()) {
3435 rwlock_write(&runtimeLock);
3436 fixupProtocol(proto);
3437 rwlock_unlock_write(&runtimeLock);
3442 static method_list_t *
3443 getProtocolMethodList(protocol_t *proto, bool required, bool instance)
3445 method_list_t **mlistp = nil;
3448 mlistp = &proto->instanceMethods;
3450 mlistp = &proto->classMethods;
3454 mlistp = &proto->optionalInstanceMethods;
3456 mlistp = &proto->optionalClassMethods;
3464 /***********************************************************************
3465 * protocol_getMethod_nolock
3466 * Locking: runtimeLock must be held by the caller
3467 **********************************************************************/
3469 protocol_getMethod_nolock(protocol_t *proto, SEL sel,
3470 bool isRequiredMethod, bool isInstanceMethod,
3473 rwlock_assert_locked(&runtimeLock);
3475 if (!proto || !sel) return nil;
3477 assert(proto->isFixedUp());
3479 method_list_t *mlist =
3480 getProtocolMethodList(proto, isRequiredMethod, isInstanceMethod);
3482 method_t *m = search_method_list(mlist, sel);
3486 if (recursive && proto->protocols) {
3488 for (uint32_t i = 0; i < proto->protocols->count; i++) {
3489 protocol_t *realProto = remapProtocol(proto->protocols->list[i]);
3490 m = protocol_getMethod_nolock(realProto, sel,
3491 isRequiredMethod, isInstanceMethod,
3501 /***********************************************************************
3502 * protocol_getMethod
3504 * Locking: acquires runtimeLock
3505 **********************************************************************/
3507 protocol_getMethod(protocol_t *proto, SEL sel, bool isRequiredMethod, bool isInstanceMethod, bool recursive)
3509 if (!proto) return nil;
3510 fixupProtocolIfNeeded(proto);
3512 rwlock_read(&runtimeLock);
3513 method_t *result = protocol_getMethod_nolock(proto, sel,
3517 rwlock_unlock_read(&runtimeLock);
3522 /***********************************************************************
3523 * protocol_getMethodTypeEncoding_nolock
3524 * Return the @encode string for the requested protocol method.
3525 * Returns nil if the compiler did not emit any extended @encode data.
3526 * Locking: runtimeLock must be held for writing by the caller
3527 **********************************************************************/
3529 protocol_getMethodTypeEncoding_nolock(protocol_t *proto, SEL sel,
3530 bool isRequiredMethod,
3531 bool isInstanceMethod)
3533 rwlock_assert_locked(&runtimeLock);
3535 if (!proto) return nil;
3536 if (!proto->hasExtendedMethodTypes()) return nil;
3538 assert(proto->isFixedUp());
3541 protocol_getMethod_nolock(proto, sel,
3542 isRequiredMethod, isInstanceMethod, false);
3544 uint32_t i = getExtendedTypesIndexForMethod(proto, m,
3547 return proto->extendedMethodTypes[i];
3550 // No method with that name. Search incorporated protocols.
3551 if (proto->protocols) {
3552 for (uintptr_t i = 0; i < proto->protocols->count; i++) {
3554 protocol_getMethodTypeEncoding_nolock(remapProtocol(proto->protocols->list[i]), sel, isRequiredMethod, isInstanceMethod);
3555 if (enc) return enc;
3562 /***********************************************************************
3563 * _protocol_getMethodTypeEncoding
3564 * Return the @encode string for the requested protocol method.
3565 * Returns nil if the compiler did not emit any extended @encode data.
3566 * Locking: acquires runtimeLock
3567 **********************************************************************/
3569 _protocol_getMethodTypeEncoding(Protocol *proto_gen, SEL sel,
3570 BOOL isRequiredMethod, BOOL isInstanceMethod)
3572 protocol_t *proto = newprotocol(proto_gen);
3574 if (!proto) return nil;
3575 fixupProtocolIfNeeded(proto);
3578 rwlock_read(&runtimeLock);
3579 enc = protocol_getMethodTypeEncoding_nolock(proto, sel,
3582 rwlock_unlock_read(&runtimeLock);
3587 /***********************************************************************
3588 * protocol_t::demangledName
3589 * Returns the (Swift-demangled) name of the given protocol.
3591 **********************************************************************/
3593 protocol_t::demangledName()
3595 assert(size >= offsetof(protocol_t, _demangledName)+sizeof(_demangledName));
3597 if (! _demangledName) {
3598 char *de = copySwiftV1DemangledName(mangledName, true/*isProtocol*/);
3599 if (! OSAtomicCompareAndSwapPtrBarrier(nil, (void*)(de ?: mangledName),
3600 (void**)&_demangledName))
3605 return _demangledName;
3608 /***********************************************************************
3610 * Returns the (Swift-demangled) name of the given protocol.
3611 * Locking: runtimeLock must not be held by the caller
3612 **********************************************************************/
3614 protocol_getName(Protocol *proto)
3616 if (!proto) return "nil";
3617 else return newprotocol(proto)->demangledName();
3621 /***********************************************************************
3622 * protocol_getInstanceMethodDescription
3623 * Returns the description of a named instance method.
3624 * Locking: runtimeLock must not be held by the caller
3625 **********************************************************************/
3626 struct objc_method_description
3627 protocol_getMethodDescription(Protocol *p, SEL aSel,
3628 BOOL isRequiredMethod, BOOL isInstanceMethod)
3631 protocol_getMethod(newprotocol(p), aSel,
3632 isRequiredMethod, isInstanceMethod, true);
3633 if (m) return *method_getDescription(m);
3634 else return (struct objc_method_description){nil, nil};
3638 /***********************************************************************
3639 * protocol_conformsToProtocol_nolock
3640 * Returns YES if self conforms to other.
3641 * Locking: runtimeLock must be held by the caller.
3642 **********************************************************************/
3644 protocol_conformsToProtocol_nolock(protocol_t *self, protocol_t *other)
3646 rwlock_assert_locked(&runtimeLock);
3648 if (!self || !other) {
3652 // protocols need not be fixed up
3654 if (0 == strcmp(self->mangledName, other->mangledName)) {
3658 if (self->protocols) {
3660 for (i = 0; i < self->protocols->count; i++) {
3661 protocol_t *proto = remapProtocol(self->protocols->list[i]);
3662 if (0 == strcmp(other->mangledName, proto->mangledName)) {
3665 if (protocol_conformsToProtocol_nolock(proto, other)) {
3675 /***********************************************************************
3676 * protocol_conformsToProtocol
3677 * Returns YES if self conforms to other.
3678 * Locking: acquires runtimeLock
3679 **********************************************************************/
3680 BOOL protocol_conformsToProtocol(Protocol *self, Protocol *other)
3683 rwlock_read(&runtimeLock);
3684 result = protocol_conformsToProtocol_nolock(newprotocol(self),
3685 newprotocol(other));
3686 rwlock_unlock_read(&runtimeLock);
3691 /***********************************************************************
3693 * Return YES if two protocols are equal (i.e. conform to each other)
3694 * Locking: acquires runtimeLock
3695 **********************************************************************/
3696 BOOL protocol_isEqual(Protocol *self, Protocol *other)
3698 if (self == other) return YES;
3699 if (!self || !other) return NO;
3701 if (!protocol_conformsToProtocol(self, other)) return NO;
3702 if (!protocol_conformsToProtocol(other, self)) return NO;
3708 /***********************************************************************
3709 * protocol_copyMethodDescriptionList
3710 * Returns descriptions of a protocol's methods.
3711 * Locking: acquires runtimeLock
3712 **********************************************************************/
3713 struct objc_method_description *
3714 protocol_copyMethodDescriptionList(Protocol *p,
3715 BOOL isRequiredMethod,BOOL isInstanceMethod,
3716 unsigned int *outCount)
3718 protocol_t *proto = newprotocol(p);
3719 struct objc_method_description *result = nil;
3720 unsigned int count = 0;
3723 if (outCount) *outCount = 0;
3727 fixupProtocolIfNeeded(proto);
3729 rwlock_read(&runtimeLock);
3731 method_list_t *mlist =
3732 getProtocolMethodList(proto, isRequiredMethod, isInstanceMethod);
3736 count = mlist->count;
3737 result = (struct objc_method_description *)
3738 calloc(count + 1, sizeof(struct objc_method_description));
3739 for (i = 0; i < count; i++) {
3740 method_t *m = method_list_nth(mlist, i);
3741 result[i].name = m->name;
3742 result[i].types = (char *)m->types;
3746 rwlock_unlock_read(&runtimeLock);
3748 if (outCount) *outCount = count;
3753 /***********************************************************************
3754 * protocol_getProperty
3756 * Locking: runtimeLock must be held by the caller
3757 **********************************************************************/
3759 protocol_getProperty_nolock(protocol_t *proto, const char *name,
3760 bool isRequiredProperty, bool isInstanceProperty)
3762 rwlock_assert_locked(&runtimeLock);
3764 if (!isRequiredProperty || !isInstanceProperty) {
3765 // Only required instance properties are currently supported
3769 property_list_t *plist;
3770 if ((plist = proto->instanceProperties)) {
3772 for (i = 0; i < plist->count; i++) {
3773 property_t *prop = property_list_nth(plist, i);
3774 if (0 == strcmp(name, prop->name)) {
3780 if (proto->protocols) {
3782 for (i = 0; i < proto->protocols->count; i++) {
3783 protocol_t *p = remapProtocol(proto->protocols->list[i]);
3785 protocol_getProperty_nolock(p, name,
3787 isInstanceProperty);
3788 if (prop) return prop;
3795 objc_property_t protocol_getProperty(Protocol *p, const char *name,
3796 BOOL isRequiredProperty, BOOL isInstanceProperty)
3800 if (!p || !name) return nil;
3802 rwlock_read(&runtimeLock);
3803 result = protocol_getProperty_nolock(newprotocol(p), name,
3805 isInstanceProperty);
3806 rwlock_unlock_read(&runtimeLock);
3808 return (objc_property_t)result;
3812 /***********************************************************************
3813 * protocol_copyPropertyList
3815 * Locking: acquires runtimeLock
3816 **********************************************************************/
3817 static property_t **
3818 copyPropertyList(property_list_t *plist, unsigned int *outCount)
3820 property_t **result = nil;
3821 unsigned int count = 0;
3824 count = plist->count;
3829 result = (property_t **)malloc((count+1) * sizeof(property_t *));
3831 for (i = 0; i < count; i++) {
3832 result[i] = property_list_nth(plist, i);
3837 if (outCount) *outCount = count;
3841 objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)
3843 property_t **result = nil;
3846 if (outCount) *outCount = 0;
3850 rwlock_read(&runtimeLock);
3852 property_list_t *plist = newprotocol(proto)->instanceProperties;
3853 result = copyPropertyList(plist, outCount);
3855 rwlock_unlock_read(&runtimeLock);
3857 return (objc_property_t *)result;
3861 /***********************************************************************
3862 * protocol_copyProtocolList
3863 * Copies this protocol's incorporated protocols.
3864 * Does not copy those protocol's incorporated protocols in turn.
3865 * Locking: acquires runtimeLock
3866 **********************************************************************/
3867 Protocol * __unsafe_unretained *
3868 protocol_copyProtocolList(Protocol *p, unsigned int *outCount)
3870 unsigned int count = 0;
3871 Protocol **result = nil;
3872 protocol_t *proto = newprotocol(p);
3875 if (outCount) *outCount = 0;
3879 rwlock_read(&runtimeLock);
3881 if (proto->protocols) {
3882 count = (unsigned int)proto->protocols->count;
3885 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
3888 for (i = 0; i < count; i++) {
3889 result[i] = (Protocol *)remapProtocol(proto->protocols->list[i]);
3894 rwlock_unlock_read(&runtimeLock);
3896 if (outCount) *outCount = count;
3901 /***********************************************************************
3902 * objc_allocateProtocol
3903 * Creates a new protocol. The protocol may not be used until
3904 * objc_registerProtocol() is called.
3905 * Returns nil if a protocol with the same name already exists.
3906 * Locking: acquires runtimeLock
3907 **********************************************************************/
3909 objc_allocateProtocol(const char *name)
3911 rwlock_write(&runtimeLock);
3913 if (getProtocol(name)) {
3914 rwlock_unlock_write(&runtimeLock);
3918 protocol_t *result = (protocol_t *)_calloc_internal(sizeof(protocol_t), 1);
3920 extern objc_class OBJC_CLASS_$___IncompleteProtocol;
3921 Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
3922 result->initProtocolIsa(cls);
3923 result->size = sizeof(protocol_t);
3924 // fixme mangle the name if it looks swift-y?
3925 result->mangledName = _strdup_internal(name);
3927 // fixme reserve name without installing
3929 rwlock_unlock_write(&runtimeLock);
3931 return (Protocol *)result;
3935 /***********************************************************************
3936 * objc_registerProtocol
3937 * Registers a newly-constructed protocol. The protocol is now
3938 * ready for use and immutable.
3939 * Locking: acquires runtimeLock
3940 **********************************************************************/
3941 void objc_registerProtocol(Protocol *proto_gen)
3943 protocol_t *proto = newprotocol(proto_gen);
3945 rwlock_write(&runtimeLock);
3947 extern objc_class OBJC_CLASS_$___IncompleteProtocol;
3948 Class oldcls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
3949 extern objc_class OBJC_CLASS_$_Protocol;
3950 Class cls = (Class)&OBJC_CLASS_$_Protocol;
3952 if (proto->ISA() == cls) {
3953 _objc_inform("objc_registerProtocol: protocol '%s' was already "
3954 "registered!", proto->nameForLogging());
3955 rwlock_unlock_write(&runtimeLock);
3958 if (proto->ISA() != oldcls) {
3959 _objc_inform("objc_registerProtocol: protocol '%s' was not allocated "
3960 "with objc_allocateProtocol!", proto->nameForLogging());
3961 rwlock_unlock_write(&runtimeLock);
3965 proto->initProtocolIsa(cls);
3967 NXMapKeyCopyingInsert(protocols(), proto->mangledName, proto);
3969 rwlock_unlock_write(&runtimeLock);
3973 /***********************************************************************
3974 * protocol_addProtocol
3975 * Adds an incorporated protocol to another protocol.
3976 * No method enforcement is performed.
3977 * `proto` must be under construction. `addition` must not.
3978 * Locking: acquires runtimeLock
3979 **********************************************************************/
3981 protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen)
3983 protocol_t *proto = newprotocol(proto_gen);
3984 protocol_t *addition = newprotocol(addition_gen);
3986 extern objc_class OBJC_CLASS_$___IncompleteProtocol;
3987 Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
3989 if (!proto_gen) return;
3990 if (!addition_gen) return;
3992 rwlock_write(&runtimeLock);
3994 if (proto->ISA() != cls) {
3995 _objc_inform("protocol_addProtocol: modified protocol '%s' is not "
3996 "under construction!", proto->nameForLogging());
3997 rwlock_unlock_write(&runtimeLock);
4000 if (addition->ISA() == cls) {
4001 _objc_inform("protocol_addProtocol: added protocol '%s' is still "
4002 "under construction!", addition->nameForLogging());
4003 rwlock_unlock_write(&runtimeLock);
4007 protocol_list_t *protolist = proto->protocols;
4009 protolist = (protocol_list_t *)
4010 _calloc_internal(1, sizeof(protocol_list_t)
4011 + sizeof(protolist->list[0]));
4013 protolist = (protocol_list_t *)
4014 _realloc_internal(protolist, protocol_list_size(protolist)
4015 + sizeof(protolist->list[0]));
4018 protolist->list[protolist->count++] = (protocol_ref_t)addition;
4019 proto->protocols = protolist;
4021 rwlock_unlock_write(&runtimeLock);
4025 /***********************************************************************
4026 * protocol_addMethodDescription
4027 * Adds a method to a protocol. The protocol must be under construction.
4028 * Locking: acquires runtimeLock
4029 **********************************************************************/
4031 protocol_addMethod_nolock(method_list_t **list, SEL name, const char *types)
4034 *list = (method_list_t *)
4035 _calloc_internal(sizeof(method_list_t), 1);
4036 (*list)->entsize_NEVER_USE = sizeof((*list)->first);
4037 setMethodListFixedUp(*list);
4039 size_t size = method_list_size(*list) + method_list_entsize(*list);
4040 *list = (method_list_t *)
4041 _realloc_internal(*list, size);
4044 method_t *meth = method_list_nth(*list, (*list)->count++);
4046 meth->types = _strdup_internal(types ? types : "");
4051 protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types,
4052 BOOL isRequiredMethod, BOOL isInstanceMethod)
4054 protocol_t *proto = newprotocol(proto_gen);
4056 extern objc_class OBJC_CLASS_$___IncompleteProtocol;
4057 Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
4059 if (!proto_gen) return;
4061 rwlock_write(&runtimeLock);
4063 if (proto->ISA() != cls) {
4064 _objc_inform("protocol_addMethodDescription: protocol '%s' is not "
4065 "under construction!", proto->nameForLogging());
4066 rwlock_unlock_write(&runtimeLock);
4070 if (isRequiredMethod && isInstanceMethod) {
4071 protocol_addMethod_nolock(&proto->instanceMethods, name, types);
4072 } else if (isRequiredMethod && !isInstanceMethod) {
4073 protocol_addMethod_nolock(&proto->classMethods, name, types);
4074 } else if (!isRequiredMethod && isInstanceMethod) {
4075 protocol_addMethod_nolock(&proto->optionalInstanceMethods, name,types);
4076 } else /* !isRequiredMethod && !isInstanceMethod) */ {
4077 protocol_addMethod_nolock(&proto->optionalClassMethods, name, types);
4080 rwlock_unlock_write(&runtimeLock);
4084 /***********************************************************************
4085 * protocol_addProperty
4086 * Adds a property to a protocol. The protocol must be under construction.
4087 * Locking: acquires runtimeLock
4088 **********************************************************************/
4090 protocol_addProperty_nolock(property_list_t **plist, const char *name,
4091 const objc_property_attribute_t *attrs,
4095 *plist = (property_list_t *)
4096 _calloc_internal(sizeof(property_list_t), 1);
4097 (*plist)->entsize = sizeof(property_t);
4099 *plist = (property_list_t *)
4100 _realloc_internal(*plist, sizeof(property_list_t)
4101 + (*plist)->count * (*plist)->entsize);
4104 property_t *prop = property_list_nth(*plist, (*plist)->count++);
4105 prop->name = _strdup_internal(name);
4106 prop->attributes = copyPropertyAttributeString(attrs, count);
4110 protocol_addProperty(Protocol *proto_gen, const char *name,
4111 const objc_property_attribute_t *attrs,
4113 BOOL isRequiredProperty, BOOL isInstanceProperty)
4115 protocol_t *proto = newprotocol(proto_gen);
4117 extern objc_class OBJC_CLASS_$___IncompleteProtocol;
4118 Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
4123 rwlock_write(&runtimeLock);
4125 if (proto->ISA() != cls) {
4126 _objc_inform("protocol_addProperty: protocol '%s' is not "
4127 "under construction!", proto->nameForLogging());
4128 rwlock_unlock_write(&runtimeLock);
4132 if (isRequiredProperty && isInstanceProperty) {
4133 protocol_addProperty_nolock(&proto->instanceProperties, name, attrs, count);
4135 //else if (isRequiredProperty && !isInstanceProperty) {
4136 // protocol_addProperty_nolock(&proto->classProperties, name, attrs, count);
4137 //} else if (!isRequiredProperty && isInstanceProperty) {
4138 // protocol_addProperty_nolock(&proto->optionalInstanceProperties, name, attrs, count);
4139 //} else /* !isRequiredProperty && !isInstanceProperty) */ {
4140 // protocol_addProperty_nolock(&proto->optionalClassProperties, name, attrs, count);
4143 rwlock_unlock_write(&runtimeLock);
4147 /***********************************************************************
4149 * Returns pointers to all classes.
4150 * This requires all classes be realized, which is regretfully non-lazy.
4151 * Locking: acquires runtimeLock
4152 **********************************************************************/
4154 objc_getClassList(Class *buffer, int bufferLen)
4156 rwlock_write(&runtimeLock);
4158 realizeAllClasses();
4163 NXHashTable *classes = realizedClasses();
4164 int allCount = NXCountHashTable(classes);
4167 rwlock_unlock_write(&runtimeLock);
4172 state = NXInitHashState(classes);
4173 while (count < bufferLen &&
4174 NXNextHashState(classes, &state, (void **)&cls))
4176 buffer[count++] = cls;
4179 rwlock_unlock_write(&runtimeLock);
4185 /***********************************************************************
4186 * objc_copyClassList
4187 * Returns pointers to all classes.
4188 * This requires all classes be realized, which is regretfully non-lazy.
4190 * outCount may be nil. *outCount is the number of classes returned.
4191 * If the returned array is not nil, it is nil-terminated and must be
4192 * freed with free().
4193 * Locking: write-locks runtimeLock
4194 **********************************************************************/
4196 objc_copyClassList(unsigned int *outCount)
4198 rwlock_write(&runtimeLock);
4200 realizeAllClasses();
4202 Class *result = nil;
4203 NXHashTable *classes = realizedClasses();
4204 unsigned int count = NXCountHashTable(classes);
4208 NXHashState state = NXInitHashState(classes);
4209 result = (Class *)malloc((1+count) * sizeof(Class));
4211 while (NXNextHashState(classes, &state, (void **)&cls)) {
4212 result[count++] = cls;
4214 result[count] = nil;
4217 rwlock_unlock_write(&runtimeLock);
4219 if (outCount) *outCount = count;
4224 /***********************************************************************
4225 * objc_copyProtocolList
4226 * Returns pointers to all protocols.
4227 * Locking: read-locks runtimeLock
4228 **********************************************************************/
4229 Protocol * __unsafe_unretained *
4230 objc_copyProtocolList(unsigned int *outCount)
4232 rwlock_read(&runtimeLock);
4234 unsigned int count, i;
4238 NXMapTable *protocol_map = protocols();
4241 count = NXCountMapTable(protocol_map);
4243 rwlock_unlock_read(&runtimeLock);
4244 if (outCount) *outCount = 0;
4248 result = (Protocol **)calloc(1 + count, sizeof(Protocol *));
4251 state = NXInitMapState(protocol_map);
4252 while (NXNextMapState(protocol_map, &state,
4253 (const void **)&name, (const void **)&proto))
4255 result[i++] = proto;
4259 assert(i == count+1);
4261 rwlock_unlock_read(&runtimeLock);
4263 if (outCount) *outCount = count;
4268 /***********************************************************************
4270 * Get a protocol by name, or return nil
4271 * Locking: read-locks runtimeLock
4272 **********************************************************************/
4273 Protocol *objc_getProtocol(const char *name)
4275 rwlock_read(&runtimeLock);
4276 Protocol *result = getProtocol(name);
4277 rwlock_unlock_read(&runtimeLock);
4282 /***********************************************************************
4283 * class_copyMethodList
4285 * Locking: read-locks runtimeLock
4286 **********************************************************************/
4288 class_copyMethodList(Class cls, unsigned int *outCount)
4290 unsigned int count = 0;
4291 Method *result = nil;
4294 if (outCount) *outCount = 0;
4298 rwlock_read(&runtimeLock);
4300 assert(cls->isRealized());
4302 FOREACH_METHOD_LIST(mlist, cls, {
4303 count += mlist->count;
4308 result = (Method *)malloc((count + 1) * sizeof(Method));
4311 FOREACH_METHOD_LIST(mlist, cls, {
4313 for (i = 0; i < mlist->count; i++) {
4314 method_t *aMethod = method_list_nth(mlist, i);
4315 if (ignoreSelector(method_getName(aMethod))) {
4319 result[m++] = aMethod;
4325 rwlock_unlock_read(&runtimeLock);
4327 if (outCount) *outCount = count;
4332 /***********************************************************************
4333 * class_copyIvarList
4335 * Locking: read-locks runtimeLock
4336 **********************************************************************/
4338 class_copyIvarList(Class cls, unsigned int *outCount)
4340 const ivar_list_t *ivars;
4342 unsigned int count = 0;
4346 if (outCount) *outCount = 0;
4350 rwlock_read(&runtimeLock);
4352 assert(cls->isRealized());
4354 if ((ivars = cls->data()->ro->ivars) && ivars->count) {
4355 result = (Ivar *)malloc((ivars->count+1) * sizeof(Ivar));
4357 for (i = 0; i < ivars->count; i++) {
4358 ivar_t *ivar = ivar_list_nth(ivars, i);
4359 if (!ivar->offset) continue; // anonymous bitfield
4360 result[count++] = ivar;
4362 result[count] = nil;
4365 rwlock_unlock_read(&runtimeLock);
4367 if (outCount) *outCount = count;
4372 /***********************************************************************
4373 * class_copyPropertyList. Returns a heap block containing the
4374 * properties declared in the class, or nil if the class
4375 * declares no properties. Caller must free the block.
4376 * Does not copy any superclass's properties.
4377 * Locking: read-locks runtimeLock
4378 **********************************************************************/
4380 class_copyPropertyList(Class cls, unsigned int *outCount)
4382 chained_property_list *plist;
4383 unsigned int count = 0;
4384 property_t **result = nil;
4387 if (outCount) *outCount = 0;
4391 rwlock_read(&runtimeLock);
4393 assert(cls->isRealized());
4395 for (plist = cls->data()->properties; plist; plist = plist->next) {
4396 count += plist->count;
4401 result = (property_t **)malloc((count + 1) * sizeof(property_t *));
4404 for (plist = cls->data()->properties; plist; plist = plist->next) {
4406 for (i = 0; i < plist->count; i++) {
4407 result[p++] = &plist->list[i];
4413 rwlock_unlock_read(&runtimeLock);
4415 if (outCount) *outCount = count;
4416 return (objc_property_t *)result;
4420 /***********************************************************************
4421 * objc_class::getLoadMethod
4423 * Called only from add_class_to_loadable_list.
4424 * Locking: runtimeLock must be read- or write-locked by the caller.
4425 **********************************************************************/
4427 objc_class::getLoadMethod()
4429 rwlock_assert_locked(&runtimeLock);
4431 const method_list_t *mlist;
4434 assert(isRealized());
4435 assert(ISA()->isRealized());
4436 assert(!isMetaClass());
4437 assert(ISA()->isMetaClass());
4439 mlist = ISA()->data()->ro->baseMethods;
4441 for (i = 0; i < mlist->count; i++) {
4442 method_t *m = method_list_nth(mlist, i);
4443 const char *name = sel_cname(m->name);
4444 if (0 == strcmp(name, "load")) {
4454 /***********************************************************************
4456 * Returns a category's name.
4458 **********************************************************************/
4460 _category_getName(Category cat)
4466 /***********************************************************************
4467 * _category_getClassName
4468 * Returns a category's class's name
4469 * Called only from add_category_to_loadable_list and
4470 * remove_category_from_loadable_list for logging purposes.
4471 * Locking: runtimeLock must be read- or write-locked by the caller
4472 **********************************************************************/
4474 _category_getClassName(Category cat)
4476 rwlock_assert_locked(&runtimeLock);
4477 return remapClass(cat->cls)->nameForLogging();
4481 /***********************************************************************
4482 * _category_getClass
4483 * Returns a category's class
4484 * Called only by call_category_loads.
4485 * Locking: read-locks runtimeLock
4486 **********************************************************************/
4488 _category_getClass(Category cat)
4490 rwlock_read(&runtimeLock);
4491 Class result = remapClass(cat->cls);
4492 assert(result->isRealized()); // ok for call_category_loads' usage
4493 rwlock_unlock_read(&runtimeLock);
4498 /***********************************************************************
4499 * _category_getLoadMethod
4501 * Called only from add_category_to_loadable_list
4502 * Locking: runtimeLock must be read- or write-locked by the caller
4503 **********************************************************************/
4505 _category_getLoadMethod(Category cat)
4507 rwlock_assert_locked(&runtimeLock);
4509 const method_list_t *mlist;
4512 mlist = cat->classMethods;
4514 for (i = 0; i < mlist->count; i++) {
4515 method_t *m = method_list_nth(mlist, i);
4516 const char *name = sel_cname(m->name);
4517 if (0 == strcmp(name, "load")) {
4527 /***********************************************************************
4528 * class_copyProtocolList
4530 * Locking: read-locks runtimeLock
4531 **********************************************************************/
4532 Protocol * __unsafe_unretained *
4533 class_copyProtocolList(Class cls, unsigned int *outCount)
4536 const protocol_list_t **p;
4537 unsigned int count = 0;
4539 Protocol **result = nil;
4542 if (outCount) *outCount = 0;
4546 rwlock_read(&runtimeLock);
4548 assert(cls->isRealized());
4550 for (p = cls->data()->protocols; p && *p; p++) {
4551 count += (uint32_t)(*p)->count;
4555 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
4557 for (p = cls->data()->protocols; p && *p; p++) {
4558 for (i = 0; i < (*p)->count; i++) {
4559 *r++ = (Protocol *)remapProtocol((*p)->list[i]);
4565 rwlock_unlock_read(&runtimeLock);
4567 if (outCount) *outCount = count;
4572 /***********************************************************************
4573 * _objc_copyClassNamesForImage
4575 * Locking: write-locks runtimeLock
4576 **********************************************************************/
4578 _objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount)
4580 size_t count, i, shift;
4581 classref_t *classlist;
4584 // Need to write-lock in case demangledName() needs to realize a class.
4585 rwlock_write(&runtimeLock);
4587 classlist = _getObjc2ClassList(hi, &count);
4588 names = (const char **)malloc((count+1) * sizeof(const char *));
4591 for (i = 0; i < count; i++) {
4592 Class cls = remapClass(classlist[i]);
4594 names[i-shift] = cls->demangledName(true/*realize*/);
4596 shift++; // ignored weak-linked class
4602 rwlock_unlock_write(&runtimeLock);
4604 if (outCount) *outCount = (unsigned int)count;
4609 /***********************************************************************
4610 * _class_getInstanceStart
4611 * Uses alignedInstanceStart() to ensure that ARR layout strings are
4612 * interpreted relative to the first word aligned ivar of an object.
4614 **********************************************************************/
4617 alignedInstanceStart(Class cls)
4620 assert(cls->isRealized());
4621 return (uint32_t)word_align(cls->data()->ro->instanceStart);
4624 uint32_t _class_getInstanceStart(Class cls) {
4625 return alignedInstanceStart(cls);
4629 /***********************************************************************
4630 * saveTemporaryString
4631 * Save a string in a thread-local FIFO buffer.
4632 * This is suitable for temporary strings generated for logging purposes.
4633 **********************************************************************/
4635 saveTemporaryString(char *str)
4637 // Fixed-size FIFO. We free the first string, shift
4638 // the rest, and add the new string to the end.
4639 _objc_pthread_data *data = _objc_fetch_pthread_data(true);
4640 if (data->printableNames[0]) {
4641 free(data->printableNames[0]);
4643 int last = countof(data->printableNames) - 1;
4644 for (int i = 0; i < last; i++) {
4645 data->printableNames[i] = data->printableNames[i+1];
4647 data->printableNames[last] = str;
4651 /***********************************************************************
4652 * objc_class::nameForLogging
4653 * Returns the class's name, suitable for display.
4654 * The returned memory is TEMPORARY. Print it or copy it immediately.
4656 **********************************************************************/
4658 objc_class::nameForLogging()
4660 // Handle the easy case directly.
4661 if (isRealized() || isFuture()) {
4662 if (data()->demangledName) return data()->demangledName;
4667 const char *name = mangledName();
4668 char *de = copySwiftV1DemangledName(name);
4669 if (de) result = de;
4670 else result = strdup(name);
4672 saveTemporaryString(result);
4677 /***********************************************************************
4678 * objc_class::demangledName
4679 * If realize=false, the class must already be realized or future.
4680 * Locking: If realize=true, runtimeLock must be held for writing by the caller.
4681 **********************************************************************/
4683 objc_class::demangledName(bool realize)
4685 // Return previously demangled name if available.
4686 if (isRealized() || isFuture()) {
4687 if (data()->demangledName) return data()->demangledName;
4690 // Try demangling the mangled name.
4691 const char *mangled = mangledName();
4692 char *de = copySwiftV1DemangledName(mangled);
4693 if (isRealized() || isFuture()) {
4694 // Class is already realized or future.
4695 // Save demangling result in rw data.
4696 // We may not own rwlock for writing so use an atomic operation instead.
4697 if (! OSAtomicCompareAndSwapPtrBarrier(nil, (void*)(de ?: mangled),
4698 (void**)&data()->demangledName))
4702 return data()->demangledName;
4705 // Class is not yet realized.
4707 // Name is not mangled. Return it without caching.
4711 // Class is not yet realized and name is mangled. Realize the class.
4712 // Only objc_copyClassNamesForImage() should get here.
4713 rwlock_assert_writing(&runtimeLock);
4716 realizeClass((Class)this);
4717 data()->demangledName = de;
4720 return de; // bug - just leak
4725 /***********************************************************************
4728 * Locking: acquires runtimeLock
4729 **********************************************************************/
4730 const char *class_getName(Class cls)
4732 if (!cls) return "nil";
4733 assert(cls->isRealized() || cls->isFuture());
4734 return cls->demangledName();
4738 /***********************************************************************
4742 **********************************************************************/
4744 class_getVersion(Class cls)
4747 assert(cls->isRealized());
4748 return cls->data()->version;
4752 /***********************************************************************
4756 **********************************************************************/
4758 class_setVersion(Class cls, int version)
4761 assert(cls->isRealized());
4762 cls->data()->version = version;
4766 static method_t *findMethodInSortedMethodList(SEL key, const method_list_t *list)
4768 const method_t * const first = &list->first;
4769 const method_t *base = first;
4770 const method_t *probe;
4771 uintptr_t keyValue = (uintptr_t)key;
4774 for (count = list->count; count != 0; count >>= 1) {
4775 probe = base + (count >> 1);
4777 uintptr_t probeValue = (uintptr_t)probe->name;
4779 if (keyValue == probeValue) {
4780 // `probe` is a match.
4781 // Rewind looking for the *first* occurrence of this value.
4782 // This is required for correct category overrides.
4783 while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
4786 return (method_t *)probe;
4789 if (keyValue > probeValue) {
4798 /***********************************************************************
4799 * getMethodNoSuper_nolock
4801 * Locking: runtimeLock must be read- or write-locked by the caller
4802 **********************************************************************/
4803 static method_t *search_method_list(const method_list_t *mlist, SEL sel)
4805 int methodListIsFixedUp = isMethodListFixedUp(mlist);
4806 int methodListHasExpectedSize = mlist->getEntsize() == sizeof(method_t);
4808 if (__builtin_expect(methodListIsFixedUp && methodListHasExpectedSize, 1)) {
4809 return findMethodInSortedMethodList(sel, mlist);
4811 // Linear search of unsorted method list
4812 method_list_t::method_iterator iter = mlist->begin();
4813 method_list_t::method_iterator end = mlist->end();
4814 for ( ; iter != end; ++iter) {
4815 if (iter->name == sel) return &*iter;
4820 // sanity-check negative results
4821 if (isMethodListFixedUp(mlist)) {
4822 method_list_t::method_iterator iter = mlist->begin();
4823 method_list_t::method_iterator end = mlist->end();
4824 for ( ; iter != end; ++iter) {
4825 if (iter->name == sel) {
4826 _objc_fatal("linear search worked when binary search did not");
4836 getMethodNoSuper_nolock(Class cls, SEL sel)
4838 rwlock_assert_locked(&runtimeLock);
4840 assert(cls->isRealized());
4844 FOREACH_METHOD_LIST(mlist, cls, {
4845 method_t *m = search_method_list(mlist, sel);
4853 /***********************************************************************
4856 * Locking: runtimeLock must be read- or write-locked by the caller
4857 **********************************************************************/
4859 getMethod_nolock(Class cls, SEL sel)
4863 rwlock_assert_locked(&runtimeLock);
4868 assert(cls->isRealized());
4870 while (cls && ((m = getMethodNoSuper_nolock(cls, sel))) == nil) {
4871 cls = cls->superclass;
4878 /***********************************************************************
4881 * Locking: read-locks runtimeLock
4882 **********************************************************************/
4883 static Method _class_getMethod(Class cls, SEL sel)
4886 rwlock_read(&runtimeLock);
4887 m = getMethod_nolock(cls, sel);
4888 rwlock_unlock_read(&runtimeLock);
4893 /***********************************************************************
4894 * class_getInstanceMethod. Return the instance method for the
4895 * specified class and selector.
4896 **********************************************************************/
4897 Method class_getInstanceMethod(Class cls, SEL sel)
4899 if (!cls || !sel) return nil;
4901 // This deliberately avoids +initialize because it historically did so.
4903 // This implementation is a bit weird because it's the only place that
4904 // wants a Method instead of an IMP.
4906 #warning fixme build and search caches
4908 // Search method lists, try method resolver, etc.
4909 lookUpImpOrNil(cls, sel, nil,
4910 NO/*initialize*/, NO/*cache*/, YES/*resolver*/);
4912 #warning fixme build and search caches
4914 return _class_getMethod(cls, sel);
4918 /***********************************************************************
4919 * log_and_fill_cache
4920 * Log this method call. If the logger permits it, fill the method cache.
4921 * cls is the method whose cache should be filled.
4922 * implementer is the class that owns the implementation in question.
4923 **********************************************************************/
4925 log_and_fill_cache(Class cls, Class implementer, IMP imp, SEL sel)
4927 #if SUPPORT_MESSAGE_LOGGING
4928 if (objcMsgLogEnabled) {
4929 bool cacheIt = logMessageSend(implementer->isMetaClass(),
4930 cls->nameForLogging(),
4931 implementer->nameForLogging(),
4933 if (!cacheIt) return;
4936 cache_fill (cls, sel, imp);
4940 /***********************************************************************
4941 * _class_lookupMethodAndLoadCache.
4942 * Method lookup for dispatchers ONLY. OTHER CODE SHOULD USE lookUpImp().
4943 * This lookup avoids optimistic cache scan because the dispatcher
4944 * already tried that.
4945 **********************************************************************/
4946 IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
4948 return lookUpImpOrForward(cls, sel, obj,
4949 YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
4953 /***********************************************************************
4954 * lookUpImpOrForward.
4955 * The standard IMP lookup.
4956 * initialize==NO tries to avoid +initialize (but sometimes fails)
4957 * cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
4958 * Most callers should use initialize==YES and cache==YES.
4959 * inst is an instance of cls or a subclass thereof, or nil if none is known.
4960 * If cls is an un-initialized metaclass then a non-nil inst is faster.
4961 * May return _objc_msgForward_impcache. IMPs destined for external use
4962 * must be converted to _objc_msgForward or _objc_msgForward_stret.
4963 * If you don't want forwarding at all, use lookUpImpOrNil() instead.
4964 **********************************************************************/
4965 IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
4966 bool initialize, bool cache, bool resolver)
4971 bool triedResolver = NO;
4973 rwlock_assert_unlocked(&runtimeLock);
4975 // Optimistic cache lookup
4977 imp = cache_getImp(cls, sel);
4978 if (imp) return imp;
4981 if (!cls->isRealized()) {
4982 rwlock_write(&runtimeLock);
4984 rwlock_unlock_write(&runtimeLock);
4987 if (initialize && !cls->isInitialized()) {
4988 _class_initialize (_class_getNonMetaClass(cls, inst));
4989 // If sel == initialize, _class_initialize will send +initialize and
4990 // then the messenger will send +initialize again after this
4991 // procedure finishes. Of course, if this is not being called
4992 // from the messenger then it won't happen. 2778172
4995 // The lock is held to make method-lookup + cache-fill atomic
4996 // with respect to method addition. Otherwise, a category could
4997 // be added but ignored indefinitely because the cache was re-filled
4998 // with the old value after the cache flush on behalf of the category.
5000 rwlock_read(&runtimeLock);
5002 // Ignore GC selectors
5003 if (ignoreSelector(sel)) {
5004 imp = _objc_ignored_method;
5005 cache_fill(cls, sel, imp);
5009 // Try this class's cache.
5011 imp = cache_getImp(cls, sel);
5014 // Try this class's method lists.
5016 meth = getMethodNoSuper_nolock(cls, sel);
5018 log_and_fill_cache(cls, cls, meth->imp, sel);
5023 // Try superclass caches and method lists.
5026 while ((curClass = curClass->superclass)) {
5027 // Superclass cache.
5028 imp = cache_getImp(curClass, sel);
5030 if (imp != (IMP)_objc_msgForward_impcache) {
5031 // Found the method in a superclass. Cache it in this class.
5032 log_and_fill_cache(cls, curClass, imp, sel);
5036 // Found a forward:: entry in a superclass.
5037 // Stop searching, but don't cache yet; call method
5038 // resolver for this class first.
5043 // Superclass method list.
5044 meth = getMethodNoSuper_nolock(curClass, sel);
5046 log_and_fill_cache(cls, curClass, meth->imp, sel);
5052 // No implementation found. Try method resolver once.
5054 if (resolver && !triedResolver) {
5055 rwlock_unlock_read(&runtimeLock);
5056 _class_resolveMethod(cls, sel, inst);
5057 // Don't cache the result; we don't hold the lock so it may have
5058 // changed already. Re-do the search from scratch instead.
5059 triedResolver = YES;
5063 // No implementation found, and method resolver didn't help.
5066 imp = (IMP)_objc_msgForward_impcache;
5067 cache_fill(cls, sel, imp);
5070 rwlock_unlock_read(&runtimeLock);
5072 // paranoia: look for ignored selectors with non-ignored implementations
5073 assert(!(ignoreSelector(sel) && imp != (IMP)&_objc_ignored_method));
5075 // paranoia: never let uncached leak out
5076 assert(imp != _objc_msgSend_uncached_impcache);
5082 /***********************************************************************
5084 * Like lookUpImpOrForward, but returns nil instead of _objc_msgForward_impcache
5085 **********************************************************************/
5086 IMP lookUpImpOrNil(Class cls, SEL sel, id inst,
5087 bool initialize, bool cache, bool resolver)
5089 IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
5090 if (imp == _objc_msgForward_impcache) return nil;
5095 /***********************************************************************
5096 * lookupMethodInClassAndLoadCache.
5097 * Like _class_lookupMethodAndLoadCache, but does not search superclasses.
5098 * Caches and returns objc_msgForward if the method is not found in the class.
5099 **********************************************************************/
5100 IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel)
5105 // fixme this is incomplete - no resolver, +initialize, GC -
5106 // but it's only used for .cxx_construct/destruct so we don't care
5107 assert(sel == SEL_cxx_construct || sel == SEL_cxx_destruct);
5109 // Search cache first.
5110 imp = cache_getImp(cls, sel);
5111 if (imp) return imp;
5113 // Cache miss. Search method list.
5115 rwlock_read(&runtimeLock);
5117 meth = getMethodNoSuper_nolock(cls, sel);
5120 // Hit in method list. Cache it.
5121 cache_fill(cls, sel, meth->imp);
5122 rwlock_unlock_read(&runtimeLock);
5125 // Miss in method list. Cache objc_msgForward.
5126 cache_fill(cls, sel, _objc_msgForward_impcache);
5127 rwlock_unlock_read(&runtimeLock);
5128 return _objc_msgForward_impcache;
5133 /***********************************************************************
5136 * Locking: read-locks runtimeLock
5137 **********************************************************************/
5138 objc_property_t class_getProperty(Class cls, const char *name)
5140 property_t *result = nil;
5141 chained_property_list *plist;
5143 if (!cls || !name) return nil;
5145 rwlock_read(&runtimeLock);
5147 assert(cls->isRealized());
5149 for ( ; cls; cls = cls->superclass) {
5150 for (plist = cls->data()->properties; plist; plist = plist->next) {
5152 for (i = 0; i < plist->count; i++) {
5153 if (0 == strcmp(name, plist->list[i].name)) {
5154 result = &plist->list[i];
5162 rwlock_unlock_read(&runtimeLock);
5164 return (objc_property_t)result;
5168 /***********************************************************************
5170 **********************************************************************/
5172 Class gdb_class_getClass(Class cls)
5174 const char *className = cls->mangledName();
5175 if(!className || !strlen(className)) return Nil;
5176 Class rCls = look_up_class(className, NO, NO);
5180 Class gdb_object_getClass(id obj)
5182 if (!obj) return nil;
5183 return gdb_class_getClass(obj->getIsa());
5187 /***********************************************************************
5188 * Locking: write-locks runtimeLock
5189 **********************************************************************/
5191 objc_class::setInitialized()
5196 assert(!isMetaClass());
5199 metacls = cls->ISA();
5201 rwlock_read(&runtimeLock);
5203 // Scan metaclass for custom AWZ.
5204 // Scan metaclass for custom RR.
5205 // Scan class for custom RR.
5206 // Also print custom RR/AWZ because we probably haven't done it yet.
5209 // GC's RR and AWZ are never default.
5210 // NSObject AWZ class methods are default.
5211 // NSObject RR instance methods are default.
5212 // updateCustomRR_AWZ() also knows these special cases.
5213 // attachMethodLists() also knows these special cases.
5216 bool metaCustomAWZ = NO;
5218 // GC is always custom AWZ
5219 metaCustomAWZ = YES;
5222 else if (MetaclassNSObjectAWZSwizzled) {
5223 // Somebody already swizzled NSObject's methods
5224 metaCustomAWZ = YES;
5227 else if (metacls == classNSObject()->ISA()) {
5228 // NSObject's metaclass AWZ is default, but we still need to check cats
5229 FOREACH_CATEGORY_METHOD_LIST(mlist, metacls, {
5230 if (methodListImplementsAWZ(mlist)) {
5231 metaCustomAWZ = YES;
5237 else if (metacls->superclass->hasCustomAWZ()) {
5238 // Superclass is custom AWZ, therefore we are too.
5239 metaCustomAWZ = YES;
5243 // Not metaclass NSObject.
5244 FOREACH_METHOD_LIST(mlist, metacls, {
5245 if (methodListImplementsAWZ(mlist)) {
5246 metaCustomAWZ = YES;
5252 if (!metaCustomAWZ) metacls->setHasDefaultAWZ();
5254 if (PrintCustomAWZ && metaCustomAWZ) metacls->printCustomAWZ(inherited);
5255 // metacls->printCustomRR();
5258 bool clsCustomRR = NO;
5260 // GC is always custom RR
5264 else if (ClassNSObjectRRSwizzled) {
5265 // Somebody already swizzled NSObject's methods
5269 if (cls == classNSObject()) {
5270 // NSObject's RR is default, but we still need to check categories
5271 FOREACH_CATEGORY_METHOD_LIST(mlist, cls, {
5272 if (methodListImplementsRR(mlist)) {
5279 else if (!cls->superclass) {
5280 // Custom root class
5284 else if (cls->superclass->hasCustomRR()) {
5285 // Superclass is custom RR, therefore we are too.
5290 // Not class NSObject.
5291 FOREACH_METHOD_LIST(mlist, cls, {
5292 if (methodListImplementsRR(mlist)) {
5299 if (!clsCustomRR) cls->setHasDefaultRR();
5301 // cls->printCustomAWZ();
5302 if (PrintCustomRR && clsCustomRR) cls->printCustomRR(inherited);
5304 // Update the +initialize flags.
5306 metacls->changeInfo(RW_INITIALIZED, RW_INITIALIZING);
5308 rwlock_unlock_read(&runtimeLock);
5312 /***********************************************************************
5313 * _class_usesAutomaticRetainRelease
5314 * Returns YES if class was compiled with -fobjc-arc
5315 **********************************************************************/
5316 BOOL _class_usesAutomaticRetainRelease(Class cls)
5318 return (cls->data()->ro->flags & RO_IS_ARR) ? YES : NO;
5322 /***********************************************************************
5323 * Return YES if sel is used by retain/release implementors
5324 **********************************************************************/
5326 isRRSelector(SEL sel)
5328 return (sel == SEL_retain || sel == SEL_release ||
5329 sel == SEL_autorelease || sel == SEL_retainCount ||
5330 sel == SEL_tryRetain || sel == SEL_retainWeakReference ||
5331 sel == SEL_isDeallocating || sel == SEL_allowsWeakReference);
5335 /***********************************************************************
5336 * Return YES if mlist implements one of the isRRSelector() methods
5337 **********************************************************************/
5339 methodListImplementsRR(const method_list_t *mlist)
5341 return (search_method_list(mlist, SEL_retain) ||
5342 search_method_list(mlist, SEL_release) ||
5343 search_method_list(mlist, SEL_autorelease) ||
5344 search_method_list(mlist, SEL_retainCount) ||
5345 search_method_list(mlist, SEL_tryRetain) ||
5346 search_method_list(mlist, SEL_isDeallocating) ||
5347 search_method_list(mlist, SEL_retainWeakReference) ||
5348 search_method_list(mlist, SEL_allowsWeakReference));
5352 /***********************************************************************
5353 * Return YES if sel is used by alloc or allocWithZone implementors
5354 **********************************************************************/
5356 isAWZSelector(SEL sel)
5358 return (sel == SEL_allocWithZone || sel == SEL_alloc);
5362 /***********************************************************************
5363 * Return YES if mlist implements one of the isAWZSelector() methods
5364 **********************************************************************/
5366 methodListImplementsAWZ(const method_list_t *mlist)
5368 return (search_method_list(mlist, SEL_allocWithZone) ||
5369 search_method_list(mlist, SEL_alloc));
5374 objc_class::printCustomRR(bool inherited)
5376 assert(PrintCustomRR);
5377 assert(hasCustomRR());
5378 _objc_inform("CUSTOM RR: %s%s%s", nameForLogging(),
5379 isMetaClass() ? " (meta)" : "",
5380 inherited ? " (inherited)" : "");
5384 objc_class::printCustomAWZ(bool inherited)
5386 assert(PrintCustomAWZ);
5387 assert(hasCustomAWZ());
5388 _objc_inform("CUSTOM AWZ: %s%s%s", nameForLogging(),
5389 isMetaClass() ? " (meta)" : "",
5390 inherited ? " (inherited)" : "");
5394 objc_class::printRequiresRawIsa(bool inherited)
5396 assert(PrintRawIsa);
5397 assert(requiresRawIsa());
5398 _objc_inform("RAW ISA: %s%s%s", nameForLogging(),
5399 isMetaClass() ? " (meta)" : "",
5400 inherited ? " (inherited)" : "");
5404 /***********************************************************************
5405 * Mark this class and all of its subclasses as implementors or
5406 * inheritors of custom RR (retain/release/autorelease/retainCount)
5407 **********************************************************************/
5408 void objc_class::setHasCustomRR(bool inherited)
5410 Class cls = (Class)this;
5411 rwlock_assert_writing(&runtimeLock);
5413 if (hasCustomRR()) return;
5415 foreach_realized_class_and_subclass(cls, ^(Class c){
5416 if (c != cls && !c->isInitialized()) {
5417 // Subclass not yet initialized. Wait for setInitialized() to do it
5418 // fixme short circuit recursion?
5421 if (c->hasCustomRR()) {
5422 // fixme short circuit recursion?
5426 c->bits.setHasCustomRR();
5428 if (PrintCustomRR) c->printCustomRR(inherited || c != cls);
5432 /***********************************************************************
5433 * Mark this class and all of its subclasses as implementors or
5434 * inheritors of custom alloc/allocWithZone:
5435 **********************************************************************/
5436 void objc_class::setHasCustomAWZ(bool inherited)
5438 Class cls = (Class)this;
5439 rwlock_assert_writing(&runtimeLock);
5441 if (hasCustomAWZ()) return;
5443 foreach_realized_class_and_subclass(cls, ^(Class c){
5444 if (c != cls && !c->isInitialized()) {
5445 // Subclass not yet initialized. Wait for setInitialized() to do it
5446 // fixme short circuit recursion?
5449 if (c->hasCustomAWZ()) {
5450 // fixme short circuit recursion?
5454 c->bits.setHasCustomAWZ();
5456 if (PrintCustomAWZ) c->printCustomAWZ(inherited || c != cls);
5461 /***********************************************************************
5462 * Mark this class and all of its subclasses as requiring raw isa pointers
5463 **********************************************************************/
5464 void objc_class::setRequiresRawIsa(bool inherited)
5466 Class cls = (Class)this;
5467 rwlock_assert_writing(&runtimeLock);
5469 if (requiresRawIsa()) return;
5471 foreach_realized_class_and_subclass(cls, ^(Class c){
5472 if (c->isInitialized()) {
5473 _objc_fatal("too late to require raw isa");
5476 if (c->requiresRawIsa()) {
5477 // fixme short circuit recursion?
5481 c->bits.setRequiresRawIsa();
5483 if (PrintRawIsa) c->printRequiresRawIsa(inherited || c != cls);
5488 /***********************************************************************
5489 * Update custom RR and AWZ when a method changes its IMP
5490 **********************************************************************/
5492 updateCustomRR_AWZ(Class cls, method_t *meth)
5494 // In almost all cases, IMP swizzling does not affect custom RR/AWZ bits.
5495 // Custom RR/AWZ search will already find the method whether or not
5496 // it is swizzled, so it does not transition from non-custom to custom.
5498 // The only cases where IMP swizzling can affect the RR/AWZ bits is
5499 // if the swizzled method is one of the methods that is assumed to be
5500 // non-custom. These special cases are listed in setInitialized().
5501 // We look for such cases here.
5503 if (isRRSelector(meth->name)) {
5504 // already custom, nothing would change
5505 if (classNSObject()->hasCustomRR()) return;
5507 bool swizzlingNSObject = NO;
5508 if (cls == classNSObject()) {
5509 swizzlingNSObject = YES;
5511 // Don't know the class.
5512 // The only special case is class NSObject.
5513 FOREACH_METHOD_LIST(mlist, classNSObject(), {
5514 for (uint32_t i = 0; i < mlist->count; i++) {
5515 if (meth == method_list_nth(mlist, i)) {
5516 swizzlingNSObject = YES;
5520 if (swizzlingNSObject) break;
5523 if (swizzlingNSObject) {
5524 if (classNSObject()->isInitialized()) {
5525 classNSObject()->setHasCustomRR();
5527 // NSObject not yet +initialized, so custom RR has not yet
5528 // been checked, and setInitialized() will not notice the
5530 ClassNSObjectRRSwizzled = YES;
5534 else if (isAWZSelector(meth->name)) {
5535 // already custom, nothing would change
5536 if (classNSObject()->ISA()->hasCustomAWZ()) return;
5538 bool swizzlingNSObject = NO;
5539 if (cls == classNSObject()->ISA()) {
5540 swizzlingNSObject = YES;
5542 // Don't know the class.
5543 // The only special case is metaclass NSObject.
5544 FOREACH_METHOD_LIST(mlist, classNSObject()->ISA(), {
5545 for (uint32_t i = 0; i < mlist->count; i++) {
5546 if (meth == method_list_nth(mlist, i)) {
5547 swizzlingNSObject = YES;
5551 if (swizzlingNSObject) break;
5554 if (swizzlingNSObject) {
5555 if (classNSObject()->ISA()->isInitialized()) {
5556 classNSObject()->ISA()->setHasCustomAWZ();
5558 // NSObject not yet +initialized, so custom RR has not yet
5559 // been checked, and setInitialized() will not notice the
5561 MetaclassNSObjectAWZSwizzled = YES;
5568 /***********************************************************************
5569 * class_getIvarLayout
5570 * Called by the garbage collector.
5571 * The class must be nil or already realized.
5573 **********************************************************************/
5575 class_getIvarLayout(Class cls)
5577 if (cls) return cls->data()->ro->ivarLayout;
5582 /***********************************************************************
5583 * class_getWeakIvarLayout
5584 * Called by the garbage collector.
5585 * The class must be nil or already realized.
5587 **********************************************************************/
5589 class_getWeakIvarLayout(Class cls)
5591 if (cls) return cls->data()->ro->weakIvarLayout;
5596 /***********************************************************************
5597 * class_setIvarLayout
5598 * Changes the class's GC scan layout.
5599 * nil layout means no unscanned ivars
5600 * The class must be under construction.
5601 * fixme: sanity-check layout vs instance size?
5602 * fixme: sanity-check layout vs superclass?
5603 * Locking: acquires runtimeLock
5604 **********************************************************************/
5606 class_setIvarLayout(Class cls, const uint8_t *layout)
5610 rwlock_write(&runtimeLock);
5612 // Can only change layout of in-construction classes.
5613 // note: if modifications to post-construction classes were
5614 // allowed, there would be a race below (us vs. concurrent GC scan)
5615 if (!(cls->data()->flags & RW_CONSTRUCTING)) {
5616 _objc_inform("*** Can't set ivar layout for already-registered "
5617 "class '%s'", cls->nameForLogging());
5618 rwlock_unlock_write(&runtimeLock);
5622 class_ro_t *ro_w = make_ro_writeable(cls->data());
5624 try_free(ro_w->ivarLayout);
5625 ro_w->ivarLayout = _ustrdup_internal(layout);
5627 rwlock_unlock_write(&runtimeLock);
5630 // SPI: Instance-specific object layout.
5633 _class_setIvarLayoutAccessor(Class cls, const uint8_t* (*accessor) (id object)) {
5636 rwlock_write(&runtimeLock);
5638 class_ro_t *ro_w = make_ro_writeable(cls->data());
5640 // FIXME: this really isn't safe to free if there are instances of this class already.
5641 if (!(cls->data()->flags & RW_HAS_INSTANCE_SPECIFIC_LAYOUT)) try_free(ro_w->ivarLayout);
5642 ro_w->ivarLayout = (uint8_t *)accessor;
5643 cls->setInfo(RW_HAS_INSTANCE_SPECIFIC_LAYOUT);
5645 rwlock_unlock_write(&runtimeLock);
5649 _object_getIvarLayout(Class cls, id object)
5652 const uint8_t* layout = cls->data()->ro->ivarLayout;
5653 if (cls->data()->flags & RW_HAS_INSTANCE_SPECIFIC_LAYOUT) {
5654 const uint8_t* (*accessor) (id object) = (const uint8_t* (*)(id))layout;
5655 layout = accessor(object);
5662 /***********************************************************************
5663 * class_setWeakIvarLayout
5664 * Changes the class's GC weak layout.
5665 * nil layout means no weak ivars
5666 * The class must be under construction.
5667 * fixme: sanity-check layout vs instance size?
5668 * fixme: sanity-check layout vs superclass?
5669 * Locking: acquires runtimeLock
5670 **********************************************************************/
5672 class_setWeakIvarLayout(Class cls, const uint8_t *layout)
5676 rwlock_write(&runtimeLock);
5678 // Can only change layout of in-construction classes.
5679 // note: if modifications to post-construction classes were
5680 // allowed, there would be a race below (us vs. concurrent GC scan)
5681 if (!(cls->data()->flags & RW_CONSTRUCTING)) {
5682 _objc_inform("*** Can't set weak ivar layout for already-registered "
5683 "class '%s'", cls->nameForLogging());
5684 rwlock_unlock_write(&runtimeLock);
5688 class_ro_t *ro_w = make_ro_writeable(cls->data());
5690 try_free(ro_w->weakIvarLayout);
5691 ro_w->weakIvarLayout = _ustrdup_internal(layout);
5693 rwlock_unlock_write(&runtimeLock);
5697 /***********************************************************************
5698 * _class_getVariable
5700 * Locking: read-locks runtimeLock
5701 **********************************************************************/
5703 _class_getVariable(Class cls, const char *name, Class *memberOf)
5705 rwlock_read(&runtimeLock);
5707 for ( ; cls; cls = cls->superclass) {
5708 ivar_t *ivar = getIvar(cls, name);
5710 rwlock_unlock_read(&runtimeLock);
5711 if (memberOf) *memberOf = cls;
5716 rwlock_unlock_read(&runtimeLock);
5722 /***********************************************************************
5723 * class_conformsToProtocol
5725 * Locking: read-locks runtimeLock
5726 **********************************************************************/
5727 BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen)
5729 protocol_t *proto = newprotocol(proto_gen);
5730 const protocol_list_t **plist;
5734 if (!cls) return NO;
5735 if (!proto_gen) return NO;
5737 rwlock_read(&runtimeLock);
5739 assert(cls->isRealized());
5741 for (plist = cls->data()->protocols; plist && *plist; plist++) {
5742 for (i = 0; i < (*plist)->count; i++) {
5743 protocol_t *p = remapProtocol((*plist)->list[i]);
5744 if (p == proto || protocol_conformsToProtocol_nolock(p, proto)) {
5752 rwlock_unlock_read(&runtimeLock);
5758 /**********************************************************************
5761 * Locking: runtimeLock must be held by the caller
5762 **********************************************************************/
5764 addMethod(Class cls, SEL name, IMP imp, const char *types, BOOL replace)
5768 rwlock_assert_writing(&runtimeLock);
5771 assert(cls->isRealized());
5774 if ((m = getMethodNoSuper_nolock(cls, name))) {
5777 result = _method_getImplementation(m);
5779 result = _method_setImplementation(cls, m, imp);
5783 method_list_t *newlist;
5784 newlist = (method_list_t *)_calloc_internal(sizeof(*newlist), 1);
5785 newlist->entsize_NEVER_USE = (uint32_t)sizeof(method_t) | fixed_up_method_list;
5787 newlist->first.name = name;
5788 newlist->first.types = strdup(types);
5789 if (!ignoreSelector(name)) {
5790 newlist->first.imp = imp;
5792 newlist->first.imp = (IMP)&_objc_ignored_method;
5795 attachMethodLists(cls, &newlist, 1, NO, NO, YES);
5805 class_addMethod(Class cls, SEL name, IMP imp, const char *types)
5807 if (!cls) return NO;
5809 rwlock_write(&runtimeLock);
5810 IMP old = addMethod(cls, name, imp, types ?: "", NO);
5811 rwlock_unlock_write(&runtimeLock);
5812 return old ? NO : YES;
5817 class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
5819 if (!cls) return nil;
5821 rwlock_write(&runtimeLock);
5822 IMP old = addMethod(cls, name, imp, types ?: "", YES);
5823 rwlock_unlock_write(&runtimeLock);
5828 /***********************************************************************
5830 * Adds an ivar to a class.
5831 * Locking: acquires runtimeLock
5832 **********************************************************************/
5834 class_addIvar(Class cls, const char *name, size_t size,
5835 uint8_t alignment, const char *type)
5837 if (!cls) return NO;
5839 if (!type) type = "";
5840 if (name && 0 == strcmp(name, "")) name = nil;
5842 rwlock_write(&runtimeLock);
5844 assert(cls->isRealized());
5846 // No class variables
5847 if (cls->isMetaClass()) {
5848 rwlock_unlock_write(&runtimeLock);
5852 // Can only add ivars to in-construction classes.
5853 if (!(cls->data()->flags & RW_CONSTRUCTING)) {
5854 rwlock_unlock_write(&runtimeLock);
5858 // Check for existing ivar with this name, unless it's anonymous.
5859 // Check for too-big ivar.
5860 // fixme check for superclass ivar too?
5861 if ((name && getIvar(cls, name)) || size > UINT32_MAX) {
5862 rwlock_unlock_write(&runtimeLock);
5866 class_ro_t *ro_w = make_ro_writeable(cls->data());
5868 // fixme allocate less memory here
5870 ivar_list_t *oldlist, *newlist;
5871 if ((oldlist = (ivar_list_t *)cls->data()->ro->ivars)) {
5872 size_t oldsize = ivar_list_size(oldlist);
5873 newlist = (ivar_list_t *)
5874 _calloc_internal(oldsize + oldlist->entsize, 1);
5875 memcpy(newlist, oldlist, oldsize);
5876 _free_internal(oldlist);
5878 newlist = (ivar_list_t *)
5879 _calloc_internal(sizeof(ivar_list_t), 1);
5880 newlist->entsize = (uint32_t)sizeof(ivar_t);
5883 uint32_t offset = cls->unalignedInstanceSize();
5884 uint32_t alignMask = (1<<alignment)-1;
5885 offset = (offset + alignMask) & ~alignMask;
5887 ivar_t *ivar = ivar_list_nth(newlist, newlist->count++);
5889 // Deliberately over-allocate the ivar offset variable.
5890 // Use calloc() to clear all 64 bits. See the note in struct ivar_t.
5891 ivar->offset = (int32_t *)(int64_t *)_calloc_internal(sizeof(int64_t), 1);
5893 ivar->offset = (int32_t *)_malloc_internal(sizeof(int32_t));
5895 *ivar->offset = offset;
5896 ivar->name = name ? _strdup_internal(name) : nil;
5897 ivar->type = _strdup_internal(type);
5898 ivar->alignment_raw = alignment;
5899 ivar->size = (uint32_t)size;
5901 ro_w->ivars = newlist;
5902 cls->setInstanceSize((uint32_t)(offset + size));
5904 // Ivar layout updated in registerClass.
5906 rwlock_unlock_write(&runtimeLock);
5912 /***********************************************************************
5914 * Adds a protocol to a class.
5915 * Locking: acquires runtimeLock
5916 **********************************************************************/
5917 BOOL class_addProtocol(Class cls, Protocol *protocol_gen)
5919 protocol_t *protocol = newprotocol(protocol_gen);
5920 protocol_list_t *plist;
5921 const protocol_list_t **plistp;
5923 if (!cls) return NO;
5924 if (class_conformsToProtocol(cls, protocol_gen)) return NO;
5926 rwlock_write(&runtimeLock);
5928 assert(cls->isRealized());
5931 plist = (protocol_list_t *)
5932 _malloc_internal(sizeof(protocol_list_t) + sizeof(protocol_t *));
5934 plist->list[0] = (protocol_ref_t)protocol;
5936 unsigned int count = 0;
5937 for (plistp = cls->data()->protocols; plistp && *plistp; plistp++) {
5941 cls->data()->protocols = (const protocol_list_t **)
5942 _realloc_internal(cls->data()->protocols,
5943 (count+2) * sizeof(protocol_list_t *));
5944 cls->data()->protocols[count] = plist;
5945 cls->data()->protocols[count+1] = nil;
5949 rwlock_unlock_write(&runtimeLock);
5955 /***********************************************************************
5957 * Adds a property to a class.
5958 * Locking: acquires runtimeLock
5959 **********************************************************************/
5961 _class_addProperty(Class cls, const char *name,
5962 const objc_property_attribute_t *attrs, unsigned int count,
5965 chained_property_list *plist;
5967 if (!cls) return NO;
5968 if (!name) return NO;
5970 property_t *prop = class_getProperty(cls, name);
5971 if (prop && !replace) {
5972 // already exists, refuse to replace
5977 rwlock_write(&runtimeLock);
5978 try_free(prop->attributes);
5979 prop->attributes = copyPropertyAttributeString(attrs, count);
5980 rwlock_unlock_write(&runtimeLock);
5984 rwlock_write(&runtimeLock);
5986 assert(cls->isRealized());
5988 plist = (chained_property_list *)
5989 _malloc_internal(sizeof(*plist) + sizeof(plist->list[0]));
5991 plist->list[0].name = _strdup_internal(name);
5992 plist->list[0].attributes = copyPropertyAttributeString(attrs, count);
5994 plist->next = cls->data()->properties;
5995 cls->data()->properties = plist;
5997 rwlock_unlock_write(&runtimeLock);
6004 class_addProperty(Class cls, const char *name,
6005 const objc_property_attribute_t *attrs, unsigned int n)
6007 return _class_addProperty(cls, name, attrs, n, NO);
6011 class_replaceProperty(Class cls, const char *name,
6012 const objc_property_attribute_t *attrs, unsigned int n)
6014 _class_addProperty(cls, name, attrs, n, YES);
6018 /***********************************************************************
6020 * Look up a class by name, and realize it.
6021 * Locking: acquires runtimeLock
6022 **********************************************************************/
6024 look_up_class(const char *name,
6025 BOOL includeUnconnected __attribute__((unused)),
6026 BOOL includeClassHandler __attribute__((unused)))
6028 if (!name) return nil;
6030 rwlock_read(&runtimeLock);
6031 Class result = getClass(name);
6032 BOOL unrealized = result && !result->isRealized();
6033 rwlock_unlock_read(&runtimeLock);
6035 rwlock_write(&runtimeLock);
6036 realizeClass(result);
6037 rwlock_unlock_write(&runtimeLock);
6043 /***********************************************************************
6044 * objc_duplicateClass
6046 * Locking: acquires runtimeLock
6047 **********************************************************************/
6049 objc_duplicateClass(Class original, const char *name,
6054 rwlock_write(&runtimeLock);
6056 assert(original->isRealized());
6057 assert(!original->isMetaClass());
6059 duplicate = alloc_class_for_subclass(original, extraBytes);
6061 duplicate->initClassIsa(original->ISA());
6062 duplicate->superclass = original->superclass;
6064 duplicate->cache.setEmpty();
6066 class_rw_t *rw = (class_rw_t *)_calloc_internal(sizeof(*original->data()), 1);
6067 rw->flags = (original->data()->flags | RW_COPIED_RO | RW_REALIZING);
6068 rw->version = original->data()->version;
6069 rw->firstSubclass = nil;
6070 rw->nextSiblingClass = nil;
6072 duplicate->bits = original->bits;
6073 duplicate->setData(rw);
6075 rw->ro = (class_ro_t *)
6076 _memdup_internal(original->data()->ro, sizeof(*original->data()->ro));
6077 *(char **)&rw->ro->name = _strdup_internal(name);
6079 if (original->data()->flags & RW_METHOD_ARRAY) {
6080 rw->method_lists = (method_list_t **)
6081 _memdup_internal(original->data()->method_lists,
6082 malloc_size(original->data()->method_lists));
6083 method_list_t **mlistp;
6084 for (mlistp = rw->method_lists; *mlistp; mlistp++) {
6085 *mlistp = (method_list_t *)
6086 _memdup_internal(*mlistp, method_list_size(*mlistp));
6089 if (original->data()->method_list) {
6090 rw->method_list = (method_list_t *)
6091 _memdup_internal(original->data()->method_list,
6092 method_list_size(original->data()->method_list));
6096 // fixme dies when categories are added to the base
6097 rw->properties = original->data()->properties;
6098 rw->protocols = original->data()->protocols;
6100 if (duplicate->superclass) {
6101 addSubclass(duplicate->superclass, duplicate);
6104 // Don't methodize class - construction above is correct
6106 addNamedClass(duplicate, duplicate->data()->ro->name);
6107 addRealizedClass(duplicate);
6108 // no: duplicate->ISA == original->ISA
6109 // addRealizedMetaclass(duplicate->ISA);
6111 if (PrintConnecting) {
6112 _objc_inform("CLASS: realizing class '%s' (duplicate of %s) %p %p",
6113 name, original->nameForLogging(),
6114 (void*)duplicate, duplicate->data()->ro);
6117 duplicate->clearInfo(RW_REALIZING);
6119 rwlock_unlock_write(&runtimeLock);
6124 /***********************************************************************
6125 * objc_initializeClassPair
6126 * Locking: runtimeLock must be write-locked by the caller
6127 **********************************************************************/
6129 // &UnsetLayout is the default ivar layout during class construction
6130 static const uint8_t UnsetLayout = 0;
6132 static void objc_initializeClassPair_internal(Class superclass, const char *name, Class cls, Class meta)
6134 rwlock_assert_writing(&runtimeLock);
6136 class_ro_t *cls_ro_w, *meta_ro_w;
6138 cls->cache.setEmpty();
6139 meta->cache.setEmpty();
6141 cls->setData((class_rw_t *)_calloc_internal(sizeof(class_rw_t), 1));
6142 meta->setData((class_rw_t *)_calloc_internal(sizeof(class_rw_t), 1));
6143 cls_ro_w = (class_ro_t *)_calloc_internal(sizeof(class_ro_t), 1);
6144 meta_ro_w = (class_ro_t *)_calloc_internal(sizeof(class_ro_t), 1);
6145 cls->data()->ro = cls_ro_w;
6146 meta->data()->ro = meta_ro_w;
6150 cls->data()->flags = RW_CONSTRUCTING | RW_COPIED_RO | RW_REALIZED | RW_REALIZING;
6151 meta->data()->flags = RW_CONSTRUCTING | RW_COPIED_RO | RW_REALIZED | RW_REALIZING;
6152 cls->data()->version = 0;
6153 meta->data()->version = 7;
6155 cls_ro_w->flags = 0;
6156 meta_ro_w->flags = RO_META;
6158 cls_ro_w->flags |= RO_ROOT;
6159 meta_ro_w->flags |= RO_ROOT;
6162 cls_ro_w->instanceStart = superclass->unalignedInstanceSize();
6163 meta_ro_w->instanceStart = superclass->ISA()->unalignedInstanceSize();
6164 cls->setInstanceSize(cls_ro_w->instanceStart);
6165 meta->setInstanceSize(meta_ro_w->instanceStart);
6167 cls_ro_w->instanceStart = 0;
6168 meta_ro_w->instanceStart = (uint32_t)sizeof(objc_class);
6169 cls->setInstanceSize((uint32_t)sizeof(id)); // just an isa
6170 meta->setInstanceSize(meta_ro_w->instanceStart);
6173 cls_ro_w->name = _strdup_internal(name);
6174 meta_ro_w->name = _strdup_internal(name);
6176 cls_ro_w->ivarLayout = &UnsetLayout;
6177 cls_ro_w->weakIvarLayout = &UnsetLayout;
6179 // Connect to superclasses and metaclasses
6180 cls->initClassIsa(meta);
6182 meta->initClassIsa(superclass->ISA()->ISA());
6183 cls->superclass = superclass;
6184 meta->superclass = superclass->ISA();
6185 addSubclass(superclass, cls);
6186 addSubclass(superclass->ISA(), meta);
6188 meta->initClassIsa(meta);
6189 cls->superclass = Nil;
6190 meta->superclass = cls;
6191 addSubclass(cls, meta);
6196 /***********************************************************************
6198 * Sanity-check the superclass provided to
6199 * objc_allocateClassPair, objc_initializeClassPair, or objc_readClassPair.
6200 **********************************************************************/
6202 verifySuperclass(Class superclass, bool rootOK)
6205 // Superclass does not exist.
6206 // If subclass may be a root class, this is OK.
6207 // If subclass must not be a root class, this is bad.
6211 // Superclass must be realized.
6212 if (! superclass->isRealized()) return false;
6214 // Superclass must not be under construction.
6215 if (superclass->data()->flags & RW_CONSTRUCTING) return false;
6221 /***********************************************************************
6222 * objc_initializeClassPair
6223 **********************************************************************/
6224 Class objc_initializeClassPair(Class superclass, const char *name, Class cls, Class meta)
6226 rwlock_write(&runtimeLock);
6228 // Fail if the class name is in use.
6229 // Fail if the superclass isn't kosher.
6230 if (getClass(name) || !verifySuperclass(superclass, true/*rootOK*/)) {
6231 rwlock_unlock_write(&runtimeLock);
6235 objc_initializeClassPair_internal(superclass, name, cls, meta);
6237 rwlock_unlock_write(&runtimeLock);
6242 /***********************************************************************
6243 * objc_allocateClassPair
6245 * Locking: acquires runtimeLock
6246 **********************************************************************/
6247 Class objc_allocateClassPair(Class superclass, const char *name,
6252 rwlock_write(&runtimeLock);
6254 // Fail if the class name is in use.
6255 // Fail if the superclass isn't kosher.
6256 if (getClass(name) || !verifySuperclass(superclass, true/*rootOK*/)) {
6257 rwlock_unlock_write(&runtimeLock);
6261 // Allocate new classes.
6262 cls = alloc_class_for_subclass(superclass, extraBytes);
6263 meta = alloc_class_for_subclass(superclass, extraBytes);
6265 // fixme mangle the name if it looks swift-y?
6266 objc_initializeClassPair_internal(superclass, name, cls, meta);
6268 rwlock_unlock_write(&runtimeLock);
6274 /***********************************************************************
6275 * objc_registerClassPair
6277 * Locking: acquires runtimeLock
6278 **********************************************************************/
6279 void objc_registerClassPair(Class cls)
6281 rwlock_write(&runtimeLock);
6283 if ((cls->data()->flags & RW_CONSTRUCTED) ||
6284 (cls->ISA()->data()->flags & RW_CONSTRUCTED))
6286 _objc_inform("objc_registerClassPair: class '%s' was already "
6287 "registered!", cls->data()->ro->name);
6288 rwlock_unlock_write(&runtimeLock);
6292 if (!(cls->data()->flags & RW_CONSTRUCTING) ||
6293 !(cls->ISA()->data()->flags & RW_CONSTRUCTING))
6295 _objc_inform("objc_registerClassPair: class '%s' was not "
6296 "allocated with objc_allocateClassPair!",
6297 cls->data()->ro->name);
6298 rwlock_unlock_write(&runtimeLock);
6302 // Build ivar layouts
6304 Class supercls = cls->superclass;
6305 class_ro_t *ro_w = (class_ro_t *)cls->data()->ro;
6307 if (ro_w->ivarLayout != &UnsetLayout) {
6308 // Class builder already called class_setIvarLayout.
6310 else if (!supercls) {
6311 // Root class. Scan conservatively (should be isa ivar only).
6312 ro_w->ivarLayout = nil;
6314 else if (ro_w->ivars == nil) {
6315 // No local ivars. Use superclass's layouts.
6317 _ustrdup_internal(supercls->data()->ro->ivarLayout);
6320 // Has local ivars. Build layouts based on superclass.
6321 layout_bitmap bitmap =
6322 layout_bitmap_create(supercls->data()->ro->ivarLayout,
6323 supercls->unalignedInstanceSize(),
6324 cls->unalignedInstanceSize(), NO);
6326 for (i = 0; i < ro_w->ivars->count; i++) {
6327 ivar_t *ivar = ivar_list_nth(ro_w->ivars, i);
6328 if (!ivar->offset) continue; // anonymous bitfield
6330 layout_bitmap_set_ivar(bitmap, ivar->type, *ivar->offset);
6332 ro_w->ivarLayout = layout_string_create(bitmap);
6333 layout_bitmap_free(bitmap);
6336 if (ro_w->weakIvarLayout != &UnsetLayout) {
6337 // Class builder already called class_setWeakIvarLayout.
6339 else if (!supercls) {
6340 // Root class. No weak ivars (should be isa ivar only).
6341 ro_w->weakIvarLayout = nil;
6343 else if (ro_w->ivars == nil) {
6344 // No local ivars. Use superclass's layout.
6345 ro_w->weakIvarLayout =
6346 _ustrdup_internal(supercls->data()->ro->weakIvarLayout);
6349 // Has local ivars. Build layout based on superclass.
6350 // No way to add weak ivars yet.
6351 ro_w->weakIvarLayout =
6352 _ustrdup_internal(supercls->data()->ro->weakIvarLayout);
6356 // Clear "under construction" bit, set "done constructing" bit
6357 cls->ISA()->changeInfo(RW_CONSTRUCTED, RW_CONSTRUCTING | RW_REALIZING);
6358 cls->changeInfo(RW_CONSTRUCTED, RW_CONSTRUCTING | RW_REALIZING);
6360 // Add to named and realized classes
6361 addNamedClass(cls, cls->data()->ro->name);
6362 addRealizedClass(cls);
6363 addRealizedMetaclass(cls->ISA());
6365 rwlock_unlock_write(&runtimeLock);
6369 /***********************************************************************
6370 * objc_readClassPair()
6371 * Read a class and metaclass as written by a compiler.
6372 * Assumes the class and metaclass are not referenced by other things
6373 * that might need to be fixed up (such as categories and subclasses).
6374 * Does not call +load.
6375 * Returns the class pointer, or nil.
6377 * Locking: runtimeLock acquired by map_images
6378 **********************************************************************/
6379 Class objc_readClassPair(Class bits, const struct objc_image_info *info)
6381 rwlock_write(&runtimeLock);
6383 // No info bits are significant yet.
6386 // Fail if the class name is in use.
6387 // Fail if the superclass isn't kosher.
6388 const char *name = bits->mangledName();
6389 bool rootOK = bits->data()->flags & RO_ROOT;
6390 if (getClass(name) || !verifySuperclass(bits->superclass, rootOK)){
6391 rwlock_unlock_write(&runtimeLock);
6395 Class cls = readClass(bits, false/*bundle*/, false/*shared cache*/);
6397 // This function isn't allowed to remap anything.
6398 _objc_fatal("objc_readClassPair for class %s changed %p to %p",
6399 cls->nameForLogging(), bits, cls);
6403 rwlock_unlock_write(&runtimeLock);
6409 /***********************************************************************
6411 * Disconnect a class from other data structures.
6412 * Exception: does not remove the class from the +load list
6413 * Call this before free_class.
6414 * Locking: runtimeLock must be held by the caller.
6415 **********************************************************************/
6416 static void detach_class(Class cls, BOOL isMeta)
6418 rwlock_assert_writing(&runtimeLock);
6420 // categories not yet attached to this class
6421 category_list *cats;
6422 cats = unattachedCategoriesForClass(cls);
6423 if (cats) free(cats);
6425 // superclass's subclass list
6426 if (cls->isRealized()) {
6427 Class supercls = cls->superclass;
6429 removeSubclass(supercls, cls);
6433 // class tables and +load queue
6435 removeNamedClass(cls, cls->mangledName());
6436 removeRealizedClass(cls);
6438 removeRealizedMetaclass(cls);
6443 /***********************************************************************
6445 * Frees a class's data structures.
6446 * Call this after detach_class.
6447 * Locking: runtimeLock must be held by the caller
6448 **********************************************************************/
6449 static void free_class(Class cls)
6451 rwlock_assert_writing(&runtimeLock);
6453 if (! cls->isRealized()) return;
6457 if (cls->cache.canBeFreed()) {
6458 free(cls->cache.buckets());
6461 FOREACH_METHOD_LIST(mlist, cls, {
6462 for (i = 0; i < mlist->count; i++) {
6463 method_t *m = method_list_nth(mlist, i);
6468 if (cls->data()->flags & RW_METHOD_ARRAY) {
6469 try_free(cls->data()->method_lists);
6472 const ivar_list_t *ilist = cls->data()->ro->ivars;
6474 for (i = 0; i < ilist->count; i++) {
6475 const ivar_t *ivar = ivar_list_nth(ilist, i);
6476 try_free(ivar->offset);
6477 try_free(ivar->name);
6478 try_free(ivar->type);
6483 const protocol_list_t **plistp;
6484 for (plistp = cls->data()->protocols; plistp && *plistp; plistp++) {
6487 try_free(cls->data()->protocols);
6489 const chained_property_list *proplist = cls->data()->properties;
6491 for (i = 0; i < proplist->count; i++) {
6492 const property_t *prop = proplist->list+i;
6493 try_free(prop->name);
6494 try_free(prop->attributes);
6497 const chained_property_list *temp = proplist;
6498 proplist = proplist->next;
6503 try_free(cls->data()->ro->ivarLayout);
6504 try_free(cls->data()->ro->weakIvarLayout);
6505 try_free(cls->data()->ro->name);
6506 try_free(cls->data()->ro);
6507 try_free(cls->data());
6512 void objc_disposeClassPair(Class cls)
6514 rwlock_write(&runtimeLock);
6516 if (!(cls->data()->flags & (RW_CONSTRUCTED|RW_CONSTRUCTING)) ||
6517 !(cls->ISA()->data()->flags & (RW_CONSTRUCTED|RW_CONSTRUCTING)))
6519 // class not allocated with objc_allocateClassPair
6520 // disposing still-unregistered class is OK!
6521 _objc_inform("objc_disposeClassPair: class '%s' was not "
6522 "allocated with objc_allocateClassPair!",
6523 cls->data()->ro->name);
6524 rwlock_unlock_write(&runtimeLock);
6528 if (cls->isMetaClass()) {
6529 _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
6530 "not a class!", cls->data()->ro->name);
6531 rwlock_unlock_write(&runtimeLock);
6535 // Shouldn't have any live subclasses.
6536 if (cls->data()->firstSubclass) {
6537 _objc_inform("objc_disposeClassPair: class '%s' still has subclasses, "
6538 "including '%s'!", cls->data()->ro->name,
6539 cls->data()->firstSubclass->nameForLogging());
6541 if (cls->ISA()->data()->firstSubclass) {
6542 _objc_inform("objc_disposeClassPair: class '%s' still has subclasses, "
6543 "including '%s'!", cls->data()->ro->name,
6544 cls->ISA()->data()->firstSubclass->nameForLogging());
6547 // don't remove_class_from_loadable_list()
6548 // - it's not there and we don't have the lock
6549 detach_class(cls->ISA(), YES);
6550 detach_class(cls, NO);
6551 free_class(cls->ISA());
6554 rwlock_unlock_write(&runtimeLock);
6558 /***********************************************************************
6559 * objc_constructInstance
6560 * Creates an instance of `cls` at the location pointed to by `bytes`.
6561 * `bytes` must point to at least class_getInstanceSize(cls) bytes of
6562 * well-aligned zero-filled memory.
6563 * The new object's isa is set. Any C++ constructors are called.
6564 * Returns `bytes` if successful. Returns nil if `cls` or `bytes` is
6565 * nil, or if C++ constructors fail.
6566 * Note: class_createInstance() and class_createInstances() preflight this.
6567 **********************************************************************/
6569 objc_constructInstance(Class cls, void *bytes)
6571 if (!cls || !bytes) return nil;
6575 // Read class's info bits all at once for performance
6576 bool hasCxxCtor = cls->hasCxxCtor();
6577 bool hasCxxDtor = cls->hasCxxDtor();
6578 bool fast = cls->canAllocIndexed();
6580 if (!UseGC && fast) {
6581 obj->initInstanceIsa(cls, hasCxxDtor);
6587 return object_cxxConstructFromClass(obj, cls);
6594 /***********************************************************************
6595 * class_createInstance
6598 **********************************************************************/
6600 static __attribute__((always_inline))
6602 _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
6604 if (!cls) return nil;
6606 assert(cls->isRealized());
6608 // Read class's info bits all at once for performance
6609 bool hasCxxCtor = cls->hasCxxCtor();
6610 bool hasCxxDtor = cls->hasCxxDtor();
6611 bool fast = cls->canAllocIndexed();
6613 size_t size = cls->instanceSize(extraBytes);
6616 if (!UseGC && !zone && fast) {
6617 obj = (id)calloc(1, size);
6618 if (!obj) return nil;
6619 obj->initInstanceIsa(cls, hasCxxDtor);
6624 obj = (id)auto_zone_allocate_object(gc_zone, size,
6625 AUTO_OBJECT_SCANNED, 0, 1);
6629 obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
6631 obj = (id)calloc(1, size);
6633 if (!obj) return nil;
6635 // Use non-indexed isa on the assumption that they might be
6636 // doing something weird with the zone or RR.
6641 obj = _objc_constructOrFree(obj, cls);
6649 class_createInstance(Class cls, size_t extraBytes)
6651 return _class_createInstanceFromZone(cls, extraBytes, nil);
6655 /***********************************************************************
6656 * class_createInstances
6659 **********************************************************************/
6660 #if SUPPORT_NONPOINTER_ISA
6661 #warning fixme optimize class_createInstances
6664 class_createInstances(Class cls, size_t extraBytes,
6665 id *results, unsigned num_requested)
6667 return _class_createInstancesFromZone(cls, extraBytes, nil,
6668 results, num_requested);
6671 static BOOL classOrSuperClassesUseARR(Class cls) {
6673 if (_class_usesAutomaticRetainRelease(cls)) return true;
6674 cls = cls->superclass;
6679 static void arr_fixup_copied_references(id newObject, id oldObject)
6681 // use ARR layouts to correctly copy the references from old object to new, both strong and weak.
6682 Class cls = oldObject->ISA();
6683 for ( ; cls; cls = cls->superclass) {
6684 if (_class_usesAutomaticRetainRelease(cls)) {
6685 // FIXME: align the instance start to nearest id boundary. This currently handles the case where
6686 // the the compiler folds a leading BOOL (char, short, etc.) into the alignment slop of a superclass.
6687 size_t instanceStart = _class_getInstanceStart(cls);
6688 const uint8_t *strongLayout = class_getIvarLayout(cls);
6690 id *newPtr = (id *)((char*)newObject + instanceStart);
6692 while ((byte = *strongLayout++)) {
6693 unsigned skips = (byte >> 4);
6694 unsigned scans = (byte & 0x0F);
6697 // ensure strong references are properly retained.
6698 id value = *newPtr++;
6699 if (value) objc_retain(value);
6703 const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
6704 // fix up weak references if any.
6706 id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
6708 while ((byte = *weakLayout++)) {
6709 unsigned skips = (byte >> 4);
6710 unsigned weaks = (byte & 0x0F);
6711 newPtr += skips, oldPtr += skips;
6714 objc_storeWeak(newPtr, objc_loadWeak(oldPtr));
6723 /***********************************************************************
6724 * object_copyFromZone
6727 **********************************************************************/
6729 _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
6734 if (!oldObj) return nil;
6735 if (oldObj->isTaggedPointer()) return oldObj;
6737 size = oldObj->ISA()->instanceSize(extraBytes);
6740 obj = (id) auto_zone_allocate_object(gc_zone, size,
6741 AUTO_OBJECT_SCANNED, 0, 1);
6745 obj = (id) malloc_zone_calloc((malloc_zone_t *)zone, size, 1);
6747 obj = (id) calloc(1, size);
6749 if (!obj) return nil;
6751 // fixme this doesn't handle C++ ivars correctly (#4619414)
6752 objc_memmove_collectable(obj, oldObj, size);
6756 gc_fixup_weakreferences(obj, oldObj);
6759 if (classOrSuperClassesUseARR(obj->ISA()))
6760 arr_fixup_copied_references(obj, oldObj);
6766 /***********************************************************************
6770 **********************************************************************/
6772 object_copy(id oldObj, size_t extraBytes)
6774 return _object_copyFromZone(oldObj, extraBytes, malloc_default_zone());
6778 #if !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
6780 /***********************************************************************
6781 * class_createInstanceFromZone
6784 **********************************************************************/
6786 class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
6788 return _class_createInstanceFromZone(cls, extraBytes, zone);
6791 /***********************************************************************
6792 * object_copyFromZone
6795 **********************************************************************/
6797 object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
6799 return _object_copyFromZone(oldObj, extraBytes, zone);
6805 /***********************************************************************
6806 * objc_destructInstance
6807 * Destroys an instance without freeing memory.
6808 * Calls C++ destructors.
6809 * Calls ARR ivar cleanup.
6810 * Removes associative references.
6811 * Returns `obj`. Does nothing if `obj` is nil.
6812 * Be warned that GC DOES NOT CALL THIS. If you edit this, also edit finalize.
6813 * CoreFoundation and other clients do call this under GC.
6814 **********************************************************************/
6815 void *objc_destructInstance(id obj)
6818 // Read all of the flags at once for performance.
6819 bool cxx = obj->hasCxxDtor();
6820 bool assoc = !UseGC && obj->hasAssociatedObjects();
6821 bool dealloc = !UseGC;
6823 // This order is important.
6824 if (cxx) object_cxxDestruct(obj);
6825 if (assoc) _object_remove_assocations(obj);
6826 if (dealloc) obj->clearDeallocating();
6833 /***********************************************************************
6837 **********************************************************************/
6839 object_dispose(id obj)
6841 if (!obj) return nil;
6843 objc_destructInstance(obj);
6847 auto_zone_retain(gc_zone, obj); // gc free expects rc==1
6857 /***********************************************************************
6858 * _objc_getFreedObjectClass
6861 **********************************************************************/
6862 Class _objc_getFreedObjectClass (void)
6869 /***********************************************************************
6870 * Tagged pointer objects.
6872 * Tagged pointer objects store the class and the object value in the
6873 * object pointer; the "pointer" does not actually point to anything.
6875 * Tagged pointer objects currently use this representation:
6877 * 1 bit set if tagged, clear if ordinary object pointer
6881 * The tag index defines the object's class.
6882 * The payload format is defined by the object's class.
6884 * This representation is subject to change. Representation-agnostic SPI is:
6885 * objc-internal.h for class implementers.
6886 * objc-gdb.h for debuggers.
6887 **********************************************************************/
6888 #if !SUPPORT_TAGGED_POINTERS
6890 // These variables are always provided for debuggers.
6891 uintptr_t objc_debug_taggedpointer_mask = 0;
6892 unsigned objc_debug_taggedpointer_slot_shift = 0;
6893 uintptr_t objc_debug_taggedpointer_slot_mask = 0;
6894 unsigned objc_debug_taggedpointer_payload_lshift = 0;
6895 unsigned objc_debug_taggedpointer_payload_rshift = 0;
6896 Class objc_debug_taggedpointer_classes[1] = { nil };
6899 disableTaggedPointers() { }
6903 // The "slot" used in the class table and given to the debugger
6904 // includes the is-tagged bit. This makes objc_msgSend faster.
6906 uintptr_t objc_debug_taggedpointer_mask = TAG_MASK;
6907 unsigned objc_debug_taggedpointer_slot_shift = TAG_SLOT_SHIFT;
6908 uintptr_t objc_debug_taggedpointer_slot_mask = TAG_SLOT_MASK;
6909 unsigned objc_debug_taggedpointer_payload_lshift = TAG_PAYLOAD_LSHIFT;
6910 unsigned objc_debug_taggedpointer_payload_rshift = TAG_PAYLOAD_RSHIFT;
6911 // objc_debug_taggedpointer_classes is defined in objc-msg-*.s
6914 disableTaggedPointers()
6916 objc_debug_taggedpointer_mask = 0;
6917 objc_debug_taggedpointer_slot_shift = 0;
6918 objc_debug_taggedpointer_slot_mask = 0;
6919 objc_debug_taggedpointer_payload_lshift = 0;
6920 objc_debug_taggedpointer_payload_rshift = 0;
6924 tagSlotForTagIndex(objc_tag_index_t tag)
6926 #if SUPPORT_MSB_TAGGED_POINTERS
6929 return (tag << 1) | 1;
6934 /***********************************************************************
6935 * _objc_registerTaggedPointerClass
6936 * Set the class to use for the given tagged pointer index.
6937 * Aborts if the tag is out of range, or if the tag is already
6938 * used by some other class.
6939 **********************************************************************/
6941 _objc_registerTaggedPointerClass(objc_tag_index_t tag, Class cls)
6943 if (objc_debug_taggedpointer_mask == 0) {
6944 _objc_fatal("tagged pointers are disabled");
6947 if ((unsigned int)tag >= TAG_COUNT) {
6948 _objc_fatal("tag index %u is too large.", tag);
6951 int slot = tagSlotForTagIndex(tag);
6952 Class oldCls = objc_tag_classes[slot];
6954 if (cls && oldCls && cls != oldCls) {
6955 _objc_fatal("tag index %u used for two different classes "
6956 "(was %p %s, now %p %s)", tag,
6957 oldCls, oldCls->nameForLogging(),
6958 cls, cls->nameForLogging());
6961 objc_tag_classes[slot] = cls;
6966 void _objc_insert_tagged_isa(unsigned char slotNumber, Class isa)
6968 return _objc_registerTaggedPointerClass((objc_tag_index_t)slotNumber, isa);
6972 /***********************************************************************
6973 * _objc_getClassForTag
6974 * Returns the class that is using the given tagged pointer tag.
6975 * Returns nil if no class is using that tag or the tag is out of range.
6976 **********************************************************************/
6978 _objc_getClassForTag(objc_tag_index_t tag)
6980 if ((unsigned int)tag >= TAG_COUNT) return nil;
6981 return objc_tag_classes[tagSlotForTagIndex(tag)];
6989 OBJC_EXTERN void objc_msgSend_fixup(void);
6990 OBJC_EXTERN void objc_msgSendSuper2_fixup(void);
6991 OBJC_EXTERN void objc_msgSend_stret_fixup(void);
6992 OBJC_EXTERN void objc_msgSendSuper2_stret_fixup(void);
6993 #if defined(__i386__) || defined(__x86_64__)
6994 OBJC_EXTERN void objc_msgSend_fpret_fixup(void);
6996 #if defined(__x86_64__)
6997 OBJC_EXTERN void objc_msgSend_fp2ret_fixup(void);
7000 OBJC_EXTERN void objc_msgSend_fixedup(void);
7001 OBJC_EXTERN void objc_msgSendSuper2_fixedup(void);
7002 OBJC_EXTERN void objc_msgSend_stret_fixedup(void);
7003 OBJC_EXTERN void objc_msgSendSuper2_stret_fixedup(void);
7004 #if defined(__i386__) || defined(__x86_64__)
7005 OBJC_EXTERN void objc_msgSend_fpret_fixedup(void);
7007 #if defined(__x86_64__)
7008 OBJC_EXTERN void objc_msgSend_fp2ret_fixedup(void);
7011 /***********************************************************************
7013 * Repairs an old vtable dispatch call site.
7014 * vtable dispatch itself is not supported.
7015 **********************************************************************/
7017 fixupMessageRef(message_ref_t *msg)
7019 msg->sel = sel_registerName((const char *)msg->sel);
7021 if (ignoreSelector(msg->sel)) {
7022 // ignored selector - bypass dispatcher
7023 msg->imp = (IMP)&_objc_ignored_method;
7025 else if (msg->imp == &objc_msgSend_fixup) {
7026 if (msg->sel == SEL_alloc) {
7027 msg->imp = (IMP)&objc_alloc;
7028 } else if (msg->sel == SEL_allocWithZone) {
7029 msg->imp = (IMP)&objc_allocWithZone;
7030 } else if (msg->sel == SEL_retain) {
7031 msg->imp = (IMP)&objc_retain;
7032 } else if (msg->sel == SEL_release) {
7033 msg->imp = (IMP)&objc_release;
7034 } else if (msg->sel == SEL_autorelease) {
7035 msg->imp = (IMP)&objc_autorelease;
7037 msg->imp = &objc_msgSend_fixedup;
7040 else if (msg->imp == &objc_msgSendSuper2_fixup) {
7041 msg->imp = &objc_msgSendSuper2_fixedup;
7043 else if (msg->imp == &objc_msgSend_stret_fixup) {
7044 msg->imp = &objc_msgSend_stret_fixedup;
7046 else if (msg->imp == &objc_msgSendSuper2_stret_fixup) {
7047 msg->imp = &objc_msgSendSuper2_stret_fixedup;
7049 #if defined(__i386__) || defined(__x86_64__)
7050 else if (msg->imp == &objc_msgSend_fpret_fixup) {
7051 msg->imp = &objc_msgSend_fpret_fixedup;
7054 #if defined(__x86_64__)
7055 else if (msg->imp == &objc_msgSend_fp2ret_fixup) {
7056 msg->imp = &objc_msgSend_fp2ret_fixedup;
7066 static Class setSuperclass(Class cls, Class newSuper)
7070 rwlock_assert_writing(&runtimeLock);
7072 assert(cls->isRealized());
7073 assert(newSuper->isRealized());
7075 oldSuper = cls->superclass;
7076 removeSubclass(oldSuper, cls);
7077 removeSubclass(oldSuper->ISA(), cls->ISA());
7079 cls->superclass = newSuper;
7080 cls->ISA()->superclass = newSuper->ISA();
7081 addSubclass(newSuper, cls);
7082 addSubclass(newSuper->ISA(), cls->ISA());
7084 // Flush subclass's method caches.
7085 // If subclass is not yet +initialized then its cache will be empty.
7086 // Otherwise this is very slow for sel-side caches.
7087 if (cls->isInitialized() || cls->ISA()->isInitialized()) {
7095 Class class_setSuperclass(Class cls, Class newSuper)
7099 rwlock_write(&runtimeLock);
7100 oldSuper = setSuperclass(cls, newSuper);
7101 rwlock_unlock_write(&runtimeLock);