2 * Copyright (c) 1999-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 old-ABI classes, methods, and categories.
27 **********************************************************************/
31 #include "objc-private.h"
32 #include "objc-runtime-old.h"
34 // Freed objects have their isa set to point to this dummy class.
35 // This avoids the need to check for Nil classes in the messenger.
36 static const struct old_class freedObjectClass =
46 (Cache) &_objc_empty_cache, // cache
53 /***********************************************************************
54 * _class_getFreedObjectClass. Return a pointer to the dummy freed
55 * object class. Freed objects get their isa pointers replaced with
56 * a pointer to the freedObjectClass, so that we can catch usages of
58 **********************************************************************/
59 static Class _class_getFreedObjectClass(void)
61 return (Class)&freedObjectClass;
65 /***********************************************************************
66 * _objc_getFreedObjectClass. Return a pointer to the dummy freed
67 * object class. Freed objects get their isa pointers replaced with
68 * a pointer to the freedObjectClass, so that we can catch usages of
70 **********************************************************************/
71 Class _objc_getFreedObjectClass(void)
73 return _class_getFreedObjectClass();
77 static void allocateExt(struct old_class *cls)
79 if (! (cls->info & CLS_EXT)) {
80 _objc_inform("class '%s' needs to be recompiled", cls->name);
84 uint32_t size = (uint32_t)sizeof(struct old_class_ext);
85 cls->ext = _calloc_internal(size, 1);
86 cls->ext->size = size;
91 static inline struct old_method *_findNamedMethodInList(struct old_method_list * mlist, const char *meth_name) {
93 if (!mlist) return NULL;
94 if (ignoreSelectorNamed(meth_name)) return NULL;
95 for (i = 0; i < mlist->method_count; i++) {
96 struct old_method *m = &mlist->method_list[i];
97 if (0 == strcmp((const char *)(m->method_name), meth_name)) {
105 /***********************************************************************
106 * Method list fixup markers.
107 * mlist->obsolete == fixed_up_method_list marks method lists with real SELs
108 * versus method lists with un-uniqued char*.
109 * PREOPTIMIZED VERSION:
110 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP
111 * dyld shared cache sets this for method lists it preoptimizes.
112 * UN-PREOPTIMIZED VERSION
113 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP_outside_dyld
114 * dyld shared cache uses OBJC_FIXED_UP, but those aren't trusted.
115 **********************************************************************/
116 #define OBJC_FIXED_UP ((void *)1771)
117 #define OBJC_FIXED_UP_outside_dyld ((void *)1773)
118 static void *fixed_up_method_list = OBJC_FIXED_UP;
120 // sel_init() decided that selectors in the dyld shared cache are untrustworthy
121 void disableSharedCacheOptimizations(void)
123 fixed_up_method_list = OBJC_FIXED_UP_outside_dyld;
126 /***********************************************************************
127 * fixupSelectorsInMethodList
128 * Uniques selectors in the given method list.
129 * Also replaces imps for GC-ignored selectors
130 * The given method list must be non-NULL and not already fixed-up.
131 * If the class was loaded from a bundle:
132 * fixes up the given list in place with heap-allocated selector strings
133 * If the class was not from a bundle:
134 * allocates a copy of the method list, fixes up the copy, and returns
135 * the copy. The given list is unmodified.
137 * If cls is already in use, methodListLock must be held by the caller.
138 **********************************************************************/
139 static struct old_method_list *fixupSelectorsInMethodList(struct old_class *cls, struct old_method_list *mlist)
143 struct old_method *method;
144 struct old_method_list *old_mlist;
146 if ( ! mlist ) return NULL;
147 if ( mlist->obsolete == fixed_up_method_list ) {
150 BOOL isBundle = (cls->info & CLS_FROM_BUNDLE) ? YES : NO;
153 size = sizeof(struct old_method_list) - sizeof(struct old_method) + old_mlist->method_count * sizeof(struct old_method);
154 mlist = _malloc_internal(size);
155 memmove(mlist, old_mlist, size);
157 // Mach-O bundles are fixed up in place.
158 // This prevents leaks when a bundle is unloaded.
161 for ( i = 0; i < mlist->method_count; i += 1 ) {
162 method = &mlist->method_list[i];
163 method->method_name =
164 sel_registerNameNoLock((const char *)method->method_name, isBundle); // Always copy selector data from bundles.
166 if (ignoreSelector(method->method_name)) {
167 method->method_imp = (IMP)&_objc_ignored_method;
171 mlist->obsolete = fixed_up_method_list;
177 /***********************************************************************
179 * Returns successive method lists from the given class.
180 * Method lists are returned in method search order (i.e. highest-priority
181 * implementations first).
182 * All necessary method list fixups are performed, so the
183 * returned method list is fully-constructed.
185 * If cls is already in use, methodListLock must be held by the caller.
186 * For full thread-safety, methodListLock must be continuously held by the
187 * caller across all calls to nextMethodList(). If the lock is released,
188 * the bad results listed in class_nextMethodList() may occur.
190 * void *iterator = NULL;
191 * struct old_method_list *mlist;
192 * mutex_lock(&methodListLock);
193 * while ((mlist = nextMethodList(cls, &iterator))) {
194 * // do something with mlist
196 * mutex_unlock(&methodListLock);
197 **********************************************************************/
198 static struct old_method_list *nextMethodList(struct old_class *cls,
201 uintptr_t index = *(uintptr_t *)it;
202 struct old_method_list **resultp;
205 // First call to nextMethodList.
206 if (!cls->methodLists) {
208 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
209 resultp = (struct old_method_list **)&cls->methodLists;
211 resultp = &cls->methodLists[0];
212 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
217 // Subsequent call to nextMethodList.
218 if (!cls->methodLists) {
220 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
223 resultp = &cls->methodLists[index];
224 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
230 // resultp now is NULL, meaning there are no more method lists,
231 // OR the address of the method list pointer to fix up and return.
235 *resultp = fixupSelectorsInMethodList(cls, *resultp);
237 *it = (void *)(index + 1);
246 /* These next three functions are the heart of ObjC method lookup.
247 * If the class is currently in use, methodListLock must be held by the caller.
249 static inline struct old_method *_findMethodInList(struct old_method_list * mlist, SEL sel) {
251 if (!mlist) return NULL;
252 for (i = 0; i < mlist->method_count; i++) {
253 struct old_method *m = &mlist->method_list[i];
254 if (m->method_name == sel) {
261 static inline struct old_method * _findMethodInClass(struct old_class *cls, SEL sel) __attribute__((always_inline));
262 static inline struct old_method * _findMethodInClass(struct old_class *cls, SEL sel) {
263 // Flattened version of nextMethodList(). The optimizer doesn't
264 // do a good job with hoisting the conditionals out of the loop.
265 // Conceptually, this looks like:
266 // while ((mlist = nextMethodList(cls, &iterator))) {
267 // struct old_method *m = _findMethodInList(mlist, sel);
271 if (!cls->methodLists) {
275 else if (cls->info & CLS_NO_METHOD_ARRAY) {
277 struct old_method_list **mlistp;
278 mlistp = (struct old_method_list **)&cls->methodLists;
279 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
280 return _findMethodInList(*mlistp, sel);
283 // Multiple method lists.
284 struct old_method_list **mlistp;
285 for (mlistp = cls->methodLists;
286 *mlistp != NULL && *mlistp != END_OF_METHODS_LIST;
289 struct old_method *m;
290 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
291 m = _findMethodInList(*mlistp, sel);
298 static inline struct old_method * _getMethod(struct old_class *cls, SEL sel) {
299 for (; cls; cls = cls->super_class) {
300 struct old_method *m;
301 m = _findMethodInClass(cls, sel);
308 // fixme for gc debugging temporary use
309 IMP findIMPInClass(struct old_class *cls, SEL sel)
311 struct old_method *m = _findMethodInClass(cls, sel);
312 if (m) return m->method_imp;
317 /***********************************************************************
319 **********************************************************************/
320 static void _freedHandler(id obj, SEL sel)
322 __objc_error (obj, "message %s sent to freed object=%p",
323 sel_getName(sel), obj);
327 /***********************************************************************
328 * ABI-specific lookUpMethod helpers.
329 **********************************************************************/
330 void lockForMethodLookup(void)
332 mutex_lock(&methodListLock);
334 void unlockForMethodLookup(void)
336 mutex_unlock(&methodListLock);
338 IMP prepareForMethodLookup(Class cls, SEL sel, BOOL init, id obj)
340 mutex_assert_unlocked(&methodListLock);
342 // Check for freed class
343 if (cls == _class_getFreedObjectClass())
344 return (IMP) _freedHandler;
346 if (init && !_class_isInitialized(cls)) {
347 _class_initialize (_class_getNonMetaClass(cls, obj));
348 // If sel == initialize, _class_initialize will send +initialize and
349 // then the messenger will send +initialize again after this
350 // procedure finishes. Of course, if this is not being called
351 // from the messenger then it won't happen. 2778172
358 /***********************************************************************
359 * class_getVariable. Return the named instance variable.
360 **********************************************************************/
362 Ivar _class_getVariable(Class cls_gen, const char *name, Class *memberOf)
364 struct old_class *cls = oldcls(cls_gen);
366 for (; cls != Nil; cls = cls->super_class) {
369 // Skip class having no ivars
370 if (!cls->ivars) continue;
372 for (i = 0; i < cls->ivars->ivar_count; i++) {
373 // Check this ivar's name. Be careful because the
374 // compiler generates ivar entries with NULL ivar_name
375 // (e.g. for anonymous bit fields).
376 struct old_ivar *ivar = &cls->ivars->ivar_list[i];
377 if (ivar->ivar_name && 0 == strcmp(name, ivar->ivar_name)) {
378 if (memberOf) *memberOf = (Class)cls;
389 struct old_property *
390 property_list_nth(const struct old_property_list *plist, uint32_t i)
392 return (struct old_property *)(i*plist->entsize + (char *)&plist->first);
395 struct old_property **
396 copyPropertyList(struct old_property_list *plist, unsigned int *outCount)
398 struct old_property **result = NULL;
399 unsigned int count = 0;
402 count = plist->count;
407 result = malloc((count+1) * sizeof(struct old_property *));
409 for (i = 0; i < count; i++) {
410 result[i] = property_list_nth(plist, i);
415 if (outCount) *outCount = count;
420 static struct old_property_list *
421 nextPropertyList(struct old_class *cls, uintptr_t *indexp)
423 struct old_property_list *result = NULL;
425 mutex_assert_locked(&classLock);
426 if (! ((cls->info & CLS_EXT) && cls->ext)) {
429 } else if (!cls->ext->propertyLists) {
432 } else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
433 // Only one property list
435 result = (struct old_property_list *)cls->ext->propertyLists;
440 // More than one property list
441 result = cls->ext->propertyLists[*indexp];
454 /***********************************************************************
455 * class_getIvarLayout
456 * NULL means all-scanned. "" means non-scanned.
457 **********************************************************************/
459 class_getIvarLayout(Class cls_gen)
461 struct old_class *cls = oldcls(cls_gen);
462 if (cls && (cls->info & CLS_EXT)) {
463 return cls->ivar_layout;
465 return NULL; // conservative scan
470 /***********************************************************************
471 * class_getWeakIvarLayout
472 * NULL means no weak ivars.
473 **********************************************************************/
475 class_getWeakIvarLayout(Class cls_gen)
477 struct old_class *cls = oldcls(cls_gen);
478 if (cls && (cls->info & CLS_EXT) && cls->ext) {
479 return cls->ext->weak_ivar_layout;
481 return NULL; // no weak ivars
486 /***********************************************************************
487 * class_setIvarLayout
488 * NULL means all-scanned. "" means non-scanned.
489 **********************************************************************/
490 void class_setIvarLayout(Class cls_gen, const uint8_t *layout)
492 struct old_class *cls = oldcls(cls_gen);
495 if (! (cls->info & CLS_EXT)) {
496 _objc_inform("class '%s' needs to be recompiled", cls->name);
501 cls->ivar_layout = _ustrdup_internal(layout);
504 // SPI: Instance-specific object layout.
506 void _class_setIvarLayoutAccessor(Class cls_gen, const uint8_t* (*accessor) (id object)) {
507 struct old_class *cls = oldcls(cls_gen);
510 if (! (cls->info & CLS_EXT)) {
511 _objc_inform("class '%s' needs to be recompiled", cls->name);
516 cls->ivar_layout = (const uint8_t *)accessor;
517 _class_setInfo(cls_gen, CLS_HAS_INSTANCE_SPECIFIC_LAYOUT);
520 const uint8_t *_object_getIvarLayout(Class cls_gen, id object) {
521 struct old_class *cls = oldcls(cls_gen);
522 if (cls && (cls->info & CLS_EXT)) {
523 const uint8_t* layout = cls->ivar_layout;
524 if (cls->info & CLS_HAS_INSTANCE_SPECIFIC_LAYOUT) {
525 const uint8_t* (*accessor) (id object) = (const uint8_t* (*)(id))layout;
526 layout = accessor(object);
534 /***********************************************************************
535 * class_setWeakIvarLayout
536 * NULL means no weak ivars.
537 **********************************************************************/
538 void class_setWeakIvarLayout(Class cls_gen, const uint8_t *layout)
540 struct old_class *cls = oldcls(cls_gen);
543 mutex_lock(&classLock);
548 cls->ext->weak_ivar_layout = _ustrdup_internal(layout);
550 mutex_unlock(&classLock);
554 /***********************************************************************
556 * Atomically sets and clears some bits in cls's info field.
557 * set and clear must not overlap.
558 **********************************************************************/
559 void _class_changeInfo(Class cls, long set, long clear)
561 struct old_class *old = oldcls(cls);
566 newinfo = (oldinfo | set) & ~clear;
567 } while (! OSAtomicCompareAndSwapLong(oldinfo, newinfo, &old->info));
571 /***********************************************************************
573 * Returns YES iff all set bits in get are also set in cls's info field.
574 **********************************************************************/
575 BOOL _class_getInfo(Class cls, int get)
577 struct old_class *old = oldcls(cls);
578 return ((old->info & get) == get) ? YES : NO;
582 /***********************************************************************
584 * Atomically sets some bits in cls's info field.
585 **********************************************************************/
586 void _class_setInfo(Class cls, long set)
588 _class_changeInfo(cls, set, 0);
592 /***********************************************************************
594 * Atomically clears some bits in cls's info field.
595 **********************************************************************/
596 void _class_clearInfo(Class cls, long clear)
598 _class_changeInfo(cls, 0, clear);
602 /***********************************************************************
604 * Return YES if cls is currently being initialized.
605 * The initializing bit is stored in the metaclass only.
606 **********************************************************************/
607 BOOL _class_isInitializing(Class cls)
609 return _class_getInfo(_class_getMeta(cls), CLS_INITIALIZING);
613 /***********************************************************************
615 * Return YES if cls is already initialized.
616 * The initialized bit is stored in the metaclass only.
617 **********************************************************************/
618 BOOL _class_isInitialized(Class cls)
620 return _class_getInfo(_class_getMeta(cls), CLS_INITIALIZED);
624 /***********************************************************************
626 * Mark cls as initialization in progress.
627 **********************************************************************/
628 void _class_setInitializing(Class cls)
630 _class_setInfo(_class_getMeta(cls), CLS_INITIALIZING);
634 /***********************************************************************
636 * Atomically mark cls as initialized and not initializing.
637 **********************************************************************/
638 void _class_setInitialized(Class cls)
640 _class_changeInfo(_class_getMeta(cls), CLS_INITIALIZED, CLS_INITIALIZING);
644 /***********************************************************************
645 * class_setVersion. Record the specified version with the class.
646 **********************************************************************/
647 void class_setVersion(Class cls, int version)
650 cls->version = version;
653 /***********************************************************************
654 * class_getVersion. Return the version recorded with the class.
655 **********************************************************************/
656 int class_getVersion(Class cls)
659 return (int)cls->version;
663 Class _class_getMeta(Class cls)
665 if (_class_getInfo(cls, CLS_META)) return cls;
666 else return ((id)cls)->isa;
669 BOOL _class_isMetaClass(Class cls)
672 return _class_getInfo(cls, CLS_META);
676 /***********************************************************************
677 * _class_getNonMetaClass.
678 * Return the ordinary class for this class or metaclass.
679 * Used by +initialize.
680 **********************************************************************/
681 Class _class_getNonMetaClass(Class cls, id obj __unused)
684 if (_class_isMetaClass(cls)) {
685 if (strncmp(_class_getName(cls), "_%", 2) == 0) {
686 // Posee's meta's name is smashed and isn't in the class_hash,
687 // so objc_getClass doesn't work.
688 const char *baseName = strchr(_class_getName(cls), '%'); // get posee's real name
689 cls = (Class)objc_getClass(baseName);
691 cls = (Class)objc_getClass(_class_getName(cls));
700 Class _class_getSuperclass(Class cls)
702 if (!cls) return nil;
703 return (Class)cls->super_class;
707 Cache _class_getCache(Class cls)
712 void _class_setCache(Class cls, Cache cache)
717 size_t _class_getInstanceSize(Class cls)
720 return (cls->instance_size + WORD_MASK) & ~WORD_MASK;
723 const char * _class_getName(Class cls)
725 if (!cls) return "nil";
731 const char *_category_getName(Category cat)
733 return oldcategory(cat)->category_name;
736 const char *_category_getClassName(Category cat)
738 return oldcategory(cat)->class_name;
741 Class _category_getClass(Category cat)
743 return (Class)objc_getClass(oldcategory(cat)->class_name);
746 IMP _category_getLoadMethod(Category cat)
748 struct old_method_list *mlist = oldcategory(cat)->class_methods;
750 return lookupNamedMethodInMethodList(mlist, "load");
758 /***********************************************************************
759 * class_nextMethodList.
760 * External version of nextMethodList().
762 * This function is not fully thread-safe. A series of calls to
763 * class_nextMethodList() may fail if methods are added to or removed
764 * from the class between calls.
765 * If methods are added between calls to class_nextMethodList(), it may
766 * return previously-returned method lists again, and may fail to return
768 * If methods are removed between calls to class_nextMethodList(), it may
769 * omit surviving method lists or simply crash.
770 **********************************************************************/
771 OBJC_EXPORT struct objc_method_list *class_nextMethodList(Class cls, void **it)
773 struct old_method_list *result;
775 OBJC_WARN_DEPRECATED;
777 mutex_lock(&methodListLock);
778 result = nextMethodList(oldcls(cls), it);
779 mutex_unlock(&methodListLock);
780 return (struct objc_method_list *)result;
784 /***********************************************************************
787 * Formerly class_addInstanceMethods ()
788 **********************************************************************/
789 OBJC_EXPORT void class_addMethods(Class cls, struct objc_method_list *meths)
791 OBJC_WARN_DEPRECATED;
794 mutex_lock(&methodListLock);
795 _objc_insertMethods(oldcls(cls), (struct old_method_list *)meths, NULL);
796 mutex_unlock(&methodListLock);
798 // Must flush when dynamically adding methods. No need to flush
799 // all the class method caches. If cls is a meta class, though,
800 // this will still flush it and any of its sub-meta classes.
801 flush_caches (cls, NO);
805 /***********************************************************************
806 * class_removeMethods.
807 **********************************************************************/
808 OBJC_EXPORT void class_removeMethods(Class cls, struct objc_method_list *meths)
810 OBJC_WARN_DEPRECATED;
812 // Remove the methods
813 mutex_lock(&methodListLock);
814 _objc_removeMethods(oldcls(cls), (struct old_method_list *)meths);
815 mutex_unlock(&methodListLock);
817 // Must flush when dynamically removing methods. No need to flush
818 // all the class method caches. If cls is a meta class, though,
819 // this will still flush it and any of its sub-meta classes.
820 flush_caches (cls, NO);
823 /***********************************************************************
824 * lookupNamedMethodInMethodList
825 * Only called to find +load/-.cxx_construct/-.cxx_destruct methods,
826 * without fixing up the entire method list.
827 * The class is not yet in use, so methodListLock is not taken.
828 **********************************************************************/
829 IMP lookupNamedMethodInMethodList(struct old_method_list *mlist, const char *meth_name)
831 struct old_method *m;
832 m = meth_name ? _findNamedMethodInList(mlist, meth_name) : NULL;
833 return (m ? m->method_imp : NULL);
836 Method _class_getMethod(Class cls, SEL sel)
840 mutex_lock(&methodListLock);
841 result = (Method)_getMethod(oldcls(cls), sel);
842 mutex_unlock(&methodListLock);
847 Method _class_getMethodNoSuper(Class cls, SEL sel)
851 mutex_lock(&methodListLock);
852 result = (Method)_findMethodInClass(oldcls(cls), sel);
853 mutex_unlock(&methodListLock);
858 Method _class_getMethodNoSuper_nolock(Class cls, SEL sel)
860 mutex_assert_locked(&methodListLock);
861 return (Method)_findMethodInClass(oldcls(cls), sel);
865 BOOL class_conformsToProtocol(Class cls_gen, Protocol *proto_gen)
867 struct old_class *cls = oldcls(cls_gen);
868 struct old_protocol *proto = oldprotocol(proto_gen);
870 if (!cls_gen) return NO;
871 if (!proto) return NO;
873 if (cls->isa->version >= 3) {
874 struct old_protocol_list *list;
875 for (list = cls->protocols; list != NULL; list = list->next) {
877 for (i = 0; i < list->count; i++) {
878 if (list->list[i] == proto) return YES;
879 if (protocol_conformsToProtocol((Protocol *)list->list[i], proto_gen)) return YES;
881 if (cls->isa->version <= 4) break;
888 static NXMapTable * posed_class_hash = NULL;
890 /***********************************************************************
892 **********************************************************************/
893 Class _objc_getOrigClass(const char *name)
897 // Look for class among the posers
899 mutex_lock(&classLock);
900 if (posed_class_hash)
901 ret = (Class) NXMapGet (posed_class_hash, name);
902 mutex_unlock(&classLock);
906 // Not a poser. Do a normal lookup.
907 ret = (Class)objc_getClass (name);
909 _objc_inform ("class `%s' not linked into application", name);
914 Class objc_getOrigClass(const char *name)
916 OBJC_WARN_DEPRECATED;
917 return _objc_getOrigClass(name);
920 /***********************************************************************
921 * _objc_addOrigClass. This function is only used from class_poseAs.
922 * Registers the original class names, before they get obscured by
923 * posing, so that [super ..] will work correctly from categories
924 * in posing classes and in categories in classes being posed for.
925 **********************************************************************/
926 static void _objc_addOrigClass (struct old_class *origClass)
928 mutex_lock(&classLock);
930 // Create the poser's hash table on first use
931 if (!posed_class_hash)
933 posed_class_hash = NXCreateMapTableFromZone (NXStrValueMapPrototype,
935 _objc_internal_zone ());
938 // Add the named class iff it is not already there (or collides?)
939 if (NXMapGet (posed_class_hash, origClass->name) == 0)
940 NXMapInsert (posed_class_hash, origClass->name, origClass);
942 mutex_unlock(&classLock);
946 /***********************************************************************
947 * change_class_references
948 * Change classrefs and superclass pointers from original to imposter
949 * But if copy!=nil, don't change copy->super_class.
950 * If changeSuperRefs==YES, also change [super message] classrefs.
951 * Used by class_poseAs and objc_setFutureClass
952 * classLock must be locked.
953 **********************************************************************/
954 void change_class_references(struct old_class *imposter,
955 struct old_class *original,
956 struct old_class *copy,
957 BOOL changeSuperRefs)
960 struct old_class *clsObject;
963 // Change all subclasses of the original to point to the imposter.
964 state = NXInitHashState (class_hash);
965 while (NXNextHashState (class_hash, &state, (void **) &clsObject))
967 while ((clsObject) && (clsObject != imposter) &&
970 if (clsObject->super_class == original)
972 clsObject->super_class = imposter;
973 clsObject->isa->super_class = imposter->isa;
974 // We must flush caches here!
978 clsObject = clsObject->super_class;
982 // Replace the original with the imposter in all class refs
983 // Major loop - process all headers
984 for (hInfo = FirstHeader; hInfo != NULL; hInfo = hInfo->next)
986 struct old_class **cls_refs;
990 // Fix class refs associated with this header
991 cls_refs = _getObjcClassRefs(hInfo, &refCount);
993 for (index = 0; index < refCount; index += 1) {
994 if (cls_refs[index] == original) {
995 cls_refs[index] = imposter;
1003 /***********************************************************************
1006 * !!! class_poseAs () does not currently flush any caches.
1007 **********************************************************************/
1008 Class class_poseAs(Class imposter_gen, Class original_gen)
1010 struct old_class *imposter = oldcls(imposter_gen);
1011 struct old_class *original = oldcls(original_gen);
1012 char * imposterNamePtr;
1013 struct old_class * copy;
1015 OBJC_WARN_DEPRECATED;
1017 // Trivial case is easy
1018 if (imposter_gen == original_gen)
1019 return imposter_gen;
1021 // Imposter must be an immediate subclass of the original
1022 if (imposter->super_class != original) {
1023 __objc_error((id)imposter_gen,
1024 "[%s poseAs:%s]: target not immediate superclass",
1025 imposter->name, original->name);
1028 // Can't pose when you have instance variables (how could it work?)
1029 if (imposter->ivars) {
1030 __objc_error((id)imposter_gen,
1031 "[%s poseAs:%s]: %s defines new instance variables",
1032 imposter->name, original->name, imposter->name);
1035 // Build a string to use to replace the name of the original class.
1037 # define imposterNamePrefix "_%"
1038 imposterNamePtr = _malloc_internal(strlen(original->name) + strlen(imposterNamePrefix) + 1);
1039 strcpy(imposterNamePtr, imposterNamePrefix);
1040 strcat(imposterNamePtr, original->name);
1041 # undef imposterNamePrefix
1043 asprintf(&imposterNamePtr, "_%%%s", original->name);
1046 // We lock the class hashtable, so we are thread safe with respect to
1047 // calls to objc_getClass (). However, the class names are not
1048 // changed atomically, nor are all of the subclasses updated
1049 // atomically. I have ordered the operations so that you will
1050 // never crash, but you may get inconsistent results....
1052 // Register the original class so that [super ..] knows
1053 // exactly which classes are the "original" classes.
1054 _objc_addOrigClass (original);
1055 _objc_addOrigClass (imposter);
1057 // Copy the imposter, so that the imposter can continue
1058 // its normal life in addition to changing the behavior of
1059 // the original. As a hack we don't bother to copy the metaclass.
1060 // For some reason we modify the original rather than the copy.
1061 copy = (struct old_class *)_malloc_internal(sizeof(struct old_class));
1062 memmove(copy, imposter, sizeof(struct old_class));
1064 mutex_lock(&classLock);
1066 // Remove both the imposter and the original class.
1067 NXHashRemove (class_hash, imposter);
1068 NXHashRemove (class_hash, original);
1070 NXHashInsert (class_hash, copy);
1071 objc_addRegisteredClass((Class)copy); // imposter & original will rejoin later, just track the new guy
1073 // Mark the imposter as such
1074 _class_setInfo((Class)imposter, CLS_POSING);
1075 _class_setInfo((Class)imposter->isa, CLS_POSING);
1077 // Change the name of the imposter to that of the original class.
1078 imposter->name = original->name;
1079 imposter->isa->name = original->isa->name;
1081 // Also copy the version field to avoid archiving problems.
1082 imposter->version = original->version;
1084 // Change classrefs and superclass pointers
1085 // Don't change copy->super_class
1086 // Don't change [super ...] messages
1087 change_class_references(imposter, original, copy, NO);
1089 // Change the name of the original class.
1090 original->name = imposterNamePtr + 1;
1091 original->isa->name = imposterNamePtr;
1093 // Restore the imposter and the original class with their new names.
1094 NXHashInsert (class_hash, imposter);
1095 NXHashInsert (class_hash, original);
1097 mutex_unlock(&classLock);
1099 return imposter_gen;
1103 /***********************************************************************
1104 * flush_caches. Flush the instance and optionally class method caches
1105 * of cls and all its subclasses.
1107 * Specifying Nil for the class "all classes."
1108 **********************************************************************/
1109 void flush_caches(Class target_gen, BOOL flush_meta)
1112 struct old_class *target = oldcls(target_gen);
1113 struct old_class *clsObject;
1114 #ifdef OBJC_INSTRUMENTED
1115 unsigned int classesVisited;
1116 unsigned int subclassCount;
1119 mutex_lock(&classLock);
1120 mutex_lock(&cacheUpdateLock);
1122 // Leaf classes are fastest because there are no subclass caches to flush.
1124 if (target && (target->info & CLS_LEAF)) {
1125 _cache_flush ((Class)target);
1128 mutex_unlock(&cacheUpdateLock);
1129 mutex_unlock(&classLock);
1131 } else if (target->isa && (target->isa->info & CLS_LEAF)) {
1132 _cache_flush ((Class)target->isa);
1133 mutex_unlock(&cacheUpdateLock);
1134 mutex_unlock(&classLock);
1137 // Reset target and handle it by one of the methods below.
1138 target = target->isa;
1144 state = NXInitHashState(class_hash);
1146 // Handle nil and root instance class specially: flush all
1147 // instance and class method caches. Nice that this
1148 // loop is linear vs the N-squared loop just below.
1149 if (!target || !target->super_class)
1151 #ifdef OBJC_INSTRUMENTED
1152 LinearFlushCachesCount += 1;
1156 // Traverse all classes in the hash table
1157 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1159 struct old_class *metaClsObject;
1160 #ifdef OBJC_INSTRUMENTED
1161 classesVisited += 1;
1164 // Skip class that is known not to be a subclass of this root
1165 // (the isa pointer of any meta class points to the meta class
1167 // NOTE: When is an isa pointer of a hash tabled class ever nil?
1168 metaClsObject = clsObject->isa;
1169 if (target && metaClsObject && target->isa != metaClsObject->isa) {
1173 #ifdef OBJC_INSTRUMENTED
1177 _cache_flush ((Class)clsObject);
1178 if (flush_meta && metaClsObject != NULL) {
1179 _cache_flush ((Class)metaClsObject);
1182 #ifdef OBJC_INSTRUMENTED
1183 LinearFlushCachesVisitedCount += classesVisited;
1184 if (classesVisited > MaxLinearFlushCachesVisitedCount)
1185 MaxLinearFlushCachesVisitedCount = classesVisited;
1186 IdealFlushCachesCount += subclassCount;
1187 if (subclassCount > MaxIdealFlushCachesCount)
1188 MaxIdealFlushCachesCount = subclassCount;
1191 mutex_unlock(&cacheUpdateLock);
1192 mutex_unlock(&classLock);
1196 // Outer loop - flush any cache that could now get a method from
1197 // cls (i.e. the cache associated with cls and any of its subclasses).
1198 #ifdef OBJC_INSTRUMENTED
1199 NonlinearFlushCachesCount += 1;
1203 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1205 struct old_class *clsIter;
1207 #ifdef OBJC_INSTRUMENTED
1208 NonlinearFlushCachesClassCount += 1;
1211 // Inner loop - Process a given class
1212 clsIter = clsObject;
1216 #ifdef OBJC_INSTRUMENTED
1217 classesVisited += 1;
1219 // Flush clsObject instance method cache if
1220 // clsObject is a subclass of cls, or is cls itself
1221 // Flush the class method cache if that was asked for
1222 if (clsIter == target)
1224 #ifdef OBJC_INSTRUMENTED
1227 _cache_flush ((Class)clsObject);
1229 _cache_flush ((Class)clsObject->isa);
1235 // Flush clsObject class method cache if cls is
1236 // the meta class of clsObject or of one
1237 // of clsObject's superclasses
1238 else if (clsIter->isa == target)
1240 #ifdef OBJC_INSTRUMENTED
1243 _cache_flush ((Class)clsObject->isa);
1247 // Move up superclass chain
1248 // else if (_class_isInitialized(clsIter))
1249 clsIter = clsIter->super_class;
1251 // clsIter is not initialized, so its cache
1252 // must be empty. This happens only when
1253 // clsIter == clsObject, because
1254 // superclasses are initialized before
1255 // subclasses, and this loop traverses
1256 // from sub- to super- classes.
1261 #ifdef OBJC_INSTRUMENTED
1262 NonlinearFlushCachesVisitedCount += classesVisited;
1263 if (classesVisited > MaxNonlinearFlushCachesVisitedCount)
1264 MaxNonlinearFlushCachesVisitedCount = classesVisited;
1265 IdealFlushCachesCount += subclassCount;
1266 if (subclassCount > MaxIdealFlushCachesCount)
1267 MaxIdealFlushCachesCount = subclassCount;
1270 mutex_unlock(&cacheUpdateLock);
1271 mutex_unlock(&classLock);
1275 /***********************************************************************
1276 * flush_marked_caches. Flush the method cache of any class marked
1277 * CLS_FLUSH_CACHE (and all subclasses thereof)
1279 **********************************************************************/
1280 void flush_marked_caches(void)
1282 struct old_class *cls;
1283 struct old_class *supercls;
1286 mutex_lock(&classLock);
1287 mutex_lock(&cacheUpdateLock);
1289 state = NXInitHashState(class_hash);
1290 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1291 for (supercls = cls; supercls; supercls = supercls->super_class) {
1292 if (supercls->info & CLS_FLUSH_CACHE) {
1293 _cache_flush((Class)cls);
1298 for (supercls = cls->isa; supercls; supercls = supercls->super_class) {
1299 if (supercls->info & CLS_FLUSH_CACHE) {
1300 _cache_flush((Class)cls->isa);
1306 state = NXInitHashState(class_hash);
1307 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1308 if (cls->info & CLS_FLUSH_CACHE) {
1309 _class_clearInfo((Class)cls, CLS_FLUSH_CACHE);
1311 if (cls->isa->info & CLS_FLUSH_CACHE) {
1312 _class_clearInfo((Class)cls->isa, CLS_FLUSH_CACHE);
1316 mutex_unlock(&cacheUpdateLock);
1317 mutex_unlock(&classLock);
1321 /***********************************************************************
1322 * get_base_method_list
1323 * Returns the method list containing the class's own methods,
1324 * ignoring any method lists added by categories or class_addMethods.
1325 * Called only by add_class_to_loadable_list.
1326 * Does not hold methodListLock because add_class_to_loadable_list
1327 * does not manipulate in-use classes.
1328 **********************************************************************/
1329 static struct old_method_list *get_base_method_list(struct old_class *cls)
1331 struct old_method_list **ptr;
1333 if (!cls->methodLists) return NULL;
1334 if (cls->info & CLS_NO_METHOD_ARRAY) return (struct old_method_list *)cls->methodLists;
1335 ptr = cls->methodLists;
1336 if (!*ptr || *ptr == END_OF_METHODS_LIST) return NULL;
1337 while ( *ptr != 0 && *ptr != END_OF_METHODS_LIST ) { ptr++; }
1343 static IMP _class_getLoadMethod_nocheck(struct old_class *cls)
1345 struct old_method_list *mlist;
1346 mlist = get_base_method_list(cls->isa);
1348 return lookupNamedMethodInMethodList (mlist, "load");
1354 BOOL _class_hasLoadMethod(Class cls)
1356 if (oldcls(cls)->isa->info & CLS_HAS_LOAD_METHOD) return YES;
1357 return (_class_getLoadMethod_nocheck(oldcls(cls)) ? YES : NO);
1361 /***********************************************************************
1362 * _class_getLoadMethod
1363 * Returns cls's +load implementation, or NULL if it doesn't have one.
1364 **********************************************************************/
1365 IMP _class_getLoadMethod(Class cls_gen)
1367 struct old_class *cls = oldcls(cls_gen);
1368 if (cls->isa->info & CLS_HAS_LOAD_METHOD) {
1369 return _class_getLoadMethod_nocheck(cls);
1375 BOOL _class_shouldGrowCache(Class cls)
1377 return _class_getInfo(cls, CLS_GROW_CACHE);
1380 void _class_setGrowCache(Class cls, BOOL grow)
1382 if (grow) _class_setInfo(cls, CLS_GROW_CACHE);
1383 else _class_clearInfo(cls, CLS_GROW_CACHE);
1386 BOOL _class_hasCxxStructors(Class cls)
1388 // this DOES check superclasses too, because set_superclass
1389 // propagates the flag from the superclass.
1390 return _class_getInfo(cls, CLS_HAS_CXX_STRUCTORS);
1393 BOOL _class_shouldFinalizeOnMainThread(Class cls) {
1394 return _class_getInfo(cls, CLS_FINALIZE_ON_MAIN_THREAD);
1397 void _class_setFinalizeOnMainThread(Class cls) {
1398 _class_setInfo(cls, CLS_FINALIZE_ON_MAIN_THREAD);
1401 BOOL _class_instancesHaveAssociatedObjects(Class cls) {
1402 return _class_getInfo(cls, CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS);
1405 void _class_setInstancesHaveAssociatedObjects(Class cls) {
1406 _class_setInfo(cls, CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS);
1409 BOOL _class_usesAutomaticRetainRelease(Class cls)
1414 uint32_t _class_getInstanceStart(Class cls)
1416 _objc_fatal("_class_getInstanceStart() unimplemented for fragile instance variables");
1417 return 0; // PCB: never used just provided for ARR consistency.
1420 ptrdiff_t ivar_getOffset(Ivar ivar)
1422 return oldivar(ivar)->ivar_offset;
1425 const char *ivar_getName(Ivar ivar)
1427 return oldivar(ivar)->ivar_name;
1430 const char *ivar_getTypeEncoding(Ivar ivar)
1432 return oldivar(ivar)->ivar_type;
1436 IMP method_getImplementation(Method m)
1438 if (!m) return NULL;
1439 return oldmethod(m)->method_imp;
1442 SEL method_getName(Method m)
1444 if (!m) return NULL;
1445 return oldmethod(m)->method_name;
1448 const char *method_getTypeEncoding(Method m)
1450 if (!m) return NULL;
1451 return oldmethod(m)->method_types;
1454 unsigned int method_getSizeOfArguments(Method m)
1456 OBJC_WARN_DEPRECATED;
1458 return encoding_getSizeOfArguments(method_getTypeEncoding(m));
1461 unsigned int method_getArgumentInfo(Method m, int arg,
1462 const char **type, int *offset)
1464 OBJC_WARN_DEPRECATED;
1466 return encoding_getArgumentInfo(method_getTypeEncoding(m),
1471 static OSSpinLock impLock = OS_SPINLOCK_INIT;
1473 IMP method_setImplementation(Method m_gen, IMP imp)
1476 struct old_method *m = oldmethod(m_gen);
1477 if (!m) return NULL;
1478 if (!imp) return NULL;
1480 if (ignoreSelector(m->method_name)) {
1481 // Ignored methods stay ignored
1482 return m->method_imp;
1485 OSSpinLockLock(&impLock);
1486 old = m->method_imp;
1487 m->method_imp = imp;
1488 OSSpinLockUnlock(&impLock);
1493 void method_exchangeImplementations(Method m1_gen, Method m2_gen)
1496 struct old_method *m1 = oldmethod(m1_gen);
1497 struct old_method *m2 = oldmethod(m2_gen);
1498 if (!m1 || !m2) return;
1500 if (ignoreSelector(m1->method_name) || ignoreSelector(m2->method_name)) {
1501 // Ignored methods stay ignored. Now they're both ignored.
1502 m1->method_imp = (IMP)&_objc_ignored_method;
1503 m2->method_imp = (IMP)&_objc_ignored_method;
1507 OSSpinLockLock(&impLock);
1508 m1_imp = m1->method_imp;
1509 m1->method_imp = m2->method_imp;
1510 m2->method_imp = m1_imp;
1511 OSSpinLockUnlock(&impLock);
1515 struct objc_method_description * method_getDescription(Method m)
1517 if (!m) return NULL;
1518 return (struct objc_method_description *)oldmethod(m);
1522 const char *property_getName(objc_property_t prop)
1524 return oldproperty(prop)->name;
1527 const char *property_getAttributes(objc_property_t prop)
1529 return oldproperty(prop)->attributes;
1532 objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
1533 unsigned int *outCount)
1536 if (outCount) *outCount = 0;
1540 objc_property_attribute_t *result;
1541 mutex_lock(&classLock);
1542 result = copyPropertyAttributeList(oldproperty(prop)->attributes,outCount);
1543 mutex_unlock(&classLock);
1547 char * property_copyAttributeValue(objc_property_t prop, const char *name)
1549 if (!prop || !name || *name == '\0') return NULL;
1552 mutex_lock(&classLock);
1553 result = copyPropertyAttributeValue(oldproperty(prop)->attributes, name);
1554 mutex_unlock(&classLock);
1559 /***********************************************************************
1561 **********************************************************************/
1562 static IMP _class_addMethod(Class cls_gen, SEL name, IMP imp,
1563 const char *types, BOOL replace)
1565 struct old_class *cls = oldcls(cls_gen);
1566 struct old_method *m;
1569 if (!types) types = "";
1571 mutex_lock(&methodListLock);
1573 if ((m = _findMethodInClass(cls, name))) {
1576 result = method_getImplementation((Method)m);
1578 method_setImplementation((Method)m, imp);
1581 // fixme could be faster
1582 struct old_method_list *mlist =
1583 _calloc_internal(sizeof(struct old_method_list), 1);
1584 mlist->obsolete = fixed_up_method_list;
1585 mlist->method_count = 1;
1586 mlist->method_list[0].method_name = name;
1587 mlist->method_list[0].method_types = _strdup_internal(types);
1588 if (!ignoreSelector(name)) {
1589 mlist->method_list[0].method_imp = imp;
1591 mlist->method_list[0].method_imp = (IMP)&_objc_ignored_method;
1594 _objc_insertMethods(cls, mlist, NULL);
1595 if (!(cls->info & CLS_CONSTRUCTING)) {
1596 flush_caches((Class)cls, NO);
1598 // in-construction class has no subclasses
1599 flush_cache((Class)cls);
1604 mutex_unlock(&methodListLock);
1610 /***********************************************************************
1612 **********************************************************************/
1613 BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
1616 if (!cls) return NO;
1618 old = _class_addMethod(cls, name, imp, types, NO);
1619 return old ? NO : YES;
1623 /***********************************************************************
1624 * class_replaceMethod
1625 **********************************************************************/
1626 IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
1628 if (!cls) return NULL;
1630 return _class_addMethod(cls, name, imp, types, YES);
1634 /***********************************************************************
1636 **********************************************************************/
1637 BOOL class_addIvar(Class cls_gen, const char *name, size_t size,
1638 uint8_t alignment, const char *type)
1640 struct old_class *cls = oldcls(cls_gen);
1643 if (!cls) return NO;
1644 if (ISMETA(cls)) return NO;
1645 if (!(cls->info & CLS_CONSTRUCTING)) return NO;
1647 if (!type) type = "";
1648 if (name && 0 == strcmp(name, "")) name = NULL;
1650 mutex_lock(&classLock);
1652 // Check for existing ivar with this name
1653 // fixme check superclasses?
1656 for (i = 0; i < cls->ivars->ivar_count; i++) {
1657 if (0 == strcmp(cls->ivars->ivar_list[i].ivar_name, name)) {
1665 struct old_ivar_list *old = cls->ivars;
1668 struct old_ivar *ivar;
1673 oldSize = sizeof(struct old_ivar_list) +
1674 (old->ivar_count - 1) * sizeof(struct old_ivar);
1675 newCount = 1 + old->ivar_count;
1677 oldSize = sizeof(struct old_ivar_list) - sizeof(struct old_ivar);
1681 // allocate new ivar list
1682 cls->ivars = _calloc_internal(oldSize + sizeof(struct old_ivar), 1);
1683 if (old) memcpy(cls->ivars, old, oldSize);
1684 if (old && malloc_size(old)) free(old);
1685 cls->ivars->ivar_count = newCount;
1686 ivar = &cls->ivars->ivar_list[newCount-1];
1688 // set ivar name and type
1689 ivar->ivar_name = _strdup_internal(name);
1690 ivar->ivar_type = _strdup_internal(type);
1692 // align if necessary
1693 alignBytes = 1 << alignment;
1694 misalign = cls->instance_size % alignBytes;
1695 if (misalign) cls->instance_size += (long)(alignBytes - misalign);
1697 // set ivar offset and increase instance size
1698 ivar->ivar_offset = (int)cls->instance_size;
1699 cls->instance_size += (long)size;
1702 mutex_unlock(&classLock);
1708 /***********************************************************************
1710 **********************************************************************/
1711 BOOL class_addProtocol(Class cls_gen, Protocol *protocol_gen)
1713 struct old_class *cls = oldcls(cls_gen);
1714 struct old_protocol *protocol = oldprotocol(protocol_gen);
1715 struct old_protocol_list *plist;
1717 if (!cls) return NO;
1718 if (class_conformsToProtocol(cls_gen, protocol_gen)) return NO;
1720 mutex_lock(&classLock);
1722 // fixme optimize - protocol list doesn't escape?
1723 plist = _calloc_internal(sizeof(struct old_protocol_list), 1);
1725 plist->list[0] = protocol;
1726 plist->next = cls->protocols;
1727 cls->protocols = plist;
1731 mutex_unlock(&classLock);
1737 /***********************************************************************
1738 * _class_addProperties
1739 * Internal helper to add properties to a class.
1740 * Used by category attachment and class_addProperty()
1741 * Locking: acquires classLock
1742 **********************************************************************/
1744 _class_addProperties(struct old_class *cls,
1745 struct old_property_list *additions)
1747 struct old_property_list *newlist;
1749 if (!(cls->info & CLS_EXT)) return NO;
1752 _memdup_internal(additions, sizeof(*newlist) - sizeof(newlist->first)
1753 + (additions->entsize * additions->count));
1755 mutex_lock(&classLock);
1758 if (!cls->ext->propertyLists) {
1759 // cls has no properties - simply use this list
1760 cls->ext->propertyLists = (struct old_property_list **)newlist;
1761 _class_setInfo((Class)cls, CLS_NO_PROPERTY_ARRAY);
1763 else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
1764 // cls has one property list - make a new array
1765 struct old_property_list **newarray =
1766 _malloc_internal(3 * sizeof(*newarray));
1767 newarray[0] = newlist;
1768 newarray[1] = (struct old_property_list *)cls->ext->propertyLists;
1770 cls->ext->propertyLists = newarray;
1771 _class_clearInfo((Class)cls, CLS_NO_PROPERTY_ARRAY);
1774 // cls has a property array - make a bigger one
1775 struct old_property_list **newarray;
1777 while (cls->ext->propertyLists[count]) count++;
1778 newarray = _malloc_internal((count+2) * sizeof(*newarray));
1779 newarray[0] = newlist;
1780 memcpy(&newarray[1], &cls->ext->propertyLists[0],
1781 count * sizeof(*newarray));
1782 newarray[count+1] = NULL;
1783 free(cls->ext->propertyLists);
1784 cls->ext->propertyLists = newarray;
1787 mutex_unlock(&classLock);
1793 /***********************************************************************
1795 * Adds a property to a class. Returns NO if the proeprty already exists.
1796 * Locking: acquires classLock
1797 **********************************************************************/
1799 _class_addProperty(Class cls_gen, const char *name,
1800 const objc_property_attribute_t *attrs, unsigned int count,
1803 struct old_class *cls = oldcls(cls_gen);
1805 if (!cls) return NO;
1806 if (!name) return NO;
1808 struct old_property *prop = oldproperty(class_getProperty(cls_gen, name));
1809 if (prop && !replace) {
1810 // already exists, refuse to replace
1815 mutex_lock(&classLock);
1816 try_free(prop->attributes);
1817 prop->attributes = copyPropertyAttributeString(attrs, count);
1818 mutex_unlock(&classLock);
1823 struct old_property_list proplist;
1824 proplist.entsize = sizeof(struct old_property);
1826 proplist.first.name = _strdup_internal(name);
1827 proplist.first.attributes = copyPropertyAttributeString(attrs, count);
1829 return _class_addProperties(cls, &proplist);
1834 class_addProperty(Class cls_gen, const char *name,
1835 const objc_property_attribute_t *attrs, unsigned int n)
1837 return _class_addProperty(cls_gen, name, attrs, n, NO);
1841 class_replaceProperty(Class cls_gen, const char *name,
1842 const objc_property_attribute_t *attrs, unsigned int n)
1844 _class_addProperty(cls_gen, name, attrs, n, YES);
1848 /***********************************************************************
1849 * class_copyProtocolList. Returns a heap block containing the
1850 * protocols implemented by the class, or NULL if the class
1851 * implements no protocols. Caller must free the block.
1852 * Does not copy any superclass's protocols.
1853 **********************************************************************/
1854 Protocol * __unsafe_unretained *
1855 class_copyProtocolList(Class cls_gen, unsigned int *outCount)
1857 struct old_class *cls = oldcls(cls_gen);
1858 struct old_protocol_list *plist;
1859 Protocol **result = NULL;
1860 unsigned int count = 0;
1864 if (outCount) *outCount = 0;
1868 mutex_lock(&classLock);
1870 for (plist = cls->protocols; plist != NULL; plist = plist->next) {
1871 count += (int)plist->count;
1875 result = malloc((count+1) * sizeof(Protocol *));
1877 for (p = 0, plist = cls->protocols;
1879 plist = plist->next)
1882 for (i = 0; i < plist->count; i++) {
1883 result[p++] = (Protocol *)plist->list[i];
1889 mutex_unlock(&classLock);
1891 if (outCount) *outCount = count;
1896 /***********************************************************************
1897 * class_getProperty. Return the named property.
1898 **********************************************************************/
1899 objc_property_t class_getProperty(Class cls_gen, const char *name)
1901 struct old_property *result;
1902 struct old_class *cls = oldcls(cls_gen);
1903 if (!cls || !name) return NULL;
1905 mutex_lock(&classLock);
1907 for (result = NULL; cls && !result; cls = cls->super_class) {
1908 uintptr_t iterator = 0;
1909 struct old_property_list *plist;
1910 while ((plist = nextPropertyList(cls, &iterator))) {
1912 for (i = 0; i < plist->count; i++) {
1913 struct old_property *p = property_list_nth(plist, i);
1914 if (0 == strcmp(name, p->name)) {
1923 mutex_unlock(&classLock);
1925 return (objc_property_t)result;
1929 /***********************************************************************
1930 * class_copyPropertyList. Returns a heap block containing the
1931 * properties declared in the class, or NULL if the class
1932 * declares no properties. Caller must free the block.
1933 * Does not copy any superclass's properties.
1934 **********************************************************************/
1935 objc_property_t *class_copyPropertyList(Class cls_gen, unsigned int *outCount)
1937 struct old_class *cls = oldcls(cls_gen);
1938 struct old_property_list *plist;
1939 uintptr_t iterator = 0;
1940 struct old_property **result = NULL;
1941 unsigned int count = 0;
1945 if (outCount) *outCount = 0;
1949 mutex_lock(&classLock);
1952 while ((plist = nextPropertyList(cls, &iterator))) {
1953 count += plist->count;
1957 result = malloc((count+1) * sizeof(struct old_property *));
1961 while ((plist = nextPropertyList(cls, &iterator))) {
1962 for (i = 0; i < plist->count; i++) {
1963 result[p++] = property_list_nth(plist, i);
1969 mutex_unlock(&classLock);
1971 if (outCount) *outCount = count;
1972 return (objc_property_t *)result;
1976 /***********************************************************************
1977 * class_copyMethodList. Returns a heap block containing the
1978 * methods implemented by the class, or NULL if the class
1979 * implements no methods. Caller must free the block.
1980 * Does not copy any superclass's methods.
1981 **********************************************************************/
1982 Method *class_copyMethodList(Class cls_gen, unsigned int *outCount)
1984 struct old_class *cls = oldcls(cls_gen);
1985 struct old_method_list *mlist;
1986 void *iterator = NULL;
1987 Method *result = NULL;
1988 unsigned int count = 0;
1992 if (outCount) *outCount = 0;
1996 mutex_lock(&methodListLock);
1999 while ((mlist = nextMethodList(cls, &iterator))) {
2000 count += mlist->method_count;
2004 result = malloc((count+1) * sizeof(Method));
2008 while ((mlist = nextMethodList(cls, &iterator))) {
2010 for (i = 0; i < mlist->method_count; i++) {
2011 Method aMethod = (Method)&mlist->method_list[i];
2012 if (ignoreSelector(method_getName(aMethod))) {
2016 result[m++] = aMethod;
2022 mutex_unlock(&methodListLock);
2024 if (outCount) *outCount = count;
2029 /***********************************************************************
2030 * class_copyIvarList. Returns a heap block containing the
2031 * ivars declared in the class, or NULL if the class
2032 * declares no ivars. Caller must free the block.
2033 * Does not copy any superclass's ivars.
2034 **********************************************************************/
2035 Ivar *class_copyIvarList(Class cls_gen, unsigned int *outCount)
2037 struct old_class *cls = oldcls(cls_gen);
2038 Ivar *result = NULL;
2039 unsigned int count = 0;
2043 if (outCount) *outCount = 0;
2048 count = cls->ivars->ivar_count;
2052 result = malloc((count+1) * sizeof(Ivar));
2054 for (i = 0; i < cls->ivars->ivar_count; i++) {
2055 result[i] = (Ivar)&cls->ivars->ivar_list[i];
2060 if (outCount) *outCount = count;
2065 /***********************************************************************
2066 * objc_allocateClass.
2067 **********************************************************************/
2069 void set_superclass(struct old_class *cls, struct old_class *supercls,
2072 struct old_class *meta = cls->isa;
2075 cls->super_class = supercls;
2076 meta->super_class = supercls->isa;
2077 meta->isa = supercls->isa->isa;
2079 // Propagate C++ cdtors from superclass.
2080 if (supercls->info & CLS_HAS_CXX_STRUCTORS) {
2081 if (cls_is_new) cls->info |= CLS_HAS_CXX_STRUCTORS;
2082 else _class_setInfo((Class)cls, CLS_HAS_CXX_STRUCTORS);
2085 // Superclass is no longer a leaf for cache flushing
2086 if (supercls->info & CLS_LEAF) {
2087 _class_clearInfo((Class)supercls, CLS_LEAF);
2088 _class_clearInfo((Class)supercls->isa, CLS_LEAF);
2091 cls->super_class = Nil; // superclass of root class is nil
2092 meta->super_class = cls; // superclass of root metaclass is root class
2093 meta->isa = meta; // metaclass of root metaclass is root metaclass
2095 // Root class is never a leaf for cache flushing, because the
2096 // root metaclass is a subclass. (This could be optimized, but
2097 // is too uncommon to bother.)
2098 _class_clearInfo((Class)cls, CLS_LEAF);
2099 _class_clearInfo((Class)meta, CLS_LEAF);
2103 // &UnsetLayout is the default ivar layout during class construction
2104 static const uint8_t UnsetLayout = 0;
2106 Class objc_initializeClassPair(Class superclass_gen, const char *name, Class cls_gen, Class meta_gen)
2108 struct old_class *supercls = oldcls(superclass_gen);
2109 struct old_class *cls = oldcls(cls_gen);
2110 struct old_class *meta = oldcls(meta_gen);
2112 // Connect to superclasses and metaclasses
2114 set_superclass(cls, supercls, YES);
2117 cls->name = _strdup_internal(name);
2118 meta->name = _strdup_internal(name);
2121 cls->info = CLS_CLASS | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2122 meta->info = CLS_META | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2124 // Set instance size based on superclass.
2126 cls->instance_size = supercls->instance_size;
2127 meta->instance_size = supercls->isa->instance_size;
2129 cls->instance_size = sizeof(struct old_class *); // just an isa
2130 meta->instance_size = sizeof(struct old_class);
2133 // No ivars. No methods. Empty cache. No protocols. No layout. Empty ext.
2135 cls->methodLists = NULL;
2136 cls->cache = (Cache)&_objc_empty_cache;
2137 cls->protocols = NULL;
2138 cls->ivar_layout = &UnsetLayout;
2141 cls->ext->weak_ivar_layout = &UnsetLayout;
2144 meta->methodLists = NULL;
2145 meta->cache = (Cache)&_objc_empty_cache;
2146 meta->protocols = NULL;
2152 Class objc_allocateClassPair(Class superclass_gen, const char *name,
2155 struct old_class *supercls = oldcls(superclass_gen);
2158 if (objc_getClass(name)) return NO;
2159 // fixme reserve class name against simultaneous allocation
2161 if (supercls && (supercls->info & CLS_CONSTRUCTING)) {
2162 // Can't make subclass of an in-construction class
2166 // Allocate new classes.
2168 cls = _calloc_class(_class_getInstanceSize((Class)supercls->isa) + extraBytes);
2169 meta = _calloc_class(_class_getInstanceSize((Class)supercls->isa->isa) + extraBytes);
2171 cls = _calloc_class(sizeof(struct old_class) + extraBytes);
2172 meta = _calloc_class(sizeof(struct old_class) + extraBytes);
2176 objc_initializeClassPair(superclass_gen, name, cls, meta);
2182 void objc_registerClassPair(Class cls_gen)
2184 struct old_class *cls = oldcls(cls_gen);
2186 if ((cls->info & CLS_CONSTRUCTED) ||
2187 (cls->isa->info & CLS_CONSTRUCTED))
2189 _objc_inform("objc_registerClassPair: class '%s' was already "
2190 "registered!", cls->name);
2194 if (!(cls->info & CLS_CONSTRUCTING) ||
2195 !(cls->isa->info & CLS_CONSTRUCTING))
2197 _objc_inform("objc_registerClassPair: class '%s' was not "
2198 "allocated with objc_allocateClassPair!", cls->name);
2203 _objc_inform("objc_registerClassPair: class '%s' is a metaclass, "
2204 "not a class!", cls->name);
2208 mutex_lock(&classLock);
2210 // Build ivar layouts
2212 if (cls->ivar_layout != &UnsetLayout) {
2213 // Class builder already called class_setIvarLayout.
2215 else if (!cls->super_class) {
2216 // Root class. Scan conservatively (should be isa ivar only).
2217 cls->ivar_layout = NULL;
2219 else if (cls->ivars == NULL) {
2220 // No local ivars. Use superclass's layout.
2222 _ustrdup_internal(cls->super_class->ivar_layout);
2225 // Has local ivars. Build layout based on superclass.
2226 struct old_class *supercls = cls->super_class;
2227 const uint8_t *superlayout =
2228 class_getIvarLayout((Class)supercls);
2229 layout_bitmap bitmap =
2230 layout_bitmap_create(superlayout, supercls->instance_size,
2231 cls->instance_size, NO);
2233 for (i = 0; i < cls->ivars->ivar_count; i++) {
2234 struct old_ivar *iv = &cls->ivars->ivar_list[i];
2235 layout_bitmap_set_ivar(bitmap, iv->ivar_type, iv->ivar_offset);
2237 cls->ivar_layout = layout_string_create(bitmap);
2238 layout_bitmap_free(bitmap);
2241 if (cls->ext->weak_ivar_layout != &UnsetLayout) {
2242 // Class builder already called class_setWeakIvarLayout.
2244 else if (!cls->super_class) {
2245 // Root class. No weak ivars (should be isa ivar only)
2246 cls->ext->weak_ivar_layout = NULL;
2248 else if (cls->ivars == NULL) {
2249 // No local ivars. Use superclass's layout.
2250 const uint8_t *weak =
2251 class_getWeakIvarLayout((Class)cls->super_class);
2253 cls->ext->weak_ivar_layout = _ustrdup_internal(weak);
2255 cls->ext->weak_ivar_layout = NULL;
2259 // Has local ivars. Build layout based on superclass.
2260 // No way to add weak ivars yet.
2261 const uint8_t *weak =
2262 class_getWeakIvarLayout((Class)cls->super_class);
2264 cls->ext->weak_ivar_layout = _ustrdup_internal(weak);
2266 cls->ext->weak_ivar_layout = NULL;
2271 // Clear "under construction" bit, set "done constructing" bit
2272 cls->info &= ~CLS_CONSTRUCTING;
2273 cls->isa->info &= ~CLS_CONSTRUCTING;
2274 cls->info |= CLS_CONSTRUCTED;
2275 cls->isa->info |= CLS_CONSTRUCTED;
2277 NXHashInsertIfAbsent(class_hash, cls);
2278 objc_addRegisteredClass((Class)cls);
2279 //objc_addRegisteredClass(cls->isa); if we ever allocate classes from GC
2281 mutex_unlock(&classLock);
2285 Class objc_duplicateClass(Class orig_gen, const char *name, size_t extraBytes)
2287 unsigned int count, i;
2288 struct old_method **originalMethods;
2289 struct old_method_list *duplicateMethods;
2290 struct old_class *original = oldcls(orig_gen);
2291 // Don't use sizeof(struct objc_class) here because
2292 // instance_size has historically contained two extra words,
2293 // and instance_size is what objc_getIndexedIvars() actually uses.
2294 struct old_class *duplicate = (struct old_class *)
2295 _calloc_class(_class_getInstanceSize((Class)original->isa) + extraBytes);
2297 duplicate->isa = original->isa;
2298 duplicate->super_class = original->super_class;
2299 duplicate->name = strdup(name);
2300 duplicate->version = original->version;
2301 duplicate->info = original->info & (CLS_CLASS|CLS_META|CLS_INITIALIZED|CLS_JAVA_HYBRID|CLS_JAVA_CLASS|CLS_HAS_CXX_STRUCTORS|CLS_HAS_LOAD_METHOD);
2302 duplicate->instance_size = original->instance_size;
2303 duplicate->ivars = original->ivars;
2304 // methodLists handled below
2305 duplicate->cache = (Cache)&_objc_empty_cache;
2306 duplicate->protocols = original->protocols;
2307 if (original->info & CLS_EXT) {
2308 duplicate->info |= original->info & (CLS_EXT|CLS_NO_PROPERTY_ARRAY);
2309 duplicate->ivar_layout = original->ivar_layout;
2310 if (original->ext) {
2311 duplicate->ext = _malloc_internal(original->ext->size);
2312 memcpy(duplicate->ext, original->ext, original->ext->size);
2314 duplicate->ext = NULL;
2318 // Method lists are deep-copied so they can be stomped.
2319 originalMethods = (struct old_method **)
2320 class_copyMethodList(orig_gen, &count);
2321 if (originalMethods) {
2322 duplicateMethods = (struct old_method_list *)
2323 calloc(sizeof(struct old_method_list) +
2324 (count-1)*sizeof(struct old_method), 1);
2325 duplicateMethods->obsolete = fixed_up_method_list;
2326 duplicateMethods->method_count = count;
2327 for (i = 0; i < count; i++) {
2328 duplicateMethods->method_list[i] = *(originalMethods[i]);
2330 duplicate->methodLists = (struct old_method_list **)duplicateMethods;
2331 duplicate->info |= CLS_NO_METHOD_ARRAY;
2332 free(originalMethods);
2335 mutex_lock(&classLock);
2336 NXHashInsert(class_hash, duplicate);
2337 objc_addRegisteredClass((Class)duplicate);
2338 mutex_unlock(&classLock);
2340 return (Class)duplicate;
2344 void objc_disposeClassPair(Class cls_gen)
2346 struct old_class *cls = oldcls(cls_gen);
2348 if (!(cls->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)) ||
2349 !(cls->isa->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)))
2351 // class not allocated with objc_allocateClassPair
2352 // disposing still-unregistered class is OK!
2353 _objc_inform("objc_disposeClassPair: class '%s' was not "
2354 "allocated with objc_allocateClassPair!", cls->name);
2359 _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
2360 "not a class!", cls->name);
2364 mutex_lock(&classLock);
2365 NXHashRemove(class_hash, cls);
2366 objc_removeRegisteredClass((Class)cls);
2367 unload_class(cls->isa);
2369 mutex_unlock(&classLock);
2374 /***********************************************************************
2375 * _class_createInstanceFromZone. Allocate an instance of the
2376 * specified class with the specified number of bytes for indexed
2377 * variables, in the specified zone. The isa field is set to the
2378 * class, C++ default constructors are called, and all other fields are zeroed.
2379 **********************************************************************/
2381 _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
2386 // Can't create something for nothing
2387 if (!cls) return nil;
2389 // Allocate and initialize
2390 size = _class_getInstanceSize(cls) + extraBytes;
2392 // CF requires all objects be at least 16 bytes.
2393 if (size < 16) size = 16;
2397 obj = (id)auto_zone_allocate_object(gc_zone, size,
2398 AUTO_OBJECT_SCANNED, 0, 1);
2402 obj = (id)malloc_zone_calloc (zone, 1, size);
2404 obj = (id)calloc(1, size);
2406 if (!obj) return nil;
2410 if (_class_hasCxxStructors(cls)) {
2411 obj = _objc_constructOrFree(cls, obj);
2418 /***********************************************************************
2419 * _class_createInstance. Allocate an instance of the specified
2420 * class with the specified number of bytes for indexed variables, in
2421 * the default zone, using _class_createInstanceFromZone.
2422 **********************************************************************/
2423 static id _class_createInstance(Class cls, size_t extraBytes)
2425 return _class_createInstanceFromZone (cls, extraBytes, NULL);
2429 static id _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
2434 if (!oldObj) return nil;
2436 obj = (*_zoneAlloc)(oldObj->isa, extraBytes, zone);
2437 size = _class_getInstanceSize(oldObj->isa) + extraBytes;
2439 // fixme need C++ copy constructor
2440 objc_memmove_collectable(obj, oldObj, size);
2443 if (UseGC) gc_fixup_weakreferences(obj, oldObj);
2450 /***********************************************************************
2451 * objc_destructInstance
2452 * Destroys an instance without freeing memory.
2453 * Calls C++ destructors.
2454 * Removes associative references.
2455 * Returns `obj`. Does nothing if `obj` is nil.
2456 * Be warned that GC DOES NOT CALL THIS. If you edit this, also edit finalize.
2457 * CoreFoundation and other clients do call this under GC.
2458 **********************************************************************/
2459 void *objc_destructInstance(id obj)
2462 Class isa = _object_getClass(obj);
2464 if (_class_hasCxxStructors(isa)) {
2465 object_cxxDestruct(obj);
2468 if (_class_instancesHaveAssociatedObjects(isa)) {
2469 _object_remove_assocations(obj);
2472 if (!UseGC) objc_clear_deallocating(obj);
2479 _object_dispose(id anObject)
2481 if (anObject==nil) return nil;
2483 objc_destructInstance(anObject);
2487 auto_zone_retain(gc_zone, anObject); // gc free expects rc==1
2491 // only clobber isa for non-gc
2492 anObject->isa = _objc_getFreedObjectClass ();
2498 static id _object_copy(id oldObj, size_t extraBytes)
2500 void *z = malloc_zone_from_ptr(oldObj);
2501 return _object_copyFromZone(oldObj, extraBytes,
2502 z ? z : malloc_default_zone());
2505 static id _object_reallocFromZone(id anObject, size_t nBytes,
2511 if (anObject == nil)
2512 __objc_error(nil, "reallocating nil object");
2514 if (anObject->isa == _objc_getFreedObjectClass ())
2515 __objc_error(anObject, "reallocating freed object");
2517 if (nBytes < _class_getInstanceSize(anObject->isa))
2518 __objc_error(anObject, "(%s, %zu) requested size too small",
2519 object_getClassName(anObject), nBytes);
2521 // fixme need C++ copy constructor
2523 // Make sure not to modify space that has been declared free
2524 tmp = anObject->isa;
2525 anObject->isa = _objc_getFreedObjectClass ();
2526 newObject = (id)malloc_zone_realloc(zone, anObject, nBytes);
2528 newObject->isa = tmp;
2530 // realloc failed, anObject is still alive
2531 anObject->isa = tmp;
2537 static id _object_realloc(id anObject, size_t nBytes)
2539 void *z = malloc_zone_from_ptr(anObject);
2540 return _object_reallocFromZone(anObject,
2542 z ? z : malloc_default_zone());
2545 id (*_alloc)(Class, size_t) = _class_createInstance;
2546 id (*_copy)(id, size_t) = _object_copy;
2547 id (*_realloc)(id, size_t) = _object_realloc;
2548 id (*_dealloc)(id) = _object_dispose;
2549 id (*_zoneAlloc)(Class, size_t, void *) = _class_createInstanceFromZone;
2550 id (*_zoneCopy)(id, size_t, void *) = _object_copyFromZone;
2551 id (*_zoneRealloc)(id, size_t, void *) = _object_reallocFromZone;
2552 void (*_error)(id, const char *, va_list) = _objc_error;
2555 id class_createInstance(Class cls, size_t extraBytes)
2558 return _class_createInstance(cls, extraBytes);
2560 return (*_alloc)(cls, extraBytes);
2564 id class_createInstanceFromZone(Class cls, size_t extraBytes, void *z)
2566 OBJC_WARN_DEPRECATED;
2568 return _class_createInstanceFromZone(cls, extraBytes, z);
2570 return (*_zoneAlloc)(cls, extraBytes, z);
2574 unsigned class_createInstances(Class cls, size_t extraBytes,
2575 id *results, unsigned num_requested)
2577 if (UseGC || _alloc == &_class_createInstance) {
2578 return _class_createInstancesFromZone(cls, extraBytes, NULL,
2579 results, num_requested);
2581 // _alloc in use, which isn't understood by the batch allocator
2586 id object_copy(id obj, size_t extraBytes)
2588 if (UseGC) return _object_copy(obj, extraBytes);
2589 else return (*_copy)(obj, extraBytes);
2592 id object_copyFromZone(id obj, size_t extraBytes, void *z)
2594 OBJC_WARN_DEPRECATED;
2595 if (UseGC) return _object_copyFromZone(obj, extraBytes, z);
2596 else return (*_zoneCopy)(obj, extraBytes, z);
2599 id object_dispose(id obj)
2601 if (UseGC) return _object_dispose(obj);
2602 else return (*_dealloc)(obj);
2605 id object_realloc(id obj, size_t nBytes)
2607 OBJC_WARN_DEPRECATED;
2608 if (UseGC) return _object_realloc(obj, nBytes);
2609 else return (*_realloc)(obj, nBytes);
2612 id object_reallocFromZone(id obj, size_t nBytes, void *z)
2614 OBJC_WARN_DEPRECATED;
2615 if (UseGC) return _object_reallocFromZone(obj, nBytes, z);
2616 else return (*_zoneRealloc)(obj, nBytes, z);
2621 Class class_setSuperclass(Class cls, Class newSuper)
2623 Class oldSuper = cls->super_class;
2624 set_superclass(oldcls(cls), oldcls(newSuper), NO);
2625 flush_caches(cls, YES);