2 * Copyright (c) 1999-2007 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 **********************************************************************/
32 #include "objc-private.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
50 static const struct old_class nonexistentObjectClass =
54 "NONEXISTENT(id)", // name
60 (Cache) &_objc_empty_cache, // cache
65 /***********************************************************************
66 * _class_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 static Class _class_getFreedObjectClass(void)
73 return (Class)&freedObjectClass;
77 /***********************************************************************
78 * _class_getNonexistentClass. Return a pointer to the dummy nonexistent
79 * object class. This is used when, for example, mapping the class
80 * refs for an image, and the class can not be found, so that we can
81 * catch later uses of the non-existent class.
82 **********************************************************************/
83 __private_extern__ Class _class_getNonexistentObjectClass(void)
85 return (Class)&nonexistentObjectClass;
89 /***********************************************************************
90 * _objc_getFreedObjectClass. Return a pointer to the dummy freed
91 * object class. Freed objects get their isa pointers replaced with
92 * a pointer to the freedObjectClass, so that we can catch usages of
94 **********************************************************************/
95 Class _objc_getFreedObjectClass(void)
97 return _class_getFreedObjectClass();
101 static void allocateExt(struct old_class *cls)
103 if (! (cls->info & CLS_EXT)) {
104 _objc_inform("class '%s' needs to be recompiled", cls->name);
108 uint32_t size = (uint32_t)sizeof(struct old_class_ext);
109 cls->ext = _calloc_internal(size, 1);
110 cls->ext->size = size;
115 static inline struct old_method *_findNamedMethodInList(struct old_method_list * mlist, const char *meth_name) {
117 if (!mlist) return NULL;
118 for (i = 0; i < mlist->method_count; i++) {
119 struct old_method *m = &mlist->method_list[i];
120 if (m->method_name == (SEL)kRTAddress_ignoredSelector) continue;
121 if (*((const char *)m->method_name) == *meth_name && 0 == strcmp((const char *)(m->method_name), meth_name)) {
129 /***********************************************************************
130 * Method list fixup markers.
131 * mlist->obsolete == fixed_up_method_list marks method lists with real SELs
132 * versus method lists with un-uniqued char*.
133 * PREOPTIMIZED VERSION:
134 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP
135 * dyld shared cache sets this for method lists it preoptimizes.
136 * UN-PREOPTIMIZED VERSION
137 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP_outside_dyld
138 * dyld shared cache uses OBJC_FIXED_UP, but those aren't trusted.
139 **********************************************************************/
140 #define OBJC_FIXED_UP ((void *)1771)
141 #define OBJC_FIXED_UP_outside_dyld ((void *)1773)
142 static void *fixed_up_method_list = OBJC_FIXED_UP;
144 // sel_init() decided that selectors in the dyld shared cache are untrustworthy
145 __private_extern__ void disableSelectorPreoptimization(void)
147 fixed_up_method_list = OBJC_FIXED_UP_outside_dyld;
150 /***********************************************************************
151 * fixupSelectorsInMethodList
152 * Uniques selectors in the given method list.
153 * Also replaces imps for GC-ignored selectors
154 * The given method list must be non-NULL and not already fixed-up.
155 * If the class was loaded from a bundle:
156 * fixes up the given list in place with heap-allocated selector strings
157 * If the class was not from a bundle:
158 * allocates a copy of the method list, fixes up the copy, and returns
159 * the copy. The given list is unmodified.
161 * If cls is already in use, methodListLock must be held by the caller.
162 **********************************************************************/
163 static struct old_method_list *fixupSelectorsInMethodList(struct old_class *cls, struct old_method_list *mlist)
167 struct old_method *method;
168 struct old_method_list *old_mlist;
170 if ( ! mlist ) return NULL;
171 if ( mlist->obsolete == fixed_up_method_list ) {
174 BOOL isBundle = (cls->info & CLS_FROM_BUNDLE) ? YES : NO;
177 size = sizeof(struct old_method_list) - sizeof(struct old_method) + old_mlist->method_count * sizeof(struct old_method);
178 mlist = _malloc_internal(size);
179 memmove(mlist, old_mlist, size);
181 // Mach-O bundles are fixed up in place.
182 // This prevents leaks when a bundle is unloaded.
185 for ( i = 0; i < mlist->method_count; i += 1 ) {
186 method = &mlist->method_list[i];
187 method->method_name =
188 sel_registerNameNoLock((const char *)method->method_name, isBundle); // Always copy selector data from bundles.
191 if (method->method_name == (SEL)kRTAddress_ignoredSelector) {
192 method->method_imp = (IMP)&_objc_ignored_method;
197 mlist->obsolete = fixed_up_method_list;
203 /***********************************************************************
205 * Returns successive method lists from the given class.
206 * Method lists are returned in method search order (i.e. highest-priority
207 * implementations first).
208 * All necessary method list fixups are performed, so the
209 * returned method list is fully-constructed.
211 * If cls is already in use, methodListLock must be held by the caller.
212 * For full thread-safety, methodListLock must be continuously held by the
213 * caller across all calls to nextMethodList(). If the lock is released,
214 * the bad results listed in class_nextMethodList() may occur.
216 * void *iterator = NULL;
217 * struct old_method_list *mlist;
218 * mutex_lock(&methodListLock);
219 * while ((mlist = nextMethodList(cls, &iterator))) {
220 * // do something with mlist
222 * mutex_unlock(&methodListLock);
223 **********************************************************************/
224 static struct old_method_list *nextMethodList(struct old_class *cls,
227 uintptr_t index = *(uintptr_t *)it;
228 struct old_method_list **resultp;
231 // First call to nextMethodList.
232 if (!cls->methodLists) {
234 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
235 resultp = (struct old_method_list **)&cls->methodLists;
237 resultp = &cls->methodLists[0];
238 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
243 // Subsequent call to nextMethodList.
244 if (!cls->methodLists) {
246 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
249 resultp = &cls->methodLists[index];
250 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
256 // resultp now is NULL, meaning there are no more method lists,
257 // OR the address of the method list pointer to fix up and return.
261 *resultp = fixupSelectorsInMethodList(cls, *resultp);
263 *it = (void *)(index + 1);
272 /* These next three functions are the heart of ObjC method lookup.
273 * If the class is currently in use, methodListLock must be held by the caller.
275 static inline struct old_method *_findMethodInList(struct old_method_list * mlist, SEL sel) {
277 if (!mlist) return NULL;
278 for (i = 0; i < mlist->method_count; i++) {
279 struct old_method *m = &mlist->method_list[i];
280 if (m->method_name == sel) {
287 static inline struct old_method * _findMethodInClass(struct old_class *cls, SEL sel) __attribute__((always_inline));
288 static inline struct old_method * _findMethodInClass(struct old_class *cls, SEL sel) {
289 // Flattened version of nextMethodList(). The optimizer doesn't
290 // do a good job with hoisting the conditionals out of the loop.
291 // Conceptually, this looks like:
292 // while ((mlist = nextMethodList(cls, &iterator))) {
293 // struct old_method *m = _findMethodInList(mlist, sel);
297 if (!cls->methodLists) {
301 else if (cls->info & CLS_NO_METHOD_ARRAY) {
303 struct old_method_list **mlistp;
304 mlistp = (struct old_method_list **)&cls->methodLists;
305 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
306 return _findMethodInList(*mlistp, sel);
309 // Multiple method lists.
310 struct old_method_list **mlistp;
311 for (mlistp = cls->methodLists;
312 *mlistp != NULL && *mlistp != END_OF_METHODS_LIST;
315 struct old_method *m;
316 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
317 m = _findMethodInList(*mlistp, sel);
324 static inline struct old_method * _getMethod(struct old_class *cls, SEL sel) {
325 for (; cls; cls = cls->super_class) {
326 struct old_method *m;
327 m = _findMethodInClass(cls, sel);
334 // fixme for gc debugging temporary use
335 __private_extern__ IMP findIMPInClass(struct old_class *cls, SEL sel)
337 struct old_method *m = _findMethodInClass(cls, sel);
338 if (m) return m->method_imp;
343 /***********************************************************************
345 **********************************************************************/
346 static void _freedHandler(id obj, SEL sel)
348 __objc_error (obj, "message %s sent to freed object=%p",
349 sel_getName(sel), obj);
352 /***********************************************************************
353 * _nonexistentHandler.
354 **********************************************************************/
355 static void _nonexistentHandler(id obj, SEL sel)
357 __objc_error (obj, "message %s sent to non-existent object=%p",
358 sel_getName(sel), obj);
362 /***********************************************************************
363 * ABI-specific lookUpMethod helpers.
364 **********************************************************************/
365 __private_extern__ void lockForMethodLookup(void)
367 mutex_lock(&methodListLock);
369 __private_extern__ void unlockForMethodLookup(void)
371 mutex_unlock(&methodListLock);
373 __private_extern__ IMP prepareForMethodLookup(Class cls, SEL sel, BOOL init)
375 mutex_assert_unlocked(&methodListLock);
377 // Check for freed class
378 if (cls == _class_getFreedObjectClass())
379 return (IMP) _freedHandler;
381 // Check for nonexistent class
382 if (cls == _class_getNonexistentObjectClass())
383 return (IMP) _nonexistentHandler;
385 if (init && !_class_isInitialized(cls)) {
386 _class_initialize (cls);
387 // If sel == initialize, _class_initialize will send +initialize and
388 // then the messenger will send +initialize again after this
389 // procedure finishes. Of course, if this is not being called
390 // from the messenger then it won't happen. 2778172
397 /***********************************************************************
398 * class_getVariable. Return the named instance variable.
399 **********************************************************************/
401 Ivar _class_getVariable(Class cls_gen, const char *name)
403 struct old_class *cls = _class_asOld(cls_gen);
405 for (; cls != Nil; cls = cls->super_class) {
408 // Skip class having no ivars
409 if (!cls->ivars) continue;
411 for (i = 0; i < cls->ivars->ivar_count; i++) {
412 // Check this ivar's name. Be careful because the
413 // compiler generates ivar entries with NULL ivar_name
414 // (e.g. for anonymous bit fields).
415 struct old_ivar *ivar = &cls->ivars->ivar_list[i];
416 if (ivar->ivar_name && 0 == strcmp(name, ivar->ivar_name)) {
427 /***********************************************************************
428 * class_getPropertyList. Return the class's property list
429 * Locking: classLock must be held by the caller
430 **********************************************************************/
431 static struct objc_property_list *
432 nextPropertyList(struct old_class *cls, uintptr_t *indexp)
434 struct objc_property_list *result = NULL;
436 mutex_assert_locked(&classLock);
437 if (! ((cls->info & CLS_EXT) && cls->ext)) {
440 } else if (!cls->ext->propertyLists) {
443 } else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
444 // Only one property list
446 result = (struct objc_property_list *)cls->ext->propertyLists;
451 // More than one property list
452 result = cls->ext->propertyLists[*indexp];
465 /***********************************************************************
466 * class_getIvarLayout
467 * NULL means all-scanned. "" means non-scanned.
468 **********************************************************************/
470 class_getIvarLayout(Class cls_gen)
472 struct old_class *cls = _class_asOld(cls_gen);
473 if (cls && (cls->info & CLS_EXT)) {
474 return cls->ivar_layout;
476 return NULL; // conservative scan
481 /***********************************************************************
482 * class_getWeakIvarLayout
483 * NULL means no weak ivars.
484 **********************************************************************/
486 class_getWeakIvarLayout(Class cls_gen)
488 struct old_class *cls = _class_asOld(cls_gen);
489 if (cls && (cls->info & CLS_EXT) && cls->ext) {
490 return cls->ext->weak_ivar_layout;
492 return NULL; // no weak ivars
497 /***********************************************************************
498 * class_setIvarLayout
499 * NULL means all-scanned. "" means non-scanned.
500 **********************************************************************/
501 void class_setIvarLayout(Class cls_gen, const char *layout)
503 struct old_class *cls = _class_asOld(cls_gen);
506 if (! (cls->info & CLS_EXT)) {
507 _objc_inform("class '%s' needs to be recompiled", cls->name);
512 cls->ivar_layout = layout ? _strdup_internal(layout) : NULL;
516 /***********************************************************************
517 * class_setWeakIvarLayout
518 * NULL means no weak ivars.
519 **********************************************************************/
520 void class_setWeakIvarLayout(Class cls_gen, const char *layout)
522 struct old_class *cls = _class_asOld(cls_gen);
525 mutex_lock(&classLock);
530 cls->ext->weak_ivar_layout = layout ? _strdup_internal(layout) : NULL;
532 mutex_unlock(&classLock);
536 /***********************************************************************
538 * Atomically sets and clears some bits in cls's info field.
539 * set and clear must not overlap.
540 **********************************************************************/
541 __private_extern__ void _class_changeInfo(Class cls, long set, long clear)
543 struct old_class *old = _class_asOld(cls);
548 newinfo = (oldinfo | set) & ~clear;
549 } while (! OSAtomicCompareAndSwapLong(oldinfo, newinfo, &old->info));
553 /***********************************************************************
555 * Returns YES iff all set bits in get are also set in cls's info field.
556 **********************************************************************/
557 __private_extern__ BOOL _class_getInfo(Class cls, int get)
559 struct old_class *old = _class_asOld(cls);
560 return ((old->info & get) == get) ? YES : NO;
564 /***********************************************************************
566 * Atomically sets some bits in cls's info field.
567 **********************************************************************/
568 __private_extern__ void _class_setInfo(Class cls, long set)
570 _class_changeInfo(cls, set, 0);
574 /***********************************************************************
576 * Atomically clears some bits in cls's info field.
577 **********************************************************************/
578 __private_extern__ void _class_clearInfo(Class cls, long clear)
580 _class_changeInfo(cls, 0, clear);
584 /***********************************************************************
586 * Return YES if cls is currently being initialized.
587 * The initializing bit is stored in the metaclass only.
588 **********************************************************************/
589 __private_extern__ BOOL _class_isInitializing(Class cls)
591 return _class_getInfo(_class_getMeta(cls), CLS_INITIALIZING);
595 /***********************************************************************
597 * Return YES if cls is already initialized.
598 * The initialized bit is stored in the metaclass only.
599 **********************************************************************/
600 __private_extern__ BOOL _class_isInitialized(Class cls)
602 return _class_getInfo(_class_getMeta(cls), CLS_INITIALIZED);
606 /***********************************************************************
608 * Mark cls as initialization in progress.
609 **********************************************************************/
610 __private_extern__ void _class_setInitializing(Class cls)
612 _class_setInfo(_class_getMeta(cls), CLS_INITIALIZING);
616 /***********************************************************************
618 * Atomically mark cls as initialized and not initializing.
619 **********************************************************************/
620 __private_extern__ void _class_setInitialized(Class cls)
622 _class_changeInfo(_class_getMeta(cls), CLS_INITIALIZED, CLS_INITIALIZING);
626 /***********************************************************************
627 * class_setVersion. Record the specified version with the class.
628 **********************************************************************/
629 void class_setVersion(Class cls, int version)
632 cls->version = version;
635 /***********************************************************************
636 * class_getVersion. Return the version recorded with the class.
637 **********************************************************************/
638 int class_getVersion(Class cls)
641 return (int)cls->version;
645 __private_extern__ Class _class_getMeta(Class cls)
647 if (_class_getInfo(cls, CLS_META)) return cls;
648 else return ((id)cls)->isa;
651 __private_extern__ BOOL _class_isMetaClass(Class cls)
654 return _class_getInfo(cls, CLS_META);
658 /***********************************************************************
659 * _class_getNonMetaClass.
660 * Return the ordinary class for this class or metaclass.
661 * Used by +initialize.
662 **********************************************************************/
663 __private_extern__ Class _class_getNonMetaClass(Class cls)
666 if (_class_isMetaClass(cls)) {
667 if (strncmp(_class_getName(cls), "_%", 2) == 0) {
668 // Posee's meta's name is smashed and isn't in the class_hash,
669 // so objc_getClass doesn't work.
670 const char *baseName = strchr(_class_getName(cls), '%'); // get posee's real name
671 cls = (Class)objc_getClass(baseName);
673 cls = (Class)objc_getClass(_class_getName(cls));
682 __private_extern__ Class _class_getSuperclass(Class cls)
684 if (!cls) return nil;
685 return (Class)cls->super_class;
689 __private_extern__ Cache _class_getCache(Class cls)
694 __private_extern__ void _class_setCache(Class cls, Cache cache)
699 __private_extern__ size_t _class_getInstanceSize(Class cls)
702 return cls->instance_size;
705 __private_extern__ const char * _class_getName(Class cls)
707 if (!cls) return "nil";
713 __private_extern__ const char *_category_getName(Category cat)
715 return _category_asOld(cat)->category_name;
718 __private_extern__ const char *_category_getClassName(Category cat)
720 return _category_asOld(cat)->class_name;
723 __private_extern__ Class _category_getClass(Category cat)
725 return (Class)objc_getClass(_category_asOld(cat)->class_name);
728 __private_extern__ IMP _category_getLoadMethod(Category cat)
730 struct old_method_list *mlist = _category_asOld(cat)->class_methods;
732 return lookupNamedMethodInMethodList(mlist, "load");
740 /***********************************************************************
741 * class_nextMethodList.
742 * External version of nextMethodList().
744 * This function is not fully thread-safe. A series of calls to
745 * class_nextMethodList() may fail if methods are added to or removed
746 * from the class between calls.
747 * If methods are added between calls to class_nextMethodList(), it may
748 * return previously-returned method lists again, and may fail to return
750 * If methods are removed between calls to class_nextMethodList(), it may
751 * omit surviving method lists or simply crash.
752 **********************************************************************/
753 OBJC_EXPORT struct objc_method_list *class_nextMethodList(Class cls, void **it)
755 struct old_method_list *result;
757 OBJC_WARN_DEPRECATED;
759 mutex_lock(&methodListLock);
760 result = nextMethodList(_class_asOld(cls), it);
761 mutex_unlock(&methodListLock);
762 return (struct objc_method_list *)result;
766 /***********************************************************************
769 * Formerly class_addInstanceMethods ()
770 **********************************************************************/
771 OBJC_EXPORT void class_addMethods(Class cls, struct objc_method_list *meths)
773 OBJC_WARN_DEPRECATED;
776 mutex_lock(&methodListLock);
777 _objc_insertMethods(_class_asOld(cls), (struct old_method_list *)meths, NULL);
778 mutex_unlock(&methodListLock);
780 // Must flush when dynamically adding methods. No need to flush
781 // all the class method caches. If cls is a meta class, though,
782 // this will still flush it and any of its sub-meta classes.
783 flush_caches (cls, NO);
787 /***********************************************************************
788 * class_removeMethods.
789 **********************************************************************/
790 OBJC_EXPORT void class_removeMethods(Class cls, struct objc_method_list *meths)
792 OBJC_WARN_DEPRECATED;
794 // Remove the methods
795 mutex_lock(&methodListLock);
796 _objc_removeMethods(_class_asOld(cls), (struct old_method_list *)meths);
797 mutex_unlock(&methodListLock);
799 // Must flush when dynamically removing methods. No need to flush
800 // all the class method caches. If cls is a meta class, though,
801 // this will still flush it and any of its sub-meta classes.
802 flush_caches (cls, NO);
805 /***********************************************************************
806 * lookupNamedMethodInMethodList
807 * Only called to find +load/-.cxx_construct/-.cxx_destruct methods,
808 * without fixing up the entire method list.
809 * The class is not yet in use, so methodListLock is not taken.
810 **********************************************************************/
811 __private_extern__ IMP lookupNamedMethodInMethodList(struct old_method_list *mlist, const char *meth_name)
813 struct old_method *m;
814 m = meth_name ? _findNamedMethodInList(mlist, meth_name) : NULL;
815 return (m ? m->method_imp : NULL);
818 __private_extern__ Method _class_getMethod(Class cls, SEL sel)
822 mutex_lock(&methodListLock);
823 result = (Method)_getMethod(_class_asOld(cls), sel);
824 mutex_unlock(&methodListLock);
829 __private_extern__ Method _class_getMethodNoSuper(Class cls, SEL sel)
833 mutex_lock(&methodListLock);
834 result = (Method)_findMethodInClass(_class_asOld(cls), sel);
835 mutex_unlock(&methodListLock);
840 __private_extern__ Method _class_getMethodNoSuper_nolock(Class cls, SEL sel)
842 mutex_assert_locked(&methodListLock);
843 return (Method)_findMethodInClass(_class_asOld(cls), sel);
847 BOOL class_conformsToProtocol(Class cls_gen, Protocol *proto_gen)
849 struct old_class *cls = oldcls(cls_gen);
850 struct old_protocol *proto = oldprotocol(proto_gen);
852 if (!cls_gen) return NO;
853 if (!proto) return NO;
855 if (cls->isa->version >= 3) {
856 struct old_protocol_list *list;
857 for (list = cls->protocols; list != NULL; list = list->next) {
859 for (i = 0; i < list->count; i++) {
860 if (list->list[i] == proto) return YES;
861 if (protocol_conformsToProtocol((Protocol *)list->list[i], proto_gen)) return YES;
863 if (cls->isa->version <= 4) break;
870 static NXMapTable * posed_class_hash = NULL;
872 /***********************************************************************
874 **********************************************************************/
875 __private_extern__ Class _objc_getOrigClass(const char *name)
879 // Look for class among the posers
881 mutex_lock(&classLock);
882 if (posed_class_hash)
883 ret = (Class) NXMapGet (posed_class_hash, name);
884 mutex_unlock(&classLock);
888 // Not a poser. Do a normal lookup.
889 ret = (Class)objc_getClass (name);
891 _objc_inform ("class `%s' not linked into application", name);
896 Class objc_getOrigClass(const char *name)
898 OBJC_WARN_DEPRECATED;
899 return _objc_getOrigClass(name);
902 /***********************************************************************
903 * _objc_addOrigClass. This function is only used from class_poseAs.
904 * Registers the original class names, before they get obscured by
905 * posing, so that [super ..] will work correctly from categories
906 * in posing classes and in categories in classes being posed for.
907 **********************************************************************/
908 static void _objc_addOrigClass (struct old_class *origClass)
910 mutex_lock(&classLock);
912 // Create the poser's hash table on first use
913 if (!posed_class_hash)
915 posed_class_hash = NXCreateMapTableFromZone (NXStrValueMapPrototype,
917 _objc_internal_zone ());
920 // Add the named class iff it is not already there (or collides?)
921 if (NXMapGet (posed_class_hash, origClass->name) == 0)
922 NXMapInsert (posed_class_hash, origClass->name, origClass);
924 mutex_unlock(&classLock);
928 /***********************************************************************
929 * change_class_references
930 * Change classrefs and superclass pointers from original to imposter
931 * But if copy!=nil, don't change copy->super_class.
932 * If changeSuperRefs==YES, also change [super message] classrefs.
933 * Used by class_poseAs and objc_setFutureClass
934 * classLock must be locked.
935 **********************************************************************/
937 void change_class_references(struct old_class *imposter,
938 struct old_class *original,
939 struct old_class *copy,
940 BOOL changeSuperRefs)
943 struct old_class *clsObject;
946 // Change all subclasses of the original to point to the imposter.
947 state = NXInitHashState (class_hash);
948 while (NXNextHashState (class_hash, &state, (void **) &clsObject))
950 while ((clsObject) && (clsObject != imposter) &&
953 if (clsObject->super_class == original)
955 clsObject->super_class = imposter;
956 clsObject->isa->super_class = imposter->isa;
957 // We must flush caches here!
961 clsObject = clsObject->super_class;
965 // Replace the original with the imposter in all class refs
966 // Major loop - process all headers
967 for (hInfo = FirstHeader; hInfo != NULL; hInfo = hInfo->next)
969 struct old_class **cls_refs;
973 // Fix class refs associated with this header
974 cls_refs = _getObjcClassRefs(hInfo, &refCount);
976 for (index = 0; index < refCount; index += 1) {
977 if (cls_refs[index] == original) {
978 cls_refs[index] = imposter;
986 /***********************************************************************
989 * !!! class_poseAs () does not currently flush any caches.
990 **********************************************************************/
991 Class class_poseAs(Class imposter_gen, Class original_gen)
993 struct old_class *imposter = _class_asOld(imposter_gen);
994 struct old_class *original = _class_asOld(original_gen);
995 char * imposterNamePtr;
996 struct old_class * copy;
998 OBJC_WARN_DEPRECATED;
1000 // Trivial case is easy
1001 if (imposter_gen == original_gen)
1002 return imposter_gen;
1004 // Imposter must be an immediate subclass of the original
1005 if (imposter->super_class != original) {
1006 __objc_error((id)imposter_gen,
1007 "[%s poseAs:%s]: target not immediate superclass",
1008 imposter->name, original->name);
1011 // Can't pose when you have instance variables (how could it work?)
1012 if (imposter->ivars) {
1013 __objc_error((id)imposter_gen,
1014 "[%s poseAs:%s]: %s defines new instance variables",
1015 imposter->name, original->name, imposter->name);
1018 // Build a string to use to replace the name of the original class.
1020 # define imposterNamePrefix "_%"
1021 imposterNamePtr = _malloc_internal(strlen(original->name) + strlen(imposterNamePrefix) + 1);
1022 strcpy(imposterNamePtr, imposterNamePrefix);
1023 strcat(imposterNamePtr, original->name);
1024 # undef imposterNamePrefix
1026 asprintf(&imposterNamePtr, "_%%%s", original->name);
1029 // We lock the class hashtable, so we are thread safe with respect to
1030 // calls to objc_getClass (). However, the class names are not
1031 // changed atomically, nor are all of the subclasses updated
1032 // atomically. I have ordered the operations so that you will
1033 // never crash, but you may get inconsistent results....
1035 // Register the original class so that [super ..] knows
1036 // exactly which classes are the "original" classes.
1037 _objc_addOrigClass (original);
1038 _objc_addOrigClass (imposter);
1040 // Copy the imposter, so that the imposter can continue
1041 // its normal life in addition to changing the behavior of
1042 // the original. As a hack we don't bother to copy the metaclass.
1043 // For some reason we modify the original rather than the copy.
1044 copy = (struct old_class *)_malloc_internal(sizeof(struct old_class));
1045 memmove(copy, imposter, sizeof(struct old_class));
1047 mutex_lock(&classLock);
1049 // Remove both the imposter and the original class.
1050 NXHashRemove (class_hash, imposter);
1051 NXHashRemove (class_hash, original);
1053 NXHashInsert (class_hash, copy);
1054 objc_addRegisteredClass((Class)copy); // imposter & original will rejoin later, just track the new guy
1056 // Mark the imposter as such
1057 _class_setInfo((Class)imposter, CLS_POSING);
1058 _class_setInfo((Class)imposter->isa, CLS_POSING);
1060 // Change the name of the imposter to that of the original class.
1061 imposter->name = original->name;
1062 imposter->isa->name = original->isa->name;
1064 // Also copy the version field to avoid archiving problems.
1065 imposter->version = original->version;
1067 // Change classrefs and superclass pointers
1068 // Don't change copy->super_class
1069 // Don't change [super ...] messages
1070 change_class_references(imposter, original, copy, NO);
1072 // Change the name of the original class.
1073 original->name = imposterNamePtr + 1;
1074 original->isa->name = imposterNamePtr;
1076 // Restore the imposter and the original class with their new names.
1077 NXHashInsert (class_hash, imposter);
1078 NXHashInsert (class_hash, original);
1080 mutex_unlock(&classLock);
1082 return imposter_gen;
1086 /***********************************************************************
1087 * flush_caches. Flush the instance and optionally class method caches
1088 * of cls and all its subclasses.
1090 * Specifying Nil for the class "all classes."
1091 **********************************************************************/
1092 __private_extern__ void flush_caches(Class target_gen, BOOL flush_meta)
1095 struct old_class *target = _class_asOld(target_gen);
1096 struct old_class *clsObject;
1097 #ifdef OBJC_INSTRUMENTED
1098 unsigned int classesVisited;
1099 unsigned int subclassCount;
1102 mutex_lock(&classLock);
1103 mutex_lock(&cacheUpdateLock);
1105 // Leaf classes are fastest because there are no subclass caches to flush.
1107 if (target && (target->info & CLS_LEAF)) {
1108 _cache_flush ((Class)target);
1111 mutex_unlock(&cacheUpdateLock);
1112 mutex_unlock(&classLock);
1114 } else if (target->isa && (target->isa->info & CLS_LEAF)) {
1115 _cache_flush ((Class)target->isa);
1116 mutex_unlock(&cacheUpdateLock);
1117 mutex_unlock(&classLock);
1120 // Reset target and handle it by one of the methods below.
1121 target = target->isa;
1127 state = NXInitHashState(class_hash);
1129 // Handle nil and root instance class specially: flush all
1130 // instance and class method caches. Nice that this
1131 // loop is linear vs the N-squared loop just below.
1132 if (!target || !target->super_class)
1134 #ifdef OBJC_INSTRUMENTED
1135 LinearFlushCachesCount += 1;
1139 // Traverse all classes in the hash table
1140 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1142 struct old_class *metaClsObject;
1143 #ifdef OBJC_INSTRUMENTED
1144 classesVisited += 1;
1147 // Skip class that is known not to be a subclass of this root
1148 // (the isa pointer of any meta class points to the meta class
1150 // NOTE: When is an isa pointer of a hash tabled class ever nil?
1151 metaClsObject = clsObject->isa;
1152 if (target && metaClsObject && target->isa != metaClsObject->isa) {
1156 #ifdef OBJC_INSTRUMENTED
1160 _cache_flush ((Class)clsObject);
1161 if (flush_meta && metaClsObject != NULL) {
1162 _cache_flush ((Class)metaClsObject);
1165 #ifdef OBJC_INSTRUMENTED
1166 LinearFlushCachesVisitedCount += classesVisited;
1167 if (classesVisited > MaxLinearFlushCachesVisitedCount)
1168 MaxLinearFlushCachesVisitedCount = classesVisited;
1169 IdealFlushCachesCount += subclassCount;
1170 if (subclassCount > MaxIdealFlushCachesCount)
1171 MaxIdealFlushCachesCount = subclassCount;
1174 mutex_unlock(&cacheUpdateLock);
1175 mutex_unlock(&classLock);
1179 // Outer loop - flush any cache that could now get a method from
1180 // cls (i.e. the cache associated with cls and any of its subclasses).
1181 #ifdef OBJC_INSTRUMENTED
1182 NonlinearFlushCachesCount += 1;
1186 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1188 struct old_class *clsIter;
1190 #ifdef OBJC_INSTRUMENTED
1191 NonlinearFlushCachesClassCount += 1;
1194 // Inner loop - Process a given class
1195 clsIter = clsObject;
1199 #ifdef OBJC_INSTRUMENTED
1200 classesVisited += 1;
1202 // Flush clsObject instance method cache if
1203 // clsObject is a subclass of cls, or is cls itself
1204 // Flush the class method cache if that was asked for
1205 if (clsIter == target)
1207 #ifdef OBJC_INSTRUMENTED
1210 _cache_flush ((Class)clsObject);
1212 _cache_flush ((Class)clsObject->isa);
1218 // Flush clsObject class method cache if cls is
1219 // the meta class of clsObject or of one
1220 // of clsObject's superclasses
1221 else if (clsIter->isa == target)
1223 #ifdef OBJC_INSTRUMENTED
1226 _cache_flush ((Class)clsObject->isa);
1230 // Move up superclass chain
1231 // else if (_class_isInitialized(clsIter))
1232 clsIter = clsIter->super_class;
1234 // clsIter is not initialized, so its cache
1235 // must be empty. This happens only when
1236 // clsIter == clsObject, because
1237 // superclasses are initialized before
1238 // subclasses, and this loop traverses
1239 // from sub- to super- classes.
1244 #ifdef OBJC_INSTRUMENTED
1245 NonlinearFlushCachesVisitedCount += classesVisited;
1246 if (classesVisited > MaxNonlinearFlushCachesVisitedCount)
1247 MaxNonlinearFlushCachesVisitedCount = classesVisited;
1248 IdealFlushCachesCount += subclassCount;
1249 if (subclassCount > MaxIdealFlushCachesCount)
1250 MaxIdealFlushCachesCount = subclassCount;
1253 mutex_unlock(&cacheUpdateLock);
1254 mutex_unlock(&classLock);
1258 /***********************************************************************
1259 * flush_marked_caches. Flush the method cache of any class marked
1260 * CLS_FLUSH_CACHE (and all subclasses thereof)
1262 **********************************************************************/
1263 __private_extern__ void flush_marked_caches(void)
1265 struct old_class *cls;
1266 struct old_class *supercls;
1269 mutex_lock(&classLock);
1270 mutex_lock(&cacheUpdateLock);
1272 state = NXInitHashState(class_hash);
1273 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1274 for (supercls = cls; supercls; supercls = supercls->super_class) {
1275 if (supercls->info & CLS_FLUSH_CACHE) {
1276 _cache_flush((Class)cls);
1281 for (supercls = cls->isa; supercls; supercls = supercls->super_class) {
1282 if (supercls->info & CLS_FLUSH_CACHE) {
1283 _cache_flush((Class)cls->isa);
1289 state = NXInitHashState(class_hash);
1290 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1291 if (cls->info & CLS_FLUSH_CACHE) {
1292 _class_clearInfo((Class)cls, CLS_FLUSH_CACHE);
1294 if (cls->isa->info & CLS_FLUSH_CACHE) {
1295 _class_clearInfo((Class)cls->isa, CLS_FLUSH_CACHE);
1299 mutex_unlock(&cacheUpdateLock);
1300 mutex_unlock(&classLock);
1304 /***********************************************************************
1305 * get_base_method_list
1306 * Returns the method list containing the class's own methods,
1307 * ignoring any method lists added by categories or class_addMethods.
1308 * Called only by add_class_to_loadable_list.
1309 * Does not hold methodListLock because add_class_to_loadable_list
1310 * does not manipulate in-use classes.
1311 **********************************************************************/
1312 static struct old_method_list *get_base_method_list(struct old_class *cls)
1314 struct old_method_list **ptr;
1316 if (!cls->methodLists) return NULL;
1317 if (cls->info & CLS_NO_METHOD_ARRAY) return (struct old_method_list *)cls->methodLists;
1318 ptr = cls->methodLists;
1319 if (!*ptr || *ptr == END_OF_METHODS_LIST) return NULL;
1320 while ( *ptr != 0 && *ptr != END_OF_METHODS_LIST ) { ptr++; }
1326 static IMP _class_getLoadMethod_nocheck(struct old_class *cls)
1328 struct old_method_list *mlist;
1329 mlist = get_base_method_list(cls->isa);
1331 return lookupNamedMethodInMethodList (mlist, "load");
1337 __private_extern__ BOOL _class_hasLoadMethod(Class cls)
1339 if (oldcls(cls)->isa->info & CLS_HAS_LOAD_METHOD) return YES;
1340 return (_class_getLoadMethod_nocheck(oldcls(cls)) ? YES : NO);
1344 /***********************************************************************
1345 * _class_getLoadMethod
1346 * Returns cls's +load implementation, or NULL if it doesn't have one.
1347 **********************************************************************/
1348 __private_extern__ IMP _class_getLoadMethod(Class cls_gen)
1350 struct old_class *cls = _class_asOld(cls_gen);
1351 if (cls->isa->info & CLS_HAS_LOAD_METHOD) {
1352 return _class_getLoadMethod_nocheck(cls);
1358 __private_extern__ BOOL _class_shouldGrowCache(Class cls)
1360 return _class_getInfo(cls, CLS_GROW_CACHE);
1363 __private_extern__ void _class_setGrowCache(Class cls, BOOL grow)
1365 if (grow) _class_setInfo(cls, CLS_GROW_CACHE);
1366 else _class_clearInfo(cls, CLS_GROW_CACHE);
1369 __private_extern__ BOOL _class_hasCxxStructorsNoSuper(Class cls)
1371 return _class_getInfo(cls, CLS_HAS_CXX_STRUCTORS);
1374 __private_extern__ BOOL _class_shouldFinalizeOnMainThread(Class cls) {
1375 return _class_getInfo(cls, CLS_FINALIZE_ON_MAIN_THREAD);
1378 __private_extern__ void _class_setFinalizeOnMainThread(Class cls) {
1379 _class_setInfo(cls, CLS_FINALIZE_ON_MAIN_THREAD);
1382 __private_extern__ BOOL _class_instancesHaveAssociatedObjects(Class cls) {
1383 return _class_getInfo(cls, CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS);
1386 __private_extern__ void _class_assertInstancesHaveAssociatedObjects(Class cls) {
1387 _class_setInfo(cls, CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS);
1390 __private_extern__ struct old_ivar *_ivar_asOld(Ivar ivar)
1392 return (struct old_ivar *)ivar;
1395 ptrdiff_t ivar_getOffset(Ivar ivar)
1397 return _ivar_asOld(ivar)->ivar_offset;
1400 const char *ivar_getName(Ivar ivar)
1402 return _ivar_asOld(ivar)->ivar_name;
1405 const char *ivar_getTypeEncoding(Ivar ivar)
1407 return _ivar_asOld(ivar)->ivar_type;
1411 IMP method_getImplementation(Method m)
1413 if (!m) return NULL;
1414 return _method_asOld(m)->method_imp;
1417 SEL method_getName(Method m)
1419 if (!m) return NULL;
1420 return _method_asOld(m)->method_name;
1423 const char *method_getTypeEncoding(Method m)
1425 if (!m) return NULL;
1426 return _method_asOld(m)->method_types;
1429 static OSSpinLock impLock = OS_SPINLOCK_INIT;
1431 IMP method_setImplementation(Method m_gen, IMP imp)
1434 struct old_method *m = _method_asOld(m_gen);
1435 if (!m) return NULL;
1436 if (!imp) return NULL;
1438 if (m->method_name == (SEL)kIgnore) {
1439 // Ignored methods stay ignored
1440 return m->method_imp;
1443 OSSpinLockLock(&impLock);
1444 old = m->method_imp;
1445 m->method_imp = imp;
1446 OSSpinLockUnlock(&impLock);
1451 void method_exchangeImplementations(Method m1_gen, Method m2_gen)
1454 struct old_method *m1 = _method_asOld(m1_gen);
1455 struct old_method *m2 = _method_asOld(m2_gen);
1456 if (!m1 || !m2) return;
1458 if (m1->method_name == (SEL)kIgnore || m2->method_name == (SEL)kIgnore) {
1459 // Ignored methods stay ignored. Now they're both ignored.
1460 m1->method_imp = (IMP)&_objc_ignored_method;
1461 m2->method_imp = (IMP)&_objc_ignored_method;
1465 OSSpinLockLock(&impLock);
1466 m1_imp = m1->method_imp;
1467 m1->method_imp = m2->method_imp;
1468 m2->method_imp = m1_imp;
1469 OSSpinLockUnlock(&impLock);
1473 struct objc_method_description * method_getDescription(Method m)
1475 if (!m) return NULL;
1476 return (struct objc_method_description *)oldmethod(m);
1480 /***********************************************************************
1482 **********************************************************************/
1483 static IMP _class_addMethod(Class cls_gen, SEL name, IMP imp,
1484 const char *types, BOOL replace)
1486 struct old_class *cls = oldcls(cls_gen);
1487 struct old_method *m;
1490 if (!types) types = "";
1492 mutex_lock(&methodListLock);
1494 if ((m = _findMethodInClass(cls, name))) {
1497 result = method_getImplementation((Method)m);
1499 method_setImplementation((Method)m, imp);
1502 // fixme could be faster
1503 struct old_method_list *mlist =
1504 _calloc_internal(sizeof(struct old_method_list), 1);
1505 mlist->obsolete = fixed_up_method_list;
1506 mlist->method_count = 1;
1507 mlist->method_list[0].method_name = name;
1508 mlist->method_list[0].method_types = _strdup_internal(types);
1509 if (name != (SEL)kIgnore) {
1510 mlist->method_list[0].method_imp = imp;
1512 mlist->method_list[0].method_imp = (IMP)&_objc_ignored_method;
1515 _objc_insertMethods(cls, mlist, NULL);
1516 if (!(cls->info & CLS_CONSTRUCTING)) {
1517 flush_caches((Class)cls, NO);
1519 // in-construction class has no subclasses
1520 flush_cache((Class)cls);
1525 mutex_unlock(&methodListLock);
1531 /***********************************************************************
1533 **********************************************************************/
1534 BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
1537 if (!cls) return NO;
1539 old = _class_addMethod(cls, name, imp, types, NO);
1540 return old ? NO : YES;
1544 /***********************************************************************
1545 * class_replaceMethod
1546 **********************************************************************/
1547 IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
1549 if (!cls) return NULL;
1551 return _class_addMethod(cls, name, imp, types, YES);
1555 /***********************************************************************
1557 **********************************************************************/
1558 BOOL class_addIvar(Class cls_gen, const char *name, size_t size,
1559 uint8_t alignment, const char *type)
1561 struct old_class *cls = oldcls(cls_gen);
1564 if (!cls) return NO;
1565 if (ISMETA(cls)) return NO;
1566 if (!(cls->info & CLS_CONSTRUCTING)) return NO;
1568 if (!type) type = "";
1569 if (name && 0 == strcmp(name, "")) name = NULL;
1571 mutex_lock(&classLock);
1573 // Check for existing ivar with this name
1574 // fixme check superclasses?
1577 for (i = 0; i < cls->ivars->ivar_count; i++) {
1578 if (0 == strcmp(cls->ivars->ivar_list[i].ivar_name, name)) {
1586 struct old_ivar_list *old = cls->ivars;
1589 struct old_ivar *ivar;
1594 oldSize = sizeof(struct old_ivar_list) +
1595 (old->ivar_count - 1) * sizeof(struct old_ivar);
1596 newCount = 1 + old->ivar_count;
1598 oldSize = sizeof(struct old_ivar_list) - sizeof(struct old_ivar);
1602 // allocate new ivar list
1603 cls->ivars = _calloc_internal(oldSize + sizeof(struct old_ivar), 1);
1604 if (old) memcpy(cls->ivars, old, oldSize);
1605 if (old && malloc_size(old)) free(old);
1606 cls->ivars->ivar_count = newCount;
1607 ivar = &cls->ivars->ivar_list[newCount-1];
1609 // set ivar name and type
1610 ivar->ivar_name = _strdup_internal(name);
1611 ivar->ivar_type = _strdup_internal(type);
1613 // align if necessary
1614 alignBytes = 1 << alignment;
1615 misalign = cls->instance_size % alignBytes;
1616 if (misalign) cls->instance_size += (long)(alignBytes - misalign);
1618 // set ivar offset and increase instance size
1619 ivar->ivar_offset = (int)cls->instance_size;
1620 cls->instance_size += (long)size;
1623 mutex_unlock(&classLock);
1629 /***********************************************************************
1631 **********************************************************************/
1632 BOOL class_addProtocol(Class cls_gen, Protocol *protocol_gen)
1634 struct old_class *cls = oldcls(cls_gen);
1635 struct old_protocol *protocol = oldprotocol(protocol_gen);
1636 struct old_protocol_list *plist;
1638 if (!cls) return NO;
1639 if (class_conformsToProtocol(cls_gen, protocol_gen)) return NO;
1641 mutex_lock(&classLock);
1643 // fixme optimize - protocol list doesn't escape?
1644 plist = _calloc_internal(sizeof(struct old_protocol_list), 1);
1646 plist->list[0] = protocol;
1647 plist->next = cls->protocols;
1648 cls->protocols = plist;
1652 mutex_unlock(&classLock);
1658 /***********************************************************************
1660 **********************************************************************/
1661 __private_extern__ void
1662 _class_addProperties(struct old_class *cls,
1663 struct objc_property_list *additions)
1665 struct objc_property_list *newlist;
1667 if (!(cls->info & CLS_EXT)) return;
1670 _memdup_internal(additions, sizeof(*newlist) - sizeof(newlist->first)
1671 + (additions->entsize * additions->count));
1673 mutex_lock(&classLock);
1676 if (!cls->ext->propertyLists) {
1677 // cls has no properties - simply use this list
1678 cls->ext->propertyLists = (struct objc_property_list **)newlist;
1679 _class_setInfo((Class)cls, CLS_NO_PROPERTY_ARRAY);
1681 else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
1682 // cls has one property list - make a new array
1683 struct objc_property_list **newarray =
1684 _malloc_internal(3 * sizeof(*newarray));
1685 newarray[0] = newlist;
1686 newarray[1] = (struct objc_property_list *)cls->ext->propertyLists;
1688 cls->ext->propertyLists = newarray;
1689 _class_clearInfo((Class)cls, CLS_NO_PROPERTY_ARRAY);
1692 // cls has a property array - make a bigger one
1693 struct objc_property_list **newarray;
1695 while (cls->ext->propertyLists[count]) count++;
1696 newarray = _malloc_internal((count+2) * sizeof(*newarray));
1697 newarray[0] = newlist;
1698 memcpy(&newarray[1], &cls->ext->propertyLists[0],
1699 count * sizeof(*newarray));
1700 newarray[count+1] = NULL;
1701 free(cls->ext->propertyLists);
1702 cls->ext->propertyLists = newarray;
1705 mutex_unlock(&classLock);
1709 /***********************************************************************
1710 * class_copyProtocolList. Returns a heap block containing the
1711 * protocols implemented by the class, or NULL if the class
1712 * implements no protocols. Caller must free the block.
1713 * Does not copy any superclass's protocols.
1714 **********************************************************************/
1715 Protocol **class_copyProtocolList(Class cls_gen, unsigned int *outCount)
1717 struct old_class *cls = oldcls(cls_gen);
1718 struct old_protocol_list *plist;
1719 Protocol **result = NULL;
1720 unsigned int count = 0;
1724 if (outCount) *outCount = 0;
1728 mutex_lock(&classLock);
1730 for (plist = cls->protocols; plist != NULL; plist = plist->next) {
1731 count += (int)plist->count;
1735 result = malloc((count+1) * sizeof(Protocol *));
1737 for (p = 0, plist = cls->protocols;
1739 plist = plist->next)
1742 for (i = 0; i < plist->count; i++) {
1743 result[p++] = (Protocol *)plist->list[i];
1749 mutex_unlock(&classLock);
1751 if (outCount) *outCount = count;
1756 /***********************************************************************
1757 * class_getProperty. Return the named property.
1758 **********************************************************************/
1759 Property class_getProperty(Class cls_gen, const char *name)
1762 struct old_class *cls = _class_asOld(cls_gen);
1763 if (!cls || !name) return NULL;
1765 mutex_lock(&classLock);
1767 for (result = NULL; cls && !result; cls = cls->super_class) {
1768 uintptr_t iterator = 0;
1769 struct objc_property_list *plist;
1770 while ((plist = nextPropertyList(cls, &iterator))) {
1772 for (i = 0; i < plist->count; i++) {
1773 Property p = property_list_nth(plist, i);
1774 if (0 == strcmp(name, p->name)) {
1783 mutex_unlock(&classLock);
1789 /***********************************************************************
1790 * class_copyPropertyList. Returns a heap block containing the
1791 * properties declared in the class, or NULL if the class
1792 * declares no properties. Caller must free the block.
1793 * Does not copy any superclass's properties.
1794 **********************************************************************/
1795 Property *class_copyPropertyList(Class cls_gen, unsigned int *outCount)
1797 struct old_class *cls = oldcls(cls_gen);
1798 struct objc_property_list *plist;
1799 uintptr_t iterator = 0;
1800 Property *result = NULL;
1801 unsigned int count = 0;
1805 if (outCount) *outCount = 0;
1809 mutex_lock(&classLock);
1812 while ((plist = nextPropertyList(cls, &iterator))) {
1813 count += plist->count;
1817 result = malloc((count+1) * sizeof(Property));
1821 while ((plist = nextPropertyList(cls, &iterator))) {
1822 for (i = 0; i < plist->count; i++) {
1823 result[p++] = property_list_nth(plist, i);
1829 mutex_unlock(&classLock);
1831 if (outCount) *outCount = count;
1836 /***********************************************************************
1837 * class_copyMethodList. Returns a heap block containing the
1838 * methods implemented by the class, or NULL if the class
1839 * implements no methods. Caller must free the block.
1840 * Does not copy any superclass's methods.
1841 **********************************************************************/
1842 Method *class_copyMethodList(Class cls_gen, unsigned int *outCount)
1844 struct old_class *cls = oldcls(cls_gen);
1845 struct old_method_list *mlist;
1846 void *iterator = NULL;
1847 Method *result = NULL;
1848 unsigned int count = 0;
1852 if (outCount) *outCount = 0;
1856 mutex_lock(&methodListLock);
1859 while ((mlist = nextMethodList(cls, &iterator))) {
1860 count += mlist->method_count;
1864 result = malloc((count+1) * sizeof(Method));
1868 while ((mlist = nextMethodList(cls, &iterator))) {
1870 for (i = 0; i < mlist->method_count; i++) {
1871 Method aMethod = (Method)&mlist->method_list[i];
1872 if (method_getName(aMethod) == (SEL)kIgnore) {
1876 result[m++] = aMethod;
1882 mutex_unlock(&methodListLock);
1884 if (outCount) *outCount = count;
1889 /***********************************************************************
1890 * class_copyIvarList. Returns a heap block containing the
1891 * ivars declared in the class, or NULL if the class
1892 * declares no ivars. Caller must free the block.
1893 * Does not copy any superclass's ivars.
1894 **********************************************************************/
1895 Ivar *class_copyIvarList(Class cls_gen, unsigned int *outCount)
1897 struct old_class *cls = oldcls(cls_gen);
1898 Ivar *result = NULL;
1899 unsigned int count = 0;
1903 if (outCount) *outCount = 0;
1908 count = cls->ivars->ivar_count;
1912 result = malloc((count+1) * sizeof(Ivar));
1914 for (i = 0; i < cls->ivars->ivar_count; i++) {
1915 result[i] = (Ivar)&cls->ivars->ivar_list[i];
1920 if (outCount) *outCount = count;
1925 /***********************************************************************
1926 * objc_allocateClass.
1927 **********************************************************************/
1929 void set_superclass(struct old_class *cls, struct old_class *supercls)
1931 struct old_class *meta = cls->isa;
1934 cls->super_class = supercls;
1935 meta->super_class = supercls->isa;
1936 meta->isa = supercls->isa->isa;
1938 // Superclass is no longer a leaf for cache flushing
1939 if (supercls->info & CLS_LEAF) {
1940 _class_clearInfo((Class)supercls, CLS_LEAF);
1941 _class_clearInfo((Class)supercls->isa, CLS_LEAF);
1944 cls->super_class = Nil; // superclass of root class is nil
1945 meta->super_class = cls; // superclass of root metaclass is root class
1946 meta->isa = meta; // metaclass of root metaclass is root metaclass
1948 // Root class is never a leaf for cache flushing, because the
1949 // root metaclass is a subclass. (This could be optimized, but
1950 // is too uncommon to bother.)
1951 _class_clearInfo((Class)cls, CLS_LEAF);
1952 _class_clearInfo((Class)meta, CLS_LEAF);
1956 void objc_initializeClassPair(Class superclass_gen, const char *name, Class cls_gen, Class meta_gen)
1958 struct old_class *supercls = oldcls(superclass_gen);
1959 struct old_class *cls = oldcls(cls_gen);
1960 struct old_class *meta = oldcls(meta_gen);
1962 // Connect to superclasses and metaclasses
1964 set_superclass(cls, supercls);
1967 cls->name = _strdup_internal(name);
1968 meta->name = _strdup_internal(name);
1971 cls->info = CLS_CLASS | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
1972 meta->info = CLS_META | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
1974 // Set instance size based on superclass.
1976 cls->instance_size = supercls->instance_size;
1977 meta->instance_size = supercls->isa->instance_size;
1979 cls->instance_size = sizeof(struct old_class *); // just an isa
1980 meta->instance_size = sizeof(struct old_class);
1983 // No ivars. No methods. Empty cache. No protocols. No layout. No ext.
1985 cls->methodLists = NULL;
1986 cls->cache = (Cache)&_objc_empty_cache;
1987 cls->protocols = NULL;
1991 meta->methodLists = NULL;
1992 meta->cache = (Cache)&_objc_empty_cache;
1993 meta->protocols = NULL;
1997 Class objc_allocateClassPair(Class superclass_gen, const char *name,
2000 struct old_class *supercls = oldcls(superclass_gen);
2003 if (objc_getClass(name)) return NO;
2004 // fixme reserve class name against simultaneous allocation
2006 if (supercls && (supercls->info & CLS_CONSTRUCTING)) {
2007 // Can't make subclass of an in-construction class
2011 // Allocate new classes.
2013 cls = _calloc_class(supercls->isa->instance_size + extraBytes);
2014 meta = _calloc_class(supercls->isa->isa->instance_size + extraBytes);
2016 cls = _calloc_class(sizeof(struct old_class) + extraBytes);
2017 meta = _calloc_class(sizeof(struct old_class) + extraBytes);
2021 objc_initializeClassPair(superclass_gen, name, cls, meta);
2027 void objc_registerClassPair(Class cls_gen)
2029 struct old_class *cls = oldcls(cls_gen);
2031 if ((cls->info & CLS_CONSTRUCTED) ||
2032 (cls->isa->info & CLS_CONSTRUCTED))
2034 _objc_inform("objc_registerClassPair: class '%s' was already "
2035 "registered!", cls->name);
2039 if (!(cls->info & CLS_CONSTRUCTING) ||
2040 !(cls->isa->info & CLS_CONSTRUCTING))
2042 _objc_inform("objc_registerClassPair: class '%s' was not "
2043 "allocated with objc_allocateClassPair!", cls->name);
2048 _objc_inform("objc_registerClassPair: class '%s' is a metaclass, "
2049 "not a class!", cls->name);
2053 mutex_lock(&classLock);
2055 // Build ivar layouts
2057 if (cls->ivar_layout) {
2058 // Class builder already called class_setIvarLayout.
2060 else if (!cls->super_class) {
2061 // Root class. Scan conservatively (should be isa ivar only).
2062 // ivar_layout is already NULL.
2064 else if (cls->ivars == NULL) {
2065 // No local ivars. Use superclass's layout.
2067 _strdup_internal(cls->super_class->ivar_layout);
2070 // Has local ivars. Build layout based on superclass.
2071 struct old_class *supercls = cls->super_class;
2072 unsigned char *superlayout =
2073 (unsigned char *) class_getIvarLayout((Class)supercls);
2074 layout_bitmap bitmap =
2075 layout_bitmap_create(superlayout, supercls->instance_size,
2076 cls->instance_size, NO);
2078 for (i = 0; i < cls->ivars->ivar_count; i++) {
2079 struct old_ivar *iv = &cls->ivars->ivar_list[i];
2080 layout_bitmap_set_ivar(bitmap, iv->ivar_type, iv->ivar_offset);
2082 cls->ivar_layout = (char *)layout_string_create(bitmap);
2083 layout_bitmap_free(bitmap);
2086 if (cls->ext && cls->ext->weak_ivar_layout) {
2087 // Class builder already called class_setWeakIvarLayout.
2089 else if (!cls->super_class) {
2090 // Root class. No weak ivars (should be isa ivar only)
2091 // weak_ivar_layout is already NULL.
2093 else if (cls->ivars == NULL) {
2094 // No local ivars. Use superclass's layout.
2096 class_getWeakIvarLayout((Class)cls->super_class);
2099 cls->ext->weak_ivar_layout = _strdup_internal(weak);
2103 // Has local ivars. Build layout based on superclass.
2104 // No way to add weak ivars yet.
2106 class_getWeakIvarLayout((Class)cls->super_class);
2109 cls->ext->weak_ivar_layout = _strdup_internal(weak);
2114 // Clear "under construction" bit, set "done constructing" bit
2115 cls->info &= ~CLS_CONSTRUCTING;
2116 cls->isa->info &= ~CLS_CONSTRUCTING;
2117 cls->info |= CLS_CONSTRUCTED;
2118 cls->isa->info |= CLS_CONSTRUCTED;
2120 NXHashInsertIfAbsent(class_hash, cls);
2121 objc_addRegisteredClass((Class)cls);
2122 //objc_addRegisteredClass(cls->isa); if we ever allocate classes from GC
2124 mutex_unlock(&classLock);
2128 Class objc_duplicateClass(Class orig_gen, const char *name, size_t extraBytes)
2130 unsigned int count, i;
2131 struct old_method **originalMethods;
2132 struct old_method_list *duplicateMethods;
2133 struct old_class *original = oldcls(orig_gen);
2134 // Don't use sizeof(struct objc_class) here because
2135 // instance_size has historically contained two extra words,
2136 // and instance_size is what objc_getIndexedIvars() actually uses.
2137 struct old_class *duplicate = (struct old_class *)
2138 _calloc_class(original->isa->instance_size + extraBytes);
2140 duplicate->isa = original->isa;
2141 duplicate->super_class = original->super_class;
2142 duplicate->name = strdup(name);
2143 duplicate->version = original->version;
2144 duplicate->info = original->info & (CLS_CLASS|CLS_META|CLS_INITIALIZED|CLS_JAVA_HYBRID|CLS_JAVA_CLASS|CLS_HAS_CXX_STRUCTORS|CLS_HAS_LOAD_METHOD);
2145 duplicate->instance_size = original->instance_size;
2146 duplicate->ivars = original->ivars;
2147 // methodLists handled below
2148 duplicate->cache = (Cache)&_objc_empty_cache;
2149 duplicate->protocols = original->protocols;
2150 if (original->info & CLS_EXT) {
2151 duplicate->info |= original->info & (CLS_EXT|CLS_NO_PROPERTY_ARRAY);
2152 duplicate->ivar_layout = original->ivar_layout;
2153 if (original->ext) {
2154 duplicate->ext = _malloc_internal(original->ext->size);
2155 memcpy(duplicate->ext, original->ext, original->ext->size);
2157 duplicate->ext = NULL;
2161 // Method lists are deep-copied so they can be stomped.
2162 originalMethods = (struct old_method **)
2163 class_copyMethodList(orig_gen, &count);
2164 if (originalMethods) {
2165 duplicateMethods = (struct old_method_list *)
2166 calloc(sizeof(struct old_method_list) +
2167 (count-1)*sizeof(struct old_method), 1);
2168 duplicateMethods->obsolete = fixed_up_method_list;
2169 duplicateMethods->method_count = count;
2170 for (i = 0; i < count; i++) {
2171 duplicateMethods->method_list[i] = *(originalMethods[i]);
2173 duplicate->methodLists = (struct old_method_list **)duplicateMethods;
2174 duplicate->info |= CLS_NO_METHOD_ARRAY;
2175 free(originalMethods);
2178 mutex_lock(&classLock);
2179 NXHashInsert(class_hash, duplicate);
2180 objc_addRegisteredClass((Class)duplicate);
2181 mutex_unlock(&classLock);
2183 return (Class)duplicate;
2187 void objc_disposeClassPair(Class cls_gen)
2189 struct old_class *cls = oldcls(cls_gen);
2191 if (!(cls->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)) ||
2192 !(cls->isa->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)))
2194 // class not allocated with objc_allocateClassPair
2195 // disposing still-unregistered class is OK!
2196 _objc_inform("objc_disposeClassPair: class '%s' was not "
2197 "allocated with objc_allocateClassPair!", cls->name);
2202 _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
2203 "not a class!", cls->name);
2207 mutex_lock(&classLock);
2208 NXHashRemove(class_hash, cls);
2209 objc_removeRegisteredClass((Class)cls);
2210 unload_class(cls->isa);
2212 mutex_unlock(&classLock);
2216 /***********************************************************************
2217 * _internal_class_createInstance. Allocate an instance of the specified
2218 * class with the specified number of bytes for indexed variables, in
2219 * the default zone, using _internal_class_createInstanceFromZone.
2220 **********************************************************************/
2221 static id _internal_class_createInstance(Class cls, size_t extraBytes)
2223 return _internal_class_createInstanceFromZone (cls, extraBytes, NULL);
2227 static id _internal_object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
2232 if (!oldObj) return nil;
2234 obj = (*_zoneAlloc)(oldObj->isa, extraBytes, zone);
2235 size = _class_getInstanceSize(oldObj->isa) + extraBytes;
2237 // fixme need C++ copy constructor
2238 objc_memmove_collectable(obj, oldObj, size);
2241 if (UseGC) gc_fixup_weakreferences(obj, oldObj);
2247 static id _internal_object_copy(id oldObj, size_t extraBytes)
2249 void *z = malloc_zone_from_ptr(oldObj);
2250 return _internal_object_copyFromZone(oldObj, extraBytes,
2251 z ? z : malloc_default_zone());
2254 static id _internal_object_reallocFromZone(id anObject, size_t nBytes,
2260 if (anObject == nil)
2261 __objc_error(nil, "reallocating nil object");
2263 if (anObject->isa == _objc_getFreedObjectClass ())
2264 __objc_error(anObject, "reallocating freed object");
2266 if (nBytes < _class_getInstanceSize(anObject->isa))
2267 __objc_error(anObject, "(%s, %zu) requested size too small",
2268 object_getClassName(anObject), nBytes);
2270 // fixme need C++ copy constructor
2272 // Make sure not to modify space that has been declared free
2273 tmp = anObject->isa;
2274 anObject->isa = _objc_getFreedObjectClass ();
2275 newObject = (id)malloc_zone_realloc(zone, anObject, nBytes);
2277 newObject->isa = tmp;
2279 // realloc failed, anObject is still alive
2280 anObject->isa = tmp;
2286 static id _internal_object_realloc(id anObject, size_t nBytes)
2288 void *z = malloc_zone_from_ptr(anObject);
2289 return _internal_object_reallocFromZone(anObject,
2291 z ? z : malloc_default_zone());
2294 id (*_alloc)(Class, size_t) = _internal_class_createInstance;
2295 id (*_copy)(id, size_t) = _internal_object_copy;
2296 id (*_realloc)(id, size_t) = _internal_object_realloc;
2297 id (*_dealloc)(id) = _internal_object_dispose;
2298 id (*_zoneAlloc)(Class, size_t, void *) = _internal_class_createInstanceFromZone;
2299 id (*_zoneCopy)(id, size_t, void *) = _internal_object_copyFromZone;
2300 id (*_zoneRealloc)(id, size_t, void *) = _internal_object_reallocFromZone;
2301 void (*_error)(id, const char *, va_list) = _objc_error;
2304 id class_createInstance(Class cls, size_t extraBytes)
2307 return _internal_class_createInstance(cls, extraBytes);
2309 return (*_alloc)(cls, extraBytes);
2313 id class_createInstanceFromZone(Class cls, size_t extraBytes, void *z)
2315 OBJC_WARN_DEPRECATED;
2317 return _internal_class_createInstanceFromZone(cls, extraBytes, z);
2319 return (*_zoneAlloc)(cls, extraBytes, z);
2323 id object_copy(id obj, size_t extraBytes)
2325 if (UseGC) return _internal_object_copy(obj, extraBytes);
2326 else return (*_copy)(obj, extraBytes);
2329 id object_copyFromZone(id obj, size_t extraBytes, void *z)
2331 OBJC_WARN_DEPRECATED;
2332 if (UseGC) return _internal_object_copyFromZone(obj, extraBytes, z);
2333 else return (*_zoneCopy)(obj, extraBytes, z);
2336 id object_dispose(id obj)
2338 if (UseGC) return _internal_object_dispose(obj);
2339 else return (*_dealloc)(obj);
2342 id object_realloc(id obj, size_t nBytes)
2344 OBJC_WARN_DEPRECATED;
2345 if (UseGC) return _internal_object_realloc(obj, nBytes);
2346 else return (*_realloc)(obj, nBytes);
2349 id object_reallocFromZone(id obj, size_t nBytes, void *z)
2351 OBJC_WARN_DEPRECATED;
2352 if (UseGC) return _internal_object_reallocFromZone(obj, nBytes, z);
2353 else return (*_zoneRealloc)(obj, nBytes, z);
2358 Class class_setSuperclass(Class cls, Class newSuper)
2360 Class oldSuper = cls->super_class;
2361 set_superclass(oldcls(cls), oldcls(newSuper));
2362 flush_caches(cls, YES);