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"
33 #include "objc-file-old.h"
34 #include "objc-cache-old.h"
36 static Method _class_getMethod(Class cls, SEL sel);
37 static Method _class_getMethodNoSuper(Class cls, SEL sel);
38 static Method _class_getMethodNoSuper_nolock(Class cls, SEL sel);
39 static void flush_caches(Class cls, bool flush_meta);
42 // Freed objects have their isa set to point to this dummy class.
43 // This avoids the need to check for Nil classes in the messenger.
44 static const void* freedObjectClass[12] =
54 (Cache) &_objc_empty_cache, // cache
61 /***********************************************************************
62 * _class_getFreedObjectClass. Return a pointer to the dummy freed
63 * object class. Freed objects get their isa pointers replaced with
64 * a pointer to the freedObjectClass, so that we can catch usages of
66 **********************************************************************/
67 static Class _class_getFreedObjectClass(void)
69 return (Class)freedObjectClass;
73 /***********************************************************************
74 * _objc_getFreedObjectClass. Return a pointer to the dummy freed
75 * object class. Freed objects get their isa pointers replaced with
76 * a pointer to the freedObjectClass, so that we can catch usages of
78 **********************************************************************/
79 Class _objc_getFreedObjectClass(void)
81 return _class_getFreedObjectClass();
85 static void allocateExt(Class cls)
87 if (! (cls->info & CLS_EXT)) {
88 _objc_inform("class '%s' needs to be recompiled", cls->name);
92 uint32_t size = (uint32_t)sizeof(old_class_ext);
93 cls->ext = (old_class_ext *)calloc(size, 1);
94 cls->ext->size = size;
99 static inline old_method *_findNamedMethodInList(old_method_list * mlist, const char *meth_name) {
101 if (!mlist) return nil;
102 for (i = 0; i < mlist->method_count; i++) {
103 old_method *m = &mlist->method_list[i];
104 if (0 == strcmp((const char *)(m->method_name), meth_name)) {
112 /***********************************************************************
113 * Method list fixup markers.
114 * mlist->obsolete == fixed_up_method_list marks method lists with real SELs
115 * versus method lists with un-uniqued char*.
116 * PREOPTIMIZED VERSION:
117 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP
118 * dyld shared cache sets this for method lists it preoptimizes.
119 * UN-PREOPTIMIZED VERSION
120 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP_outside_dyld
121 * dyld shared cache uses OBJC_FIXED_UP, but those aren't trusted.
122 **********************************************************************/
123 #define OBJC_FIXED_UP ((void *)1771)
124 #define OBJC_FIXED_UP_outside_dyld ((void *)1773)
125 static void *fixed_up_method_list = OBJC_FIXED_UP;
127 // sel_init() decided that selectors in the dyld shared cache are untrustworthy
128 void disableSharedCacheOptimizations(void)
130 fixed_up_method_list = OBJC_FIXED_UP_outside_dyld;
133 /***********************************************************************
134 * fixupSelectorsInMethodList
135 * Uniques selectors in the given method list.
136 * The given method list must be non-nil and not already fixed-up.
137 * If the class was loaded from a bundle:
138 * fixes up the given list in place with heap-allocated selector strings
139 * If the class was not from a bundle:
140 * allocates a copy of the method list, fixes up the copy, and returns
141 * the copy. The given list is unmodified.
143 * If cls is already in use, methodListLock must be held by the caller.
144 **********************************************************************/
145 static old_method_list *fixupSelectorsInMethodList(Class cls, old_method_list *mlist)
150 old_method_list *old_mlist;
152 if ( ! mlist ) return nil;
153 if ( mlist->obsolete == fixed_up_method_list ) {
156 bool isBundle = cls->info & CLS_FROM_BUNDLE;
159 size = sizeof(old_method_list) - sizeof(old_method) + old_mlist->method_count * sizeof(old_method);
160 mlist = (old_method_list *)malloc(size);
161 memmove(mlist, old_mlist, size);
163 // Mach-O bundles are fixed up in place.
164 // This prevents leaks when a bundle is unloaded.
167 for ( i = 0; i < mlist->method_count; i += 1 ) {
168 method = &mlist->method_list[i];
169 method->method_name =
170 sel_registerNameNoLock((const char *)method->method_name, isBundle); // Always copy selector data from bundles.
173 mlist->obsolete = fixed_up_method_list;
179 /***********************************************************************
181 * Returns successive method lists from the given class.
182 * Method lists are returned in method search order (i.e. highest-priority
183 * implementations first).
184 * All necessary method list fixups are performed, so the
185 * returned method list is fully-constructed.
187 * If cls is already in use, methodListLock must be held by the caller.
188 * For full thread-safety, methodListLock must be continuously held by the
189 * caller across all calls to nextMethodList(). If the lock is released,
190 * the bad results listed in class_nextMethodList() may occur.
192 * void *iterator = nil;
193 * old_method_list *mlist;
194 * mutex_locker_t lock(methodListLock);
195 * while ((mlist = nextMethodList(cls, &iterator))) {
196 * // do something with mlist
198 **********************************************************************/
199 static old_method_list *nextMethodList(Class cls,
202 uintptr_t index = *(uintptr_t *)it;
203 old_method_list **resultp;
206 // First call to nextMethodList.
207 if (!cls->methodLists) {
209 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
210 resultp = (old_method_list **)&cls->methodLists;
212 resultp = &cls->methodLists[0];
213 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
218 // Subsequent call to nextMethodList.
219 if (!cls->methodLists) {
221 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
224 resultp = &cls->methodLists[index];
225 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
231 // resultp now is nil, meaning there are no more method lists,
232 // OR the address of the method list pointer to fix up and return.
236 *resultp = fixupSelectorsInMethodList(cls, *resultp);
238 *it = (void *)(index + 1);
247 /* These next three functions are the heart of ObjC method lookup.
248 * If the class is currently in use, methodListLock must be held by the caller.
250 static inline old_method *_findMethodInList(old_method_list * mlist, SEL sel) {
252 if (!mlist) return nil;
253 for (i = 0; i < mlist->method_count; i++) {
254 old_method *m = &mlist->method_list[i];
255 if (m->method_name == sel) {
262 static inline old_method * _findMethodInClass(Class cls, SEL sel) __attribute__((always_inline));
263 static inline old_method * _findMethodInClass(Class cls, SEL sel) {
264 // Flattened version of nextMethodList(). The optimizer doesn't
265 // do a good job with hoisting the conditionals out of the loop.
266 // Conceptually, this looks like:
267 // while ((mlist = nextMethodList(cls, &iterator))) {
268 // old_method *m = _findMethodInList(mlist, sel);
272 if (!cls->methodLists) {
276 else if (cls->info & CLS_NO_METHOD_ARRAY) {
278 old_method_list **mlistp;
279 mlistp = (old_method_list **)&cls->methodLists;
280 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
281 return _findMethodInList(*mlistp, sel);
284 // Multiple method lists.
285 old_method_list **mlistp;
286 for (mlistp = cls->methodLists;
287 *mlistp != nil && *mlistp != END_OF_METHODS_LIST;
291 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
292 m = _findMethodInList(*mlistp, sel);
299 static inline old_method * _getMethod(Class cls, SEL sel) {
300 for (; cls; cls = cls->superclass) {
302 m = _findMethodInClass(cls, sel);
309 // called by a debugging check in _objc_insertMethods
310 IMP findIMPInClass(Class cls, SEL sel)
312 old_method *m = _findMethodInClass(cls, sel);
313 if (m) return m->method_imp;
318 /***********************************************************************
320 **********************************************************************/
321 static void _freedHandler(id obj, SEL sel)
323 __objc_error (obj, "message %s sent to freed object=%p",
324 sel_getName(sel), (void*)obj);
328 /***********************************************************************
330 * Log this method call. If the logger permits it, fill the method cache.
331 * cls is the method whose cache should be filled.
332 * implementer is the class that owns the implementation in question.
333 **********************************************************************/
335 log_and_fill_cache(Class cls, Class implementer, Method meth, SEL sel)
337 #if SUPPORT_MESSAGE_LOGGING
338 if (objcMsgLogEnabled) {
339 bool cacheIt = logMessageSend(implementer->isMetaClass(),
340 cls->nameForLogging(),
341 implementer->nameForLogging(),
343 if (!cacheIt) return;
346 _cache_fill (cls, meth, sel);
350 /***********************************************************************
351 * _class_lookupMethodAndLoadCache.
352 * Method lookup for dispatchers ONLY. OTHER CODE SHOULD USE lookUpImp().
353 * This lookup avoids optimistic cache scan because the dispatcher
354 * already tried that.
355 **********************************************************************/
356 IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
358 return lookUpImpOrForward(cls, sel, obj,
359 YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
363 /***********************************************************************
364 * lookUpImpOrForward.
365 * The standard IMP lookup.
366 * initialize==NO tries to avoid +initialize (but sometimes fails)
367 * cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
368 * Most callers should use initialize==YES and cache==YES.
369 * inst is an instance of cls or a subclass thereof, or nil if none is known.
370 * If cls is an un-initialized metaclass then a non-nil inst is faster.
371 * May return _objc_msgForward_impcache. IMPs destined for external use
372 * must be converted to _objc_msgForward or _objc_msgForward_stret.
373 * If you don't want forwarding at all, use lookUpImpOrNil() instead.
374 **********************************************************************/
375 IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
376 bool initialize, bool cache, bool resolver)
381 bool triedResolver = NO;
383 methodListLock.assertUnlocked();
385 // Optimistic cache lookup
387 methodPC = _cache_getImp(cls, sel);
388 if (methodPC) return methodPC;
391 // Check for freed class
392 if (cls == _class_getFreedObjectClass())
393 return (IMP) _freedHandler;
395 // Check for +initialize
396 if (initialize && !cls->isInitialized()) {
397 _class_initialize (_class_getNonMetaClass(cls, inst));
398 // If sel == initialize, _class_initialize will send +initialize and
399 // then the messenger will send +initialize again after this
400 // procedure finishes. Of course, if this is not being called
401 // from the messenger then it won't happen. 2778172
404 // The lock is held to make method-lookup + cache-fill atomic
405 // with respect to method addition. Otherwise, a category could
406 // be added but ignored indefinitely because the cache was re-filled
407 // with the old value after the cache flush on behalf of the category.
409 methodListLock.lock();
411 // Try this class's cache.
413 methodPC = _cache_getImp(cls, sel);
414 if (methodPC) goto done;
416 // Try this class's method lists.
418 meth = _class_getMethodNoSuper_nolock(cls, sel);
420 log_and_fill_cache(cls, cls, meth, sel);
421 methodPC = method_getImplementation(meth);
425 // Try superclass caches and method lists.
428 while ((curClass = curClass->superclass)) {
430 meth = _cache_getMethod(curClass, sel, _objc_msgForward_impcache);
432 if (meth != (Method)1) {
433 // Found the method in a superclass. Cache it in this class.
434 log_and_fill_cache(cls, curClass, meth, sel);
435 methodPC = method_getImplementation(meth);
439 // Found a forward:: entry in a superclass.
440 // Stop searching, but don't cache yet; call method
441 // resolver for this class first.
446 // Superclass method list.
447 meth = _class_getMethodNoSuper_nolock(curClass, sel);
449 log_and_fill_cache(cls, curClass, meth, sel);
450 methodPC = method_getImplementation(meth);
455 // No implementation found. Try method resolver once.
457 if (resolver && !triedResolver) {
458 methodListLock.unlock();
459 _class_resolveMethod(cls, sel, inst);
464 // No implementation found, and method resolver didn't help.
467 _cache_addForwardEntry(cls, sel);
468 methodPC = _objc_msgForward_impcache;
471 methodListLock.unlock();
477 /***********************************************************************
479 * Like lookUpImpOrForward, but returns nil instead of _objc_msgForward_impcache
480 **********************************************************************/
481 IMP lookUpImpOrNil(Class cls, SEL sel, id inst,
482 bool initialize, bool cache, bool resolver)
484 IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
485 if (imp == _objc_msgForward_impcache) return nil;
490 /***********************************************************************
491 * lookupMethodInClassAndLoadCache.
492 * Like _class_lookupMethodAndLoadCache, but does not search superclasses.
493 * Caches and returns objc_msgForward if the method is not found in the class.
494 **********************************************************************/
495 IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel)
500 // fixme this still has the method list vs method cache race
501 // because it doesn't hold a lock across lookup+cache_fill,
502 // but it's only used for .cxx_construct/destruct and we assume
503 // categories don't change them.
505 // Search cache first.
506 imp = _cache_getImp(cls, sel);
509 // Cache miss. Search method list.
511 meth = _class_getMethodNoSuper(cls, sel);
514 // Hit in method list. Cache it.
515 _cache_fill(cls, meth, sel);
516 return method_getImplementation(meth);
518 // Miss in method list. Cache objc_msgForward.
519 _cache_addForwardEntry(cls, sel);
520 return _objc_msgForward_impcache;
525 /***********************************************************************
526 * _class_getClassForIvar
527 * Given a class and an ivar that is in it or one of its superclasses,
528 * find the actual class that defined the ivar.
529 **********************************************************************/
530 Class _class_getClassForIvar(Class cls, Ivar ivar)
532 for ( ; cls; cls = cls->superclass) {
533 if (auto ivars = cls->ivars) {
534 if (ivar >= &ivars->ivar_list[0] &&
535 ivar < &ivars->ivar_list[ivars->ivar_count])
546 /***********************************************************************
547 * class_getVariable. Return the named instance variable.
548 **********************************************************************/
550 Ivar _class_getVariable(Class cls, const char *name)
552 for (; cls != Nil; cls = cls->superclass) {
555 // Skip class having no ivars
556 if (!cls->ivars) continue;
558 for (i = 0; i < cls->ivars->ivar_count; i++) {
559 // Check this ivar's name. Be careful because the
560 // compiler generates ivar entries with nil ivar_name
561 // (e.g. for anonymous bit fields).
562 old_ivar *ivar = &cls->ivars->ivar_list[i];
563 if (ivar->ivar_name && 0 == strcmp(name, ivar->ivar_name)) {
575 property_list_nth(const old_property_list *plist, uint32_t i)
577 return (old_property *)(i*plist->entsize + (char *)&plist->first);
581 copyPropertyList(old_property_list *plist, unsigned int *outCount)
583 old_property **result = nil;
584 unsigned int count = 0;
587 count = plist->count;
592 result = (old_property **)malloc((count+1) * sizeof(old_property *));
594 for (i = 0; i < count; i++) {
595 result[i] = property_list_nth(plist, i);
600 if (outCount) *outCount = count;
605 static old_property_list *
606 nextPropertyList(Class cls, uintptr_t *indexp)
608 old_property_list *result = nil;
610 classLock.assertLocked();
611 if (! ((cls->info & CLS_EXT) && cls->ext)) {
614 } else if (!cls->ext->propertyLists) {
617 } else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
618 // Only one property list
620 result = (old_property_list *)cls->ext->propertyLists;
625 // More than one property list
626 result = cls->ext->propertyLists[*indexp];
639 /***********************************************************************
640 * class_getIvarLayout
641 * nil means all-scanned. "" means non-scanned.
642 **********************************************************************/
644 class_getIvarLayout(Class cls)
646 if (cls && (cls->info & CLS_EXT)) {
647 return cls->ivar_layout;
649 return nil; // conservative scan
654 /***********************************************************************
655 * class_getWeakIvarLayout
656 * nil means no weak ivars.
657 **********************************************************************/
659 class_getWeakIvarLayout(Class cls)
661 if (cls && (cls->info & CLS_EXT) && cls->ext) {
662 return cls->ext->weak_ivar_layout;
664 return nil; // no weak ivars
669 /***********************************************************************
670 * class_setIvarLayout
671 * nil means all-scanned. "" means non-scanned.
672 **********************************************************************/
673 void class_setIvarLayout(Class cls, const uint8_t *layout)
677 if (! (cls->info & CLS_EXT)) {
678 _objc_inform("class '%s' needs to be recompiled", cls->name);
683 cls->ivar_layout = ustrdupMaybeNil(layout);
686 // SPI: Instance-specific object layout.
688 void _class_setIvarLayoutAccessor(Class cls, const uint8_t* (*accessor) (id object)) {
691 if (! (cls->info & CLS_EXT)) {
692 _objc_inform("class '%s' needs to be recompiled", cls->name);
697 cls->ivar_layout = (const uint8_t *)accessor;
698 cls->setInfo(CLS_HAS_INSTANCE_SPECIFIC_LAYOUT);
701 const uint8_t *_object_getIvarLayout(Class cls, id object) {
702 if (cls && (cls->info & CLS_EXT)) {
703 const uint8_t* layout = cls->ivar_layout;
704 if (cls->info & CLS_HAS_INSTANCE_SPECIFIC_LAYOUT) {
705 const uint8_t* (*accessor) (id object) = (const uint8_t* (*)(id))layout;
706 layout = accessor(object);
714 /***********************************************************************
715 * class_setWeakIvarLayout
716 * nil means no weak ivars.
717 **********************************************************************/
718 void class_setWeakIvarLayout(Class cls, const uint8_t *layout)
722 mutex_locker_t lock(classLock);
727 cls->ext->weak_ivar_layout = ustrdupMaybeNil(layout);
731 /***********************************************************************
732 * class_setVersion. Record the specified version with the class.
733 **********************************************************************/
734 void class_setVersion(Class cls, int version)
737 cls->version = version;
740 /***********************************************************************
741 * class_getVersion. Return the version recorded with the class.
742 **********************************************************************/
743 int class_getVersion(Class cls)
746 return (int)cls->version;
750 /***********************************************************************
752 **********************************************************************/
753 const char *class_getName(Class cls)
755 if (!cls) return "nil";
756 else return cls->demangledName();
760 /***********************************************************************
761 * _class_getNonMetaClass.
762 * Return the ordinary class for this class or metaclass.
763 * Used by +initialize.
764 **********************************************************************/
765 Class _class_getNonMetaClass(Class cls, id obj)
768 if (cls->isMetaClass()) {
769 if (cls->info & CLS_CONSTRUCTING) {
770 // Class is under construction and isn't in the class_hash,
771 // so objc_getClass doesn't work.
772 cls = obj; // fixme this may be nil in some paths
774 else if (strncmp(cls->name, "_%", 2) == 0) {
775 // Posee's meta's name is smashed and isn't in the class_hash,
776 // so objc_getClass doesn't work.
777 const char *baseName = strchr(cls->name, '%'); // get posee's real name
778 cls = objc_getClass(baseName);
781 cls = objc_getClass(cls->name);
790 Cache _class_getCache(Class cls)
795 void _class_setCache(Class cls, Cache cache)
800 const char *_category_getName(Category cat)
802 return oldcategory(cat)->category_name;
805 const char *_category_getClassName(Category cat)
807 return oldcategory(cat)->class_name;
810 Class _category_getClass(Category cat)
812 return objc_getClass(oldcategory(cat)->class_name);
815 IMP _category_getLoadMethod(Category cat)
817 old_method_list *mlist = oldcategory(cat)->class_methods;
819 return lookupNamedMethodInMethodList(mlist, "load");
827 /***********************************************************************
828 * class_nextMethodList.
829 * External version of nextMethodList().
831 * This function is not fully thread-safe. A series of calls to
832 * class_nextMethodList() may fail if methods are added to or removed
833 * from the class between calls.
834 * If methods are added between calls to class_nextMethodList(), it may
835 * return previously-returned method lists again, and may fail to return
837 * If methods are removed between calls to class_nextMethodList(), it may
838 * omit surviving method lists or simply crash.
839 **********************************************************************/
840 OBJC_EXPORT struct objc_method_list *class_nextMethodList(Class cls, void **it)
842 OBJC_WARN_DEPRECATED;
844 mutex_locker_t lock(methodListLock);
845 return (struct objc_method_list *) nextMethodList(cls, it);
849 /***********************************************************************
852 * Formerly class_addInstanceMethods ()
853 **********************************************************************/
854 OBJC_EXPORT void class_addMethods(Class cls, struct objc_method_list *meths)
856 OBJC_WARN_DEPRECATED;
860 mutex_locker_t lock(methodListLock);
861 _objc_insertMethods(cls, (old_method_list *)meths, nil);
864 // Must flush when dynamically adding methods. No need to flush
865 // all the class method caches. If cls is a meta class, though,
866 // this will still flush it and any of its sub-meta classes.
867 flush_caches (cls, NO);
871 /***********************************************************************
872 * class_removeMethods.
873 **********************************************************************/
874 OBJC_EXPORT void class_removeMethods(Class cls, struct objc_method_list *meths)
876 OBJC_WARN_DEPRECATED;
878 // Remove the methods
880 mutex_locker_t lock(methodListLock);
881 _objc_removeMethods(cls, (old_method_list *)meths);
884 // Must flush when dynamically removing methods. No need to flush
885 // all the class method caches. If cls is a meta class, though,
886 // this will still flush it and any of its sub-meta classes.
887 flush_caches (cls, NO);
890 /***********************************************************************
891 * lookupNamedMethodInMethodList
892 * Only called to find +load/-.cxx_construct/-.cxx_destruct methods,
893 * without fixing up the entire method list.
894 * The class is not yet in use, so methodListLock is not taken.
895 **********************************************************************/
896 IMP lookupNamedMethodInMethodList(old_method_list *mlist, const char *meth_name)
899 m = meth_name ? _findNamedMethodInList(mlist, meth_name) : nil;
900 return (m ? m->method_imp : nil);
903 static Method _class_getMethod(Class cls, SEL sel)
905 mutex_locker_t lock(methodListLock);
906 return (Method)_getMethod(cls, sel);
909 static Method _class_getMethodNoSuper(Class cls, SEL sel)
911 mutex_locker_t lock(methodListLock);
912 return (Method)_findMethodInClass(cls, sel);
915 static Method _class_getMethodNoSuper_nolock(Class cls, SEL sel)
917 methodListLock.assertLocked();
918 return (Method)_findMethodInClass(cls, sel);
922 /***********************************************************************
923 * class_getInstanceMethod. Return the instance method for the
924 * specified class and selector.
925 **********************************************************************/
926 Method class_getInstanceMethod(Class cls, SEL sel)
928 if (!cls || !sel) return nil;
930 // This deliberately avoids +initialize because it historically did so.
932 // This implementation is a bit weird because it's the only place that
933 // wants a Method instead of an IMP.
936 meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache);
937 if (meth == (Method)1) {
938 // Cache contains forward:: . Stop searching.
944 // Search method lists, try method resolver, etc.
945 lookUpImpOrNil(cls, sel, nil,
946 NO/*initialize*/, NO/*cache*/, YES/*resolver*/);
948 meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache);
949 if (meth == (Method)1) {
950 // Cache contains forward:: . Stop searching.
956 return _class_getMethod(cls, sel);
960 BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen)
962 old_protocol *proto = oldprotocol(proto_gen);
965 if (!proto) return NO;
967 if (cls->ISA()->version >= 3) {
968 old_protocol_list *list;
969 for (list = cls->protocols; list != nil; list = list->next) {
971 for (i = 0; i < list->count; i++) {
972 if (list->list[i] == proto) return YES;
973 if (protocol_conformsToProtocol((Protocol *)list->list[i], proto_gen)) return YES;
975 if (cls->ISA()->version <= 4) break;
982 static NXMapTable * posed_class_hash = nil;
984 /***********************************************************************
986 **********************************************************************/
988 Class _objc_getOrigClass(const char *name)
990 // Look for class among the posers
992 mutex_locker_t lock(classLock);
993 if (posed_class_hash) {
994 Class cls = (Class) NXMapGet (posed_class_hash, name);
999 // Not a poser. Do a normal lookup.
1000 Class cls = objc_getClass (name);
1001 if (cls) return cls;
1003 _objc_inform ("class `%s' not linked into application", name);
1007 Class objc_getOrigClass(const char *name)
1009 OBJC_WARN_DEPRECATED;
1010 return _objc_getOrigClass(name);
1013 /***********************************************************************
1014 * _objc_addOrigClass. This function is only used from class_poseAs.
1015 * Registers the original class names, before they get obscured by
1016 * posing, so that [super ..] will work correctly from categories
1017 * in posing classes and in categories in classes being posed for.
1018 **********************************************************************/
1019 static void _objc_addOrigClass (Class origClass)
1021 mutex_locker_t lock(classLock);
1023 // Create the poser's hash table on first use
1024 if (!posed_class_hash)
1026 posed_class_hash = NXCreateMapTable(NXStrValueMapPrototype, 8);
1029 // Add the named class iff it is not already there (or collides?)
1030 if (NXMapGet (posed_class_hash, origClass->name) == 0)
1031 NXMapInsert (posed_class_hash, origClass->name, origClass);
1035 /***********************************************************************
1036 * change_class_references
1037 * Change classrefs and superclass pointers from original to imposter
1038 * But if copy!=nil, don't change copy->superclass.
1039 * If changeSuperRefs==YES, also change [super message] classrefs.
1040 * Used by class_poseAs and objc_setFutureClass
1041 * classLock must be locked.
1042 **********************************************************************/
1043 void change_class_references(Class imposter,
1046 bool changeSuperRefs)
1052 // Change all subclasses of the original to point to the imposter.
1053 state = NXInitHashState (class_hash);
1054 while (NXNextHashState (class_hash, &state, (void **) &clsObject))
1056 while ((clsObject) && (clsObject != imposter) &&
1057 (clsObject != copy))
1059 if (clsObject->superclass == original)
1061 clsObject->superclass = imposter;
1062 clsObject->ISA()->superclass = imposter->ISA();
1063 // We must flush caches here!
1067 clsObject = clsObject->superclass;
1071 // Replace the original with the imposter in all class refs
1072 // Major loop - process all headers
1073 for (hInfo = FirstHeader; hInfo != nil; hInfo = hInfo->getNext())
1079 // Fix class refs associated with this header
1080 cls_refs = _getObjcClassRefs(hInfo, &refCount);
1082 for (index = 0; index < refCount; index += 1) {
1083 if (cls_refs[index] == original) {
1084 cls_refs[index] = imposter;
1092 /***********************************************************************
1095 * !!! class_poseAs () does not currently flush any caches.
1096 **********************************************************************/
1097 Class class_poseAs(Class imposter, Class original)
1099 char * imposterNamePtr;
1102 OBJC_WARN_DEPRECATED;
1104 // Trivial case is easy
1105 if (imposter == original)
1108 // Imposter must be an immediate subclass of the original
1109 if (imposter->superclass != original) {
1110 __objc_error(imposter,
1111 "[%s poseAs:%s]: target not immediate superclass",
1112 imposter->name, original->name);
1115 // Can't pose when you have instance variables (how could it work?)
1116 if (imposter->ivars) {
1117 __objc_error(imposter,
1118 "[%s poseAs:%s]: %s defines new instance variables",
1119 imposter->name, original->name, imposter->name);
1122 // Build a string to use to replace the name of the original class.
1124 # define imposterNamePrefix "_%"
1125 imposterNamePtr = malloc(strlen(original->name) + strlen(imposterNamePrefix) + 1);
1126 strcpy(imposterNamePtr, imposterNamePrefix);
1127 strcat(imposterNamePtr, original->name);
1128 # undef imposterNamePrefix
1130 asprintf(&imposterNamePtr, "_%%%s", original->name);
1133 // We lock the class hashtable, so we are thread safe with respect to
1134 // calls to objc_getClass (). However, the class names are not
1135 // changed atomically, nor are all of the subclasses updated
1136 // atomically. I have ordered the operations so that you will
1137 // never crash, but you may get inconsistent results....
1139 // Register the original class so that [super ..] knows
1140 // exactly which classes are the "original" classes.
1141 _objc_addOrigClass (original);
1142 _objc_addOrigClass (imposter);
1144 // Copy the imposter, so that the imposter can continue
1145 // its normal life in addition to changing the behavior of
1146 // the original. As a hack we don't bother to copy the metaclass.
1147 // For some reason we modify the original rather than the copy.
1148 copy = (Class)malloc(sizeof(objc_class));
1149 memmove(copy, imposter, sizeof(objc_class));
1151 mutex_locker_t lock(classLock);
1153 // Remove both the imposter and the original class.
1154 NXHashRemove (class_hash, imposter);
1155 NXHashRemove (class_hash, original);
1157 NXHashInsert (class_hash, copy);
1159 // Mark the imposter as such
1160 imposter->setInfo(CLS_POSING);
1161 imposter->ISA()->setInfo(CLS_POSING);
1163 // Change the name of the imposter to that of the original class.
1164 imposter->name = original->name;
1165 imposter->ISA()->name = original->ISA()->name;
1167 // Also copy the version field to avoid archiving problems.
1168 imposter->version = original->version;
1170 // Change classrefs and superclass pointers
1171 // Don't change copy->superclass
1172 // Don't change [super ...] messages
1173 change_class_references(imposter, original, copy, NO);
1175 // Change the name of the original class.
1176 original->name = imposterNamePtr + 1;
1177 original->ISA()->name = imposterNamePtr;
1179 // Restore the imposter and the original class with their new names.
1180 NXHashInsert (class_hash, imposter);
1181 NXHashInsert (class_hash, original);
1187 /***********************************************************************
1188 * _objc_flush_caches. Flush the instance and class method caches
1189 * of cls and all its subclasses.
1191 * Specifying Nil for the class "all classes."
1192 **********************************************************************/
1193 static void flush_caches(Class target, bool flush_meta)
1195 bool collectALot = (target == nil);
1198 #ifdef OBJC_INSTRUMENTED
1199 unsigned int classesVisited;
1200 unsigned int subclassCount;
1203 mutex_locker_t lock(classLock);
1204 mutex_locker_t lock2(cacheUpdateLock);
1206 // Leaf classes are fastest because there are no subclass caches to flush.
1208 if (target && (target->info & CLS_LEAF)) {
1209 _cache_flush (target);
1211 if (target->ISA() && (target->ISA()->info & CLS_LEAF)) {
1212 _cache_flush (target->ISA());
1215 // Reset target and handle it by one of the methods below.
1216 target = target->ISA();
1222 state = NXInitHashState(class_hash);
1224 // Handle nil and root instance class specially: flush all
1225 // instance and class method caches. Nice that this
1226 // loop is linear vs the N-squared loop just below.
1227 if (!target || !target->superclass)
1229 #ifdef OBJC_INSTRUMENTED
1230 LinearFlushCachesCount += 1;
1234 // Traverse all classes in the hash table
1235 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1237 Class metaClsObject;
1238 #ifdef OBJC_INSTRUMENTED
1239 classesVisited += 1;
1242 // Skip class that is known not to be a subclass of this root
1243 // (the isa pointer of any meta class points to the meta class
1245 // NOTE: When is an isa pointer of a hash tabled class ever nil?
1246 metaClsObject = clsObject->ISA();
1247 if (target && metaClsObject && target->ISA() != metaClsObject->ISA()) {
1251 #ifdef OBJC_INSTRUMENTED
1255 _cache_flush (clsObject);
1256 if (flush_meta && metaClsObject != nil) {
1257 _cache_flush (metaClsObject);
1260 #ifdef OBJC_INSTRUMENTED
1261 LinearFlushCachesVisitedCount += classesVisited;
1262 if (classesVisited > MaxLinearFlushCachesVisitedCount)
1263 MaxLinearFlushCachesVisitedCount = classesVisited;
1264 IdealFlushCachesCount += subclassCount;
1265 if (subclassCount > MaxIdealFlushCachesCount)
1266 MaxIdealFlushCachesCount = subclassCount;
1272 // Outer loop - flush any cache that could now get a method from
1273 // cls (i.e. the cache associated with cls and any of its subclasses).
1274 #ifdef OBJC_INSTRUMENTED
1275 NonlinearFlushCachesCount += 1;
1279 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1283 #ifdef OBJC_INSTRUMENTED
1284 NonlinearFlushCachesClassCount += 1;
1287 // Inner loop - Process a given class
1288 clsIter = clsObject;
1292 #ifdef OBJC_INSTRUMENTED
1293 classesVisited += 1;
1295 // Flush clsObject instance method cache if
1296 // clsObject is a subclass of cls, or is cls itself
1297 // Flush the class method cache if that was asked for
1298 if (clsIter == target)
1300 #ifdef OBJC_INSTRUMENTED
1303 _cache_flush (clsObject);
1305 _cache_flush (clsObject->ISA());
1311 // Flush clsObject class method cache if cls is
1312 // the meta class of clsObject or of one
1313 // of clsObject's superclasses
1314 else if (clsIter->ISA() == target)
1316 #ifdef OBJC_INSTRUMENTED
1319 _cache_flush (clsObject->ISA());
1323 // Move up superclass chain
1324 // else if (clsIter->isInitialized())
1325 clsIter = clsIter->superclass;
1327 // clsIter is not initialized, so its cache
1328 // must be empty. This happens only when
1329 // clsIter == clsObject, because
1330 // superclasses are initialized before
1331 // subclasses, and this loop traverses
1332 // from sub- to super- classes.
1337 #ifdef OBJC_INSTRUMENTED
1338 NonlinearFlushCachesVisitedCount += classesVisited;
1339 if (classesVisited > MaxNonlinearFlushCachesVisitedCount)
1340 MaxNonlinearFlushCachesVisitedCount = classesVisited;
1341 IdealFlushCachesCount += subclassCount;
1342 if (subclassCount > MaxIdealFlushCachesCount)
1343 MaxIdealFlushCachesCount = subclassCount;
1349 _cache_collect(true);
1354 void _objc_flush_caches(Class target)
1356 flush_caches(target, YES);
1361 /***********************************************************************
1362 * flush_marked_caches. Flush the method cache of any class marked
1363 * CLS_FLUSH_CACHE (and all subclasses thereof)
1365 **********************************************************************/
1366 void flush_marked_caches(void)
1372 mutex_locker_t lock(classLock);
1373 mutex_locker_t lock2(cacheUpdateLock);
1375 state = NXInitHashState(class_hash);
1376 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1377 for (supercls = cls; supercls; supercls = supercls->superclass) {
1378 if (supercls->info & CLS_FLUSH_CACHE) {
1384 for (supercls = cls->ISA(); supercls; supercls = supercls->superclass) {
1385 if (supercls->info & CLS_FLUSH_CACHE) {
1386 _cache_flush(cls->ISA());
1392 state = NXInitHashState(class_hash);
1393 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1394 if (cls->info & CLS_FLUSH_CACHE) {
1395 cls->clearInfo(CLS_FLUSH_CACHE);
1397 if (cls->ISA()->info & CLS_FLUSH_CACHE) {
1398 cls->ISA()->clearInfo(CLS_FLUSH_CACHE);
1404 /***********************************************************************
1405 * get_base_method_list
1406 * Returns the method list containing the class's own methods,
1407 * ignoring any method lists added by categories or class_addMethods.
1408 * Called only by add_class_to_loadable_list.
1409 * Does not hold methodListLock because add_class_to_loadable_list
1410 * does not manipulate in-use classes.
1411 **********************************************************************/
1412 static old_method_list *get_base_method_list(Class cls)
1414 old_method_list **ptr;
1416 if (!cls->methodLists) return nil;
1417 if (cls->info & CLS_NO_METHOD_ARRAY) return (old_method_list *)cls->methodLists;
1418 ptr = cls->methodLists;
1419 if (!*ptr || *ptr == END_OF_METHODS_LIST) return nil;
1420 while ( *ptr != 0 && *ptr != END_OF_METHODS_LIST ) { ptr++; }
1426 static IMP _class_getLoadMethod_nocheck(Class cls)
1428 old_method_list *mlist;
1429 mlist = get_base_method_list(cls->ISA());
1431 return lookupNamedMethodInMethodList (mlist, "load");
1437 bool _class_hasLoadMethod(Class cls)
1439 if (cls->ISA()->info & CLS_HAS_LOAD_METHOD) return YES;
1440 return _class_getLoadMethod_nocheck(cls);
1444 /***********************************************************************
1445 * objc_class::getLoadMethod
1446 * Returns cls's +load implementation, or nil if it doesn't have one.
1447 **********************************************************************/
1448 IMP objc_class::getLoadMethod()
1450 if (ISA()->info & CLS_HAS_LOAD_METHOD) {
1451 return _class_getLoadMethod_nocheck((Class)this);
1456 ptrdiff_t ivar_getOffset(Ivar ivar)
1458 return oldivar(ivar)->ivar_offset;
1461 const char *ivar_getName(Ivar ivar)
1463 return oldivar(ivar)->ivar_name;
1466 const char *ivar_getTypeEncoding(Ivar ivar)
1468 return oldivar(ivar)->ivar_type;
1472 IMP method_getImplementation(Method m)
1475 return oldmethod(m)->method_imp;
1478 SEL method_getName(Method m)
1481 return oldmethod(m)->method_name;
1484 const char *method_getTypeEncoding(Method m)
1487 return oldmethod(m)->method_types;
1490 unsigned int method_getSizeOfArguments(Method m)
1492 OBJC_WARN_DEPRECATED;
1494 return encoding_getSizeOfArguments(method_getTypeEncoding(m));
1497 unsigned int method_getArgumentInfo(Method m, int arg,
1498 const char **type, int *offset)
1500 OBJC_WARN_DEPRECATED;
1502 return encoding_getArgumentInfo(method_getTypeEncoding(m),
1509 IMP method_setImplementation(Method m_gen, IMP imp)
1512 old_method *m = oldmethod(m_gen);
1514 if (!imp) return nil;
1517 old = m->method_imp;
1518 m->method_imp = imp;
1524 void method_exchangeImplementations(Method m1_gen, Method m2_gen)
1527 old_method *m1 = oldmethod(m1_gen);
1528 old_method *m2 = oldmethod(m2_gen);
1529 if (!m1 || !m2) return;
1532 m1_imp = m1->method_imp;
1533 m1->method_imp = m2->method_imp;
1534 m2->method_imp = m1_imp;
1539 struct objc_method_description * method_getDescription(Method m)
1542 return (struct objc_method_description *)oldmethod(m);
1546 const char *property_getName(objc_property_t prop)
1548 return oldproperty(prop)->name;
1551 const char *property_getAttributes(objc_property_t prop)
1553 return oldproperty(prop)->attributes;
1556 objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
1557 unsigned int *outCount)
1560 if (outCount) *outCount = 0;
1564 mutex_locker_t lock(classLock);
1565 return copyPropertyAttributeList(oldproperty(prop)->attributes,outCount);
1568 char * property_copyAttributeValue(objc_property_t prop, const char *name)
1570 if (!prop || !name || *name == '\0') return nil;
1572 mutex_locker_t lock(classLock);
1573 return copyPropertyAttributeValue(oldproperty(prop)->attributes, name);
1577 /***********************************************************************
1579 **********************************************************************/
1580 static IMP _class_addMethod(Class cls, SEL name, IMP imp,
1581 const char *types, bool replace)
1586 if (!types) types = "";
1588 mutex_locker_t lock(methodListLock);
1590 if ((m = _findMethodInClass(cls, name))) {
1593 result = method_getImplementation((Method)m);
1595 method_setImplementation((Method)m, imp);
1598 // fixme could be faster
1599 old_method_list *mlist =
1600 (old_method_list *)calloc(sizeof(old_method_list), 1);
1601 mlist->obsolete = fixed_up_method_list;
1602 mlist->method_count = 1;
1603 mlist->method_list[0].method_name = name;
1604 mlist->method_list[0].method_types = strdup(types);
1605 mlist->method_list[0].method_imp = imp;
1607 _objc_insertMethods(cls, mlist, nil);
1608 if (!(cls->info & CLS_CONSTRUCTING)) {
1609 flush_caches(cls, NO);
1611 // in-construction class has no subclasses
1621 /***********************************************************************
1623 **********************************************************************/
1624 BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
1627 if (!cls) return NO;
1629 old = _class_addMethod(cls, name, imp, types, NO);
1634 /***********************************************************************
1635 * class_replaceMethod
1636 **********************************************************************/
1637 IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
1639 if (!cls) return nil;
1641 return _class_addMethod(cls, name, imp, types, YES);
1645 /***********************************************************************
1647 **********************************************************************/
1648 BOOL class_addIvar(Class cls, const char *name, size_t size,
1649 uint8_t alignment, const char *type)
1653 if (!cls) return NO;
1654 if (ISMETA(cls)) return NO;
1655 if (!(cls->info & CLS_CONSTRUCTING)) return NO;
1657 if (!type) type = "";
1658 if (name && 0 == strcmp(name, "")) name = nil;
1660 mutex_locker_t lock(classLock);
1662 // Check for existing ivar with this name
1663 // fixme check superclasses?
1666 for (i = 0; i < cls->ivars->ivar_count; i++) {
1667 if (0 == strcmp(cls->ivars->ivar_list[i].ivar_name, name)) {
1675 old_ivar_list *old = cls->ivars;
1683 oldSize = sizeof(old_ivar_list) +
1684 (old->ivar_count - 1) * sizeof(old_ivar);
1685 newCount = 1 + old->ivar_count;
1687 oldSize = sizeof(old_ivar_list) - sizeof(old_ivar);
1691 // allocate new ivar list
1692 cls->ivars = (old_ivar_list *)
1693 calloc(oldSize+sizeof(old_ivar), 1);
1694 if (old) memcpy(cls->ivars, old, oldSize);
1695 if (old && malloc_size(old)) free(old);
1696 cls->ivars->ivar_count = newCount;
1697 ivar = &cls->ivars->ivar_list[newCount-1];
1699 // set ivar name and type
1700 ivar->ivar_name = strdup(name);
1701 ivar->ivar_type = strdup(type);
1703 // align if necessary
1704 alignBytes = 1 << alignment;
1705 misalign = cls->instance_size % alignBytes;
1706 if (misalign) cls->instance_size += (long)(alignBytes - misalign);
1708 // set ivar offset and increase instance size
1709 ivar->ivar_offset = (int)cls->instance_size;
1710 cls->instance_size += (long)size;
1717 /***********************************************************************
1719 **********************************************************************/
1720 BOOL class_addProtocol(Class cls, Protocol *protocol_gen)
1722 old_protocol *protocol = oldprotocol(protocol_gen);
1723 old_protocol_list *plist;
1725 if (!cls) return NO;
1726 if (class_conformsToProtocol(cls, protocol_gen)) return NO;
1728 mutex_locker_t lock(classLock);
1730 // fixme optimize - protocol list doesn't escape?
1731 plist = (old_protocol_list*)calloc(sizeof(old_protocol_list), 1);
1733 plist->list[0] = protocol;
1734 plist->next = cls->protocols;
1735 cls->protocols = plist;
1743 /***********************************************************************
1744 * _class_addProperties
1745 * Internal helper to add properties to a class.
1746 * Used by category attachment and class_addProperty()
1747 * Locking: acquires classLock
1748 **********************************************************************/
1750 _class_addProperties(Class cls,
1751 old_property_list *additions)
1753 old_property_list *newlist;
1755 if (!(cls->info & CLS_EXT)) return NO;
1757 newlist = (old_property_list *)
1758 memdup(additions, sizeof(*newlist) - sizeof(newlist->first)
1759 + (additions->entsize * additions->count));
1761 mutex_locker_t lock(classLock);
1764 if (!cls->ext->propertyLists) {
1765 // cls has no properties - simply use this list
1766 cls->ext->propertyLists = (old_property_list **)newlist;
1767 cls->setInfo(CLS_NO_PROPERTY_ARRAY);
1769 else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
1770 // cls has one property list - make a new array
1771 old_property_list **newarray = (old_property_list **)
1772 malloc(3 * sizeof(*newarray));
1773 newarray[0] = newlist;
1774 newarray[1] = (old_property_list *)cls->ext->propertyLists;
1776 cls->ext->propertyLists = newarray;
1777 cls->clearInfo(CLS_NO_PROPERTY_ARRAY);
1780 // cls has a property array - make a bigger one
1781 old_property_list **newarray;
1783 while (cls->ext->propertyLists[count]) count++;
1784 newarray = (old_property_list **)
1785 malloc((count+2) * sizeof(*newarray));
1786 newarray[0] = newlist;
1787 memcpy(&newarray[1], &cls->ext->propertyLists[0],
1788 count * sizeof(*newarray));
1789 newarray[count+1] = nil;
1790 free(cls->ext->propertyLists);
1791 cls->ext->propertyLists = newarray;
1798 /***********************************************************************
1800 * Adds a property to a class. Returns NO if the proeprty already exists.
1801 * Locking: acquires classLock
1802 **********************************************************************/
1804 _class_addProperty(Class cls, const char *name,
1805 const objc_property_attribute_t *attrs, unsigned int count,
1808 if (!cls) return NO;
1809 if (!name) return NO;
1811 old_property *prop = oldproperty(class_getProperty(cls, name));
1812 if (prop && !replace) {
1813 // already exists, refuse to replace
1818 mutex_locker_t lock(classLock);
1819 try_free(prop->attributes);
1820 prop->attributes = copyPropertyAttributeString(attrs, count);
1825 old_property_list proplist;
1826 proplist.entsize = sizeof(old_property);
1828 proplist.first.name = strdup(name);
1829 proplist.first.attributes = copyPropertyAttributeString(attrs, count);
1831 return _class_addProperties(cls, &proplist);
1836 class_addProperty(Class cls, const char *name,
1837 const objc_property_attribute_t *attrs, unsigned int n)
1839 return _class_addProperty(cls, name, attrs, n, NO);
1843 class_replaceProperty(Class cls, const char *name,
1844 const objc_property_attribute_t *attrs, unsigned int n)
1846 _class_addProperty(cls, name, attrs, n, YES);
1850 /***********************************************************************
1851 * class_copyProtocolList. Returns a heap block containing the
1852 * protocols implemented by the class, or nil if the class
1853 * implements no protocols. Caller must free the block.
1854 * Does not copy any superclass's protocols.
1855 **********************************************************************/
1856 Protocol * __unsafe_unretained *
1857 class_copyProtocolList(Class cls, unsigned int *outCount)
1859 old_protocol_list *plist;
1860 Protocol **result = nil;
1861 unsigned int count = 0;
1865 if (outCount) *outCount = 0;
1869 mutex_locker_t lock(classLock);
1871 for (plist = cls->protocols; plist != nil; plist = plist->next) {
1872 count += (int)plist->count;
1876 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
1878 for (p = 0, plist = cls->protocols;
1880 plist = plist->next)
1883 for (i = 0; i < plist->count; i++) {
1884 result[p++] = (Protocol *)plist->list[i];
1890 if (outCount) *outCount = count;
1895 /***********************************************************************
1896 * class_getProperty. Return the named property.
1897 **********************************************************************/
1898 objc_property_t class_getProperty(Class cls, const char *name)
1900 if (!cls || !name) return nil;
1902 mutex_locker_t lock(classLock);
1904 for (; cls; cls = cls->superclass) {
1905 uintptr_t iterator = 0;
1906 old_property_list *plist;
1907 while ((plist = nextPropertyList(cls, &iterator))) {
1909 for (i = 0; i < plist->count; i++) {
1910 old_property *p = property_list_nth(plist, i);
1911 if (0 == strcmp(name, p->name)) {
1912 return (objc_property_t)p;
1922 /***********************************************************************
1923 * class_copyPropertyList. Returns a heap block containing the
1924 * properties declared in the class, or nil if the class
1925 * declares no properties. Caller must free the block.
1926 * Does not copy any superclass's properties.
1927 **********************************************************************/
1928 objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
1930 old_property_list *plist;
1931 uintptr_t iterator = 0;
1932 old_property **result = nil;
1933 unsigned int count = 0;
1937 if (outCount) *outCount = 0;
1941 mutex_locker_t lock(classLock);
1944 while ((plist = nextPropertyList(cls, &iterator))) {
1945 count += plist->count;
1949 result = (old_property **)malloc((count+1) * sizeof(old_property *));
1953 while ((plist = nextPropertyList(cls, &iterator))) {
1954 for (i = 0; i < plist->count; i++) {
1955 result[p++] = property_list_nth(plist, i);
1961 if (outCount) *outCount = count;
1962 return (objc_property_t *)result;
1966 /***********************************************************************
1967 * class_copyMethodList. Returns a heap block containing the
1968 * methods implemented by the class, or nil if the class
1969 * implements no methods. Caller must free the block.
1970 * Does not copy any superclass's methods.
1971 **********************************************************************/
1972 Method *class_copyMethodList(Class cls, unsigned int *outCount)
1974 old_method_list *mlist;
1975 void *iterator = nil;
1976 Method *result = nil;
1977 unsigned int count = 0;
1981 if (outCount) *outCount = 0;
1985 mutex_locker_t lock(methodListLock);
1988 while ((mlist = nextMethodList(cls, &iterator))) {
1989 count += mlist->method_count;
1993 result = (Method *)malloc((count+1) * sizeof(Method));
1997 while ((mlist = nextMethodList(cls, &iterator))) {
1999 for (i = 0; i < mlist->method_count; i++) {
2000 result[m++] = (Method)&mlist->method_list[i];
2006 if (outCount) *outCount = count;
2011 /***********************************************************************
2012 * class_copyIvarList. Returns a heap block containing the
2013 * ivars declared in the class, or nil if the class
2014 * declares no ivars. Caller must free the block.
2015 * Does not copy any superclass's ivars.
2016 **********************************************************************/
2017 Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
2020 unsigned int count = 0;
2024 if (outCount) *outCount = 0;
2029 count = cls->ivars->ivar_count;
2033 result = (Ivar *)malloc((count+1) * sizeof(Ivar));
2035 for (i = 0; i < cls->ivars->ivar_count; i++) {
2036 result[i] = (Ivar)&cls->ivars->ivar_list[i];
2041 if (outCount) *outCount = count;
2046 /***********************************************************************
2047 * objc_allocateClass.
2048 **********************************************************************/
2050 void set_superclass(Class cls, Class supercls, bool cls_is_new)
2052 Class meta = cls->ISA();
2055 cls->superclass = supercls;
2056 meta->superclass = supercls->ISA();
2057 meta->initIsa(supercls->ISA()->ISA());
2059 // Propagate C++ cdtors from superclass.
2060 if (supercls->info & CLS_HAS_CXX_STRUCTORS) {
2061 if (cls_is_new) cls->info |= CLS_HAS_CXX_STRUCTORS;
2062 else cls->setInfo(CLS_HAS_CXX_STRUCTORS);
2065 // Superclass is no longer a leaf for cache flushing
2066 if (supercls->info & CLS_LEAF) {
2067 supercls->clearInfo(CLS_LEAF);
2068 supercls->ISA()->clearInfo(CLS_LEAF);
2071 cls->superclass = Nil; // superclass of root class is nil
2072 meta->superclass = cls; // superclass of root metaclass is root class
2073 meta->initIsa(meta); // metaclass of root metaclass is root metaclass
2075 // Root class is never a leaf for cache flushing, because the
2076 // root metaclass is a subclass. (This could be optimized, but
2077 // is too uncommon to bother.)
2078 cls->clearInfo(CLS_LEAF);
2079 meta->clearInfo(CLS_LEAF);
2083 // &UnsetLayout is the default ivar layout during class construction
2084 static const uint8_t UnsetLayout = 0;
2086 Class objc_initializeClassPair(Class supercls, const char *name, Class cls, Class meta)
2088 // Connect to superclasses and metaclasses
2090 set_superclass(cls, supercls, YES);
2093 cls->name = strdup(name);
2094 meta->name = strdup(name);
2097 cls->info = CLS_CLASS | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2098 meta->info = CLS_META | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2100 // Set instance size based on superclass.
2102 cls->instance_size = supercls->instance_size;
2103 meta->instance_size = supercls->ISA()->instance_size;
2105 cls->instance_size = sizeof(Class); // just an isa
2106 meta->instance_size = sizeof(objc_class);
2109 // No ivars. No methods. Empty cache. No protocols. No layout. Empty ext.
2111 cls->methodLists = nil;
2112 cls->cache = (Cache)&_objc_empty_cache;
2113 cls->protocols = nil;
2114 cls->ivar_layout = &UnsetLayout;
2117 cls->ext->weak_ivar_layout = &UnsetLayout;
2120 meta->methodLists = nil;
2121 meta->cache = (Cache)&_objc_empty_cache;
2122 meta->protocols = nil;
2128 Class objc_allocateClassPair(Class supercls, const char *name,
2133 if (objc_getClass(name)) return nil;
2134 // fixme reserve class name against simultaneous allocation
2136 if (supercls && (supercls->info & CLS_CONSTRUCTING)) {
2137 // Can't make subclass of an in-construction class
2141 // Allocate new classes.
2143 cls = _calloc_class(supercls->ISA()->alignedInstanceSize() + extraBytes);
2144 meta = _calloc_class(supercls->ISA()->ISA()->alignedInstanceSize() + extraBytes);
2146 cls = _calloc_class(sizeof(objc_class) + extraBytes);
2147 meta = _calloc_class(sizeof(objc_class) + extraBytes);
2151 objc_initializeClassPair(supercls, name, cls, meta);
2157 void objc_registerClassPair(Class cls)
2159 if ((cls->info & CLS_CONSTRUCTED) ||
2160 (cls->ISA()->info & CLS_CONSTRUCTED))
2162 _objc_inform("objc_registerClassPair: class '%s' was already "
2163 "registered!", cls->name);
2167 if (!(cls->info & CLS_CONSTRUCTING) ||
2168 !(cls->ISA()->info & CLS_CONSTRUCTING))
2170 _objc_inform("objc_registerClassPair: class '%s' was not "
2171 "allocated with objc_allocateClassPair!", cls->name);
2176 _objc_inform("objc_registerClassPair: class '%s' is a metaclass, "
2177 "not a class!", cls->name);
2181 mutex_locker_t lock(classLock);
2183 // Clear "under construction" bit, set "done constructing" bit
2184 cls->info &= ~CLS_CONSTRUCTING;
2185 cls->ISA()->info &= ~CLS_CONSTRUCTING;
2186 cls->info |= CLS_CONSTRUCTED;
2187 cls->ISA()->info |= CLS_CONSTRUCTED;
2189 NXHashInsertIfAbsent(class_hash, cls);
2193 Class objc_duplicateClass(Class original, const char *name, size_t extraBytes)
2195 unsigned int count, i;
2196 old_method **originalMethods;
2197 old_method_list *duplicateMethods;
2198 // Don't use sizeof(objc_class) here because
2199 // instance_size has historically contained two extra words,
2200 // and instance_size is what objc_getIndexedIvars() actually uses.
2202 _calloc_class(original->ISA()->alignedInstanceSize() + extraBytes);
2204 duplicate->initIsa(original->ISA());
2205 duplicate->superclass = original->superclass;
2206 duplicate->name = strdup(name);
2207 duplicate->version = original->version;
2208 duplicate->info = original->info & (CLS_CLASS|CLS_META|CLS_INITIALIZED|CLS_JAVA_HYBRID|CLS_JAVA_CLASS|CLS_HAS_CXX_STRUCTORS|CLS_HAS_LOAD_METHOD);
2209 duplicate->instance_size = original->instance_size;
2210 duplicate->ivars = original->ivars;
2211 // methodLists handled below
2212 duplicate->cache = (Cache)&_objc_empty_cache;
2213 duplicate->protocols = original->protocols;
2214 if (original->info & CLS_EXT) {
2215 duplicate->info |= original->info & (CLS_EXT|CLS_NO_PROPERTY_ARRAY);
2216 duplicate->ivar_layout = original->ivar_layout;
2217 if (original->ext) {
2218 duplicate->ext = (old_class_ext *)malloc(original->ext->size);
2219 memcpy(duplicate->ext, original->ext, original->ext->size);
2221 duplicate->ext = nil;
2225 // Method lists are deep-copied so they can be stomped.
2226 originalMethods = (old_method **)class_copyMethodList(original, &count);
2227 if (originalMethods) {
2228 duplicateMethods = (old_method_list *)
2229 calloc(sizeof(old_method_list) +
2230 (count-1)*sizeof(old_method), 1);
2231 duplicateMethods->obsolete = fixed_up_method_list;
2232 duplicateMethods->method_count = count;
2233 for (i = 0; i < count; i++) {
2234 duplicateMethods->method_list[i] = *(originalMethods[i]);
2236 duplicate->methodLists = (old_method_list **)duplicateMethods;
2237 duplicate->info |= CLS_NO_METHOD_ARRAY;
2238 free(originalMethods);
2241 mutex_locker_t lock(classLock);
2242 NXHashInsert(class_hash, duplicate);
2248 void objc_disposeClassPair(Class cls)
2250 if (!(cls->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)) ||
2251 !(cls->ISA()->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)))
2253 // class not allocated with objc_allocateClassPair
2254 // disposing still-unregistered class is OK!
2255 _objc_inform("objc_disposeClassPair: class '%s' was not "
2256 "allocated with objc_allocateClassPair!", cls->name);
2261 _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
2262 "not a class!", cls->name);
2266 mutex_locker_t lock(classLock);
2267 NXHashRemove(class_hash, cls);
2268 unload_class(cls->ISA());
2273 /***********************************************************************
2274 * objc_constructInstance
2275 * Creates an instance of `cls` at the location pointed to by `bytes`.
2276 * `bytes` must point to at least class_getInstanceSize(cls) bytes of
2277 * well-aligned zero-filled memory.
2278 * The new object's isa is set. Any C++ constructors are called.
2279 * Returns `bytes` if successful. Returns nil if `cls` or `bytes` is
2280 * nil, or if C++ constructors fail.
2281 **********************************************************************/
2283 objc_constructInstance(Class cls, void *bytes)
2285 if (!cls || !bytes) return nil;
2291 if (cls->hasCxxCtor()) {
2292 return object_cxxConstructFromClass(obj, cls);
2299 /***********************************************************************
2300 * _class_createInstanceFromZone. Allocate an instance of the
2301 * specified class with the specified number of bytes for indexed
2302 * variables, in the specified zone. The isa field is set to the
2303 * class, C++ default constructors are called, and all other fields are zeroed.
2304 **********************************************************************/
2306 _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
2311 // Can't create something for nothing
2312 if (!cls) return nil;
2314 // Allocate and initialize
2315 size = cls->alignedInstanceSize() + extraBytes;
2317 // CF requires all objects be at least 16 bytes.
2318 if (size < 16) size = 16;
2321 bytes = malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
2323 bytes = calloc(1, size);
2326 return objc_constructInstance(cls, bytes);
2330 /***********************************************************************
2331 * _class_createInstance. Allocate an instance of the specified
2332 * class with the specified number of bytes for indexed variables, in
2333 * the default zone, using _class_createInstanceFromZone.
2334 **********************************************************************/
2335 static id _class_createInstance(Class cls, size_t extraBytes)
2337 return _class_createInstanceFromZone (cls, extraBytes, nil);
2341 static id _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
2346 if (!oldObj) return nil;
2348 obj = (*_zoneAlloc)(oldObj->ISA(), extraBytes, zone);
2349 size = oldObj->ISA()->alignedInstanceSize() + extraBytes;
2351 // fixme need C++ copy constructor
2352 memmove(obj, oldObj, size);
2354 fixupCopiedIvars(obj, oldObj);
2360 /***********************************************************************
2361 * objc_destructInstance
2362 * Destroys an instance without freeing memory.
2363 * Calls C++ destructors.
2364 * Removes associative references.
2365 * Returns `obj`. Does nothing if `obj` is nil.
2366 * CoreFoundation and other clients do call this under GC.
2367 **********************************************************************/
2368 void *objc_destructInstance(id obj)
2371 Class isa = obj->getIsa();
2373 if (isa->hasCxxDtor()) {
2374 object_cxxDestruct(obj);
2377 if (isa->instancesHaveAssociatedObjects()) {
2378 _object_remove_assocations(obj);
2381 objc_clear_deallocating(obj);
2388 _object_dispose(id anObject)
2390 if (anObject==nil) return nil;
2392 objc_destructInstance(anObject);
2394 anObject->initIsa(_objc_getFreedObjectClass ());
2400 static id _object_copy(id oldObj, size_t extraBytes)
2402 void *z = malloc_zone_from_ptr(oldObj);
2403 return _object_copyFromZone(oldObj, extraBytes,
2404 z ? z : malloc_default_zone());
2407 static id _object_reallocFromZone(id anObject, size_t nBytes, void *zone)
2412 if (anObject == nil)
2413 __objc_error(nil, "reallocating nil object");
2415 if (anObject->ISA() == _objc_getFreedObjectClass ())
2416 __objc_error(anObject, "reallocating freed object");
2418 if (nBytes < anObject->ISA()->alignedInstanceSize())
2419 __objc_error(anObject, "(%s, %zu) requested size too small",
2420 object_getClassName(anObject), nBytes);
2422 // fixme need C++ copy constructor
2424 // Make sure not to modify space that has been declared free
2425 tmp = anObject->ISA();
2426 anObject->initIsa(_objc_getFreedObjectClass ());
2427 newObject = (id)malloc_zone_realloc((malloc_zone_t *)zone, anObject, nBytes);
2429 newObject->initIsa(tmp);
2431 // realloc failed, anObject is still alive
2432 anObject->initIsa(tmp);
2438 static id _object_realloc(id anObject, size_t nBytes)
2440 void *z = malloc_zone_from_ptr(anObject);
2441 return _object_reallocFromZone(anObject,
2443 z ? z : malloc_default_zone());
2446 id (*_alloc)(Class, size_t) = _class_createInstance;
2447 id (*_copy)(id, size_t) = _object_copy;
2448 id (*_realloc)(id, size_t) = _object_realloc;
2449 id (*_dealloc)(id) = _object_dispose;
2450 id (*_zoneAlloc)(Class, size_t, void *) = _class_createInstanceFromZone;
2451 id (*_zoneCopy)(id, size_t, void *) = _object_copyFromZone;
2452 id (*_zoneRealloc)(id, size_t, void *) = _object_reallocFromZone;
2453 void (*_error)(id, const char *, va_list) = _objc_error;
2456 id class_createInstance(Class cls, size_t extraBytes)
2458 return (*_alloc)(cls, extraBytes);
2461 id class_createInstanceFromZone(Class cls, size_t extraBytes, void *z)
2463 OBJC_WARN_DEPRECATED;
2464 return (*_zoneAlloc)(cls, extraBytes, z);
2467 unsigned class_createInstances(Class cls, size_t extraBytes,
2468 id *results, unsigned num_requested)
2470 if (_alloc == &_class_createInstance) {
2471 return _class_createInstancesFromZone(cls, extraBytes, nil,
2472 results, num_requested);
2474 // _alloc in use, which isn't understood by the batch allocator
2479 id object_copy(id obj, size_t extraBytes)
2481 return (*_copy)(obj, extraBytes);
2484 id object_copyFromZone(id obj, size_t extraBytes, void *z)
2486 OBJC_WARN_DEPRECATED;
2487 return (*_zoneCopy)(obj, extraBytes, z);
2490 id object_dispose(id obj)
2492 return (*_dealloc)(obj);
2495 id object_realloc(id obj, size_t nBytes)
2497 OBJC_WARN_DEPRECATED;
2498 return (*_realloc)(obj, nBytes);
2501 id object_reallocFromZone(id obj, size_t nBytes, void *z)
2503 OBJC_WARN_DEPRECATED;
2504 return (*_zoneRealloc)(obj, nBytes, z);
2508 /***********************************************************************
2509 * object_getIndexedIvars.
2510 **********************************************************************/
2511 void *object_getIndexedIvars(id obj)
2513 // ivars are tacked onto the end of the object
2514 if (!obj) return nil;
2515 if (obj->isTaggedPointer()) return nil;
2516 return ((char *) obj) + obj->ISA()->alignedInstanceSize();
2521 Class class_setSuperclass(Class cls, Class newSuper)
2523 Class oldSuper = cls->superclass;
2524 set_superclass(cls, newSuper, NO);
2525 flush_caches(cls, YES);