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.
166 mutex_locker_t lock(selLock);
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.
172 mlist->obsolete = fixed_up_method_list;
178 /***********************************************************************
180 * Returns successive method lists from the given class.
181 * Method lists are returned in method search order (i.e. highest-priority
182 * implementations first).
183 * All necessary method list fixups are performed, so the
184 * returned method list is fully-constructed.
186 * If cls is already in use, methodListLock must be held by the caller.
187 * For full thread-safety, methodListLock must be continuously held by the
188 * caller across all calls to nextMethodList(). If the lock is released,
189 * the bad results listed in class_nextMethodList() may occur.
191 * void *iterator = nil;
192 * old_method_list *mlist;
193 * mutex_locker_t lock(methodListLock);
194 * while ((mlist = nextMethodList(cls, &iterator))) {
195 * // do something with mlist
197 **********************************************************************/
198 static old_method_list *nextMethodList(Class cls,
201 uintptr_t index = *(uintptr_t *)it;
202 old_method_list **resultp;
205 // First call to nextMethodList.
206 if (!cls->methodLists) {
208 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
209 resultp = (old_method_list **)&cls->methodLists;
211 resultp = &cls->methodLists[0];
212 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
217 // Subsequent call to nextMethodList.
218 if (!cls->methodLists) {
220 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
223 resultp = &cls->methodLists[index];
224 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
230 // resultp now is nil, meaning there are no more method lists,
231 // OR the address of the method list pointer to fix up and return.
235 *resultp = fixupSelectorsInMethodList(cls, *resultp);
237 *it = (void *)(index + 1);
246 /* These next three functions are the heart of ObjC method lookup.
247 * If the class is currently in use, methodListLock must be held by the caller.
249 static inline old_method *_findMethodInList(old_method_list * mlist, SEL sel) {
251 if (!mlist) return nil;
252 for (i = 0; i < mlist->method_count; i++) {
253 old_method *m = &mlist->method_list[i];
254 if (m->method_name == sel) {
261 static inline old_method * _findMethodInClass(Class cls, SEL sel) __attribute__((always_inline));
262 static inline old_method * _findMethodInClass(Class cls, SEL sel) {
263 // Flattened version of nextMethodList(). The optimizer doesn't
264 // do a good job with hoisting the conditionals out of the loop.
265 // Conceptually, this looks like:
266 // while ((mlist = nextMethodList(cls, &iterator))) {
267 // old_method *m = _findMethodInList(mlist, sel);
271 if (!cls->methodLists) {
275 else if (cls->info & CLS_NO_METHOD_ARRAY) {
277 old_method_list **mlistp;
278 mlistp = (old_method_list **)&cls->methodLists;
279 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
280 return _findMethodInList(*mlistp, sel);
283 // Multiple method lists.
284 old_method_list **mlistp;
285 for (mlistp = cls->methodLists;
286 *mlistp != nil && *mlistp != END_OF_METHODS_LIST;
290 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
291 m = _findMethodInList(*mlistp, sel);
298 static inline old_method * _getMethod(Class cls, SEL sel) {
299 for (; cls; cls = cls->superclass) {
301 m = _findMethodInClass(cls, sel);
308 // called by a debugging check in _objc_insertMethods
309 IMP findIMPInClass(Class cls, SEL sel)
311 old_method *m = _findMethodInClass(cls, sel);
312 if (m) return m->method_imp;
317 /***********************************************************************
319 **********************************************************************/
320 static void _freedHandler(id obj, SEL sel)
322 __objc_error (obj, "message %s sent to freed object=%p",
323 sel_getName(sel), (void*)obj);
327 /***********************************************************************
329 * Log this method call. If the logger permits it, fill the method cache.
330 * cls is the method whose cache should be filled.
331 * implementer is the class that owns the implementation in question.
332 **********************************************************************/
334 log_and_fill_cache(Class cls, Class implementer, Method meth, SEL sel)
336 #if SUPPORT_MESSAGE_LOGGING
337 if (objcMsgLogEnabled) {
338 bool cacheIt = logMessageSend(implementer->isMetaClass(),
339 cls->nameForLogging(),
340 implementer->nameForLogging(),
342 if (!cacheIt) return;
345 _cache_fill (cls, meth, sel);
349 /***********************************************************************
350 * _class_lookupMethodAndLoadCache.
351 * Method lookup for dispatchers ONLY. OTHER CODE SHOULD USE lookUpImp().
352 * This lookup avoids optimistic cache scan because the dispatcher
353 * already tried that.
354 **********************************************************************/
355 IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
357 return lookUpImpOrForward(cls, sel, obj,
358 YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
362 /***********************************************************************
363 * lookUpImpOrForward.
364 * The standard IMP lookup.
365 * initialize==NO tries to avoid +initialize (but sometimes fails)
366 * cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
367 * Most callers should use initialize==YES and cache==YES.
368 * inst is an instance of cls or a subclass thereof, or nil if none is known.
369 * If cls is an un-initialized metaclass then a non-nil inst is faster.
370 * May return _objc_msgForward_impcache. IMPs destined for external use
371 * must be converted to _objc_msgForward or _objc_msgForward_stret.
372 * If you don't want forwarding at all, use lookUpImpOrNil() instead.
373 **********************************************************************/
374 IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
375 bool initialize, bool cache, bool resolver)
380 bool triedResolver = NO;
382 methodListLock.assertUnlocked();
384 // Optimistic cache lookup
386 methodPC = _cache_getImp(cls, sel);
387 if (methodPC) return methodPC;
390 // Check for freed class
391 if (cls == _class_getFreedObjectClass())
392 return (IMP) _freedHandler;
394 // Check for +initialize
395 if (initialize && !cls->isInitialized()) {
396 _class_initialize (_class_getNonMetaClass(cls, inst));
397 // If sel == initialize, _class_initialize will send +initialize and
398 // then the messenger will send +initialize again after this
399 // procedure finishes. Of course, if this is not being called
400 // from the messenger then it won't happen. 2778172
403 // The lock is held to make method-lookup + cache-fill atomic
404 // with respect to method addition. Otherwise, a category could
405 // be added but ignored indefinitely because the cache was re-filled
406 // with the old value after the cache flush on behalf of the category.
408 methodListLock.lock();
410 // Try this class's cache.
412 methodPC = _cache_getImp(cls, sel);
413 if (methodPC) goto done;
415 // Try this class's method lists.
417 meth = _class_getMethodNoSuper_nolock(cls, sel);
419 log_and_fill_cache(cls, cls, meth, sel);
420 methodPC = method_getImplementation(meth);
424 // Try superclass caches and method lists.
427 while ((curClass = curClass->superclass)) {
429 meth = _cache_getMethod(curClass, sel, _objc_msgForward_impcache);
431 if (meth != (Method)1) {
432 // Found the method in a superclass. Cache it in this class.
433 log_and_fill_cache(cls, curClass, meth, sel);
434 methodPC = method_getImplementation(meth);
438 // Found a forward:: entry in a superclass.
439 // Stop searching, but don't cache yet; call method
440 // resolver for this class first.
445 // Superclass method list.
446 meth = _class_getMethodNoSuper_nolock(curClass, sel);
448 log_and_fill_cache(cls, curClass, meth, sel);
449 methodPC = method_getImplementation(meth);
454 // No implementation found. Try method resolver once.
456 if (resolver && !triedResolver) {
457 methodListLock.unlock();
458 _class_resolveMethod(cls, sel, inst);
463 // No implementation found, and method resolver didn't help.
466 _cache_addForwardEntry(cls, sel);
467 methodPC = _objc_msgForward_impcache;
470 methodListLock.unlock();
476 /***********************************************************************
478 * Like lookUpImpOrForward, but returns nil instead of _objc_msgForward_impcache
479 **********************************************************************/
480 IMP lookUpImpOrNil(Class cls, SEL sel, id inst,
481 bool initialize, bool cache, bool resolver)
483 IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
484 if (imp == _objc_msgForward_impcache) return nil;
489 /***********************************************************************
490 * lookupMethodInClassAndLoadCache.
491 * Like _class_lookupMethodAndLoadCache, but does not search superclasses.
492 * Caches and returns objc_msgForward if the method is not found in the class.
493 **********************************************************************/
494 IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel)
499 // fixme this still has the method list vs method cache race
500 // because it doesn't hold a lock across lookup+cache_fill,
501 // but it's only used for .cxx_construct/destruct and we assume
502 // categories don't change them.
504 // Search cache first.
505 imp = _cache_getImp(cls, sel);
508 // Cache miss. Search method list.
510 meth = _class_getMethodNoSuper(cls, sel);
513 // Hit in method list. Cache it.
514 _cache_fill(cls, meth, sel);
515 return method_getImplementation(meth);
517 // Miss in method list. Cache objc_msgForward.
518 _cache_addForwardEntry(cls, sel);
519 return _objc_msgForward_impcache;
524 /***********************************************************************
525 * _class_getClassForIvar
526 * Given a class and an ivar that is in it or one of its superclasses,
527 * find the actual class that defined the ivar.
528 **********************************************************************/
529 Class _class_getClassForIvar(Class cls, Ivar ivar)
531 for ( ; cls; cls = cls->superclass) {
532 if (auto ivars = cls->ivars) {
533 if (ivar >= &ivars->ivar_list[0] &&
534 ivar < &ivars->ivar_list[ivars->ivar_count])
545 /***********************************************************************
546 * class_getVariable. Return the named instance variable.
547 **********************************************************************/
549 Ivar _class_getVariable(Class cls, const char *name)
551 for (; cls != Nil; cls = cls->superclass) {
554 // Skip class having no ivars
555 if (!cls->ivars) continue;
557 for (i = 0; i < cls->ivars->ivar_count; i++) {
558 // Check this ivar's name. Be careful because the
559 // compiler generates ivar entries with nil ivar_name
560 // (e.g. for anonymous bit fields).
561 old_ivar *ivar = &cls->ivars->ivar_list[i];
562 if (ivar->ivar_name && 0 == strcmp(name, ivar->ivar_name)) {
574 property_list_nth(const old_property_list *plist, uint32_t i)
576 return (old_property *)(i*plist->entsize + (char *)&plist->first);
580 copyPropertyList(old_property_list *plist, unsigned int *outCount)
582 old_property **result = nil;
583 unsigned int count = 0;
586 count = plist->count;
591 result = (old_property **)malloc((count+1) * sizeof(old_property *));
593 for (i = 0; i < count; i++) {
594 result[i] = property_list_nth(plist, i);
599 if (outCount) *outCount = count;
604 static old_property_list *
605 nextPropertyList(Class cls, uintptr_t *indexp)
607 old_property_list *result = nil;
609 classLock.assertLocked();
610 if (! ((cls->info & CLS_EXT) && cls->ext)) {
613 } else if (!cls->ext->propertyLists) {
616 } else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
617 // Only one property list
619 result = (old_property_list *)cls->ext->propertyLists;
624 // More than one property list
625 result = cls->ext->propertyLists[*indexp];
638 /***********************************************************************
639 * class_getIvarLayout
640 * nil means all-scanned. "" means non-scanned.
641 **********************************************************************/
643 class_getIvarLayout(Class cls)
645 if (cls && (cls->info & CLS_EXT)) {
646 return cls->ivar_layout;
648 return nil; // conservative scan
653 /***********************************************************************
654 * class_getWeakIvarLayout
655 * nil means no weak ivars.
656 **********************************************************************/
658 class_getWeakIvarLayout(Class cls)
660 if (cls && (cls->info & CLS_EXT) && cls->ext) {
661 return cls->ext->weak_ivar_layout;
663 return nil; // no weak ivars
668 /***********************************************************************
669 * class_setIvarLayout
670 * nil means all-scanned. "" means non-scanned.
671 **********************************************************************/
672 void class_setIvarLayout(Class cls, const uint8_t *layout)
676 if (! (cls->info & CLS_EXT)) {
677 _objc_inform("class '%s' needs to be recompiled", cls->name);
682 cls->ivar_layout = ustrdupMaybeNil(layout);
686 /***********************************************************************
687 * class_setWeakIvarLayout
688 * nil means no weak ivars.
689 **********************************************************************/
690 void class_setWeakIvarLayout(Class cls, const uint8_t *layout)
694 mutex_locker_t lock(classLock);
699 cls->ext->weak_ivar_layout = ustrdupMaybeNil(layout);
703 /***********************************************************************
704 * class_setVersion. Record the specified version with the class.
705 **********************************************************************/
706 void class_setVersion(Class cls, int version)
709 cls->version = version;
712 /***********************************************************************
713 * class_getVersion. Return the version recorded with the class.
714 **********************************************************************/
715 int class_getVersion(Class cls)
718 return (int)cls->version;
722 /***********************************************************************
724 **********************************************************************/
725 const char *class_getName(Class cls)
727 if (!cls) return "nil";
728 else return cls->demangledName();
732 /***********************************************************************
733 * _class_getNonMetaClass.
734 * Return the ordinary class for this class or metaclass.
735 * Used by +initialize.
736 **********************************************************************/
737 Class _class_getNonMetaClass(Class cls, id obj)
740 if (cls->isMetaClass()) {
741 if (cls->info & CLS_CONSTRUCTING) {
742 // Class is under construction and isn't in the class_hash,
743 // so objc_getClass doesn't work.
744 cls = obj; // fixme this may be nil in some paths
746 else if (strncmp(cls->name, "_%", 2) == 0) {
747 // Posee's meta's name is smashed and isn't in the class_hash,
748 // so objc_getClass doesn't work.
749 const char *baseName = strchr(cls->name, '%'); // get posee's real name
750 cls = objc_getClass(baseName);
753 cls = objc_getClass(cls->name);
762 Cache _class_getCache(Class cls)
767 void _class_setCache(Class cls, Cache cache)
772 const char *_category_getName(Category cat)
774 return oldcategory(cat)->category_name;
777 const char *_category_getClassName(Category cat)
779 return oldcategory(cat)->class_name;
782 Class _category_getClass(Category cat)
784 return objc_getClass(oldcategory(cat)->class_name);
787 IMP _category_getLoadMethod(Category cat)
789 old_method_list *mlist = oldcategory(cat)->class_methods;
791 return lookupNamedMethodInMethodList(mlist, "load");
799 /***********************************************************************
800 * class_nextMethodList.
801 * External version of nextMethodList().
803 * This function is not fully thread-safe. A series of calls to
804 * class_nextMethodList() may fail if methods are added to or removed
805 * from the class between calls.
806 * If methods are added between calls to class_nextMethodList(), it may
807 * return previously-returned method lists again, and may fail to return
809 * If methods are removed between calls to class_nextMethodList(), it may
810 * omit surviving method lists or simply crash.
811 **********************************************************************/
812 struct objc_method_list *class_nextMethodList(Class cls, void **it)
814 OBJC_WARN_DEPRECATED;
816 mutex_locker_t lock(methodListLock);
817 return (struct objc_method_list *) nextMethodList(cls, it);
821 /***********************************************************************
824 * Formerly class_addInstanceMethods ()
825 **********************************************************************/
826 void class_addMethods(Class cls, struct objc_method_list *meths)
828 OBJC_WARN_DEPRECATED;
832 mutex_locker_t lock(methodListLock);
833 _objc_insertMethods(cls, (old_method_list *)meths, nil);
836 // Must flush when dynamically adding methods. No need to flush
837 // all the class method caches. If cls is a meta class, though,
838 // this will still flush it and any of its sub-meta classes.
839 flush_caches (cls, NO);
843 /***********************************************************************
844 * class_removeMethods.
845 **********************************************************************/
846 void class_removeMethods(Class cls, struct objc_method_list *meths)
848 OBJC_WARN_DEPRECATED;
850 // Remove the methods
852 mutex_locker_t lock(methodListLock);
853 _objc_removeMethods(cls, (old_method_list *)meths);
856 // Must flush when dynamically removing methods. No need to flush
857 // all the class method caches. If cls is a meta class, though,
858 // this will still flush it and any of its sub-meta classes.
859 flush_caches (cls, NO);
862 /***********************************************************************
863 * lookupNamedMethodInMethodList
864 * Only called to find +load/-.cxx_construct/-.cxx_destruct methods,
865 * without fixing up the entire method list.
866 * The class is not yet in use, so methodListLock is not taken.
867 **********************************************************************/
868 IMP lookupNamedMethodInMethodList(old_method_list *mlist, const char *meth_name)
871 m = meth_name ? _findNamedMethodInList(mlist, meth_name) : nil;
872 return (m ? m->method_imp : nil);
875 static Method _class_getMethod(Class cls, SEL sel)
877 mutex_locker_t lock(methodListLock);
878 return (Method)_getMethod(cls, sel);
881 static Method _class_getMethodNoSuper(Class cls, SEL sel)
883 mutex_locker_t lock(methodListLock);
884 return (Method)_findMethodInClass(cls, sel);
887 static Method _class_getMethodNoSuper_nolock(Class cls, SEL sel)
889 methodListLock.assertLocked();
890 return (Method)_findMethodInClass(cls, sel);
894 /***********************************************************************
895 * class_getInstanceMethod. Return the instance method for the
896 * specified class and selector.
897 **********************************************************************/
898 Method class_getInstanceMethod(Class cls, SEL sel)
900 if (!cls || !sel) return nil;
902 // This deliberately avoids +initialize because it historically did so.
904 // This implementation is a bit weird because it's the only place that
905 // wants a Method instead of an IMP.
908 meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache);
909 if (meth == (Method)1) {
910 // Cache contains forward:: . Stop searching.
916 // Search method lists, try method resolver, etc.
917 lookUpImpOrNil(cls, sel, nil,
918 NO/*initialize*/, NO/*cache*/, YES/*resolver*/);
920 meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache);
921 if (meth == (Method)1) {
922 // Cache contains forward:: . Stop searching.
928 return _class_getMethod(cls, sel);
932 BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen)
934 old_protocol *proto = oldprotocol(proto_gen);
937 if (!proto) return NO;
939 if (cls->ISA()->version >= 3) {
940 old_protocol_list *list;
941 for (list = cls->protocols; list != nil; list = list->next) {
943 for (i = 0; i < list->count; i++) {
944 if (list->list[i] == proto) return YES;
945 if (protocol_conformsToProtocol((Protocol *)list->list[i], proto_gen)) return YES;
947 if (cls->ISA()->version <= 4) break;
954 static NXMapTable * posed_class_hash = nil;
956 /***********************************************************************
958 **********************************************************************/
960 Class _objc_getOrigClass(const char *name)
962 // Look for class among the posers
964 mutex_locker_t lock(classLock);
965 if (posed_class_hash) {
966 Class cls = (Class) NXMapGet (posed_class_hash, name);
971 // Not a poser. Do a normal lookup.
972 Class cls = objc_getClass (name);
975 _objc_inform ("class `%s' not linked into application", name);
979 Class objc_getOrigClass(const char *name)
981 OBJC_WARN_DEPRECATED;
982 return _objc_getOrigClass(name);
985 /***********************************************************************
986 * _objc_addOrigClass. This function is only used from class_poseAs.
987 * Registers the original class names, before they get obscured by
988 * posing, so that [super ..] will work correctly from categories
989 * in posing classes and in categories in classes being posed for.
990 **********************************************************************/
991 static void _objc_addOrigClass (Class origClass)
993 mutex_locker_t lock(classLock);
995 // Create the poser's hash table on first use
996 if (!posed_class_hash)
998 posed_class_hash = NXCreateMapTable(NXStrValueMapPrototype, 8);
1001 // Add the named class iff it is not already there (or collides?)
1002 if (NXMapGet (posed_class_hash, origClass->name) == 0)
1003 NXMapInsert (posed_class_hash, origClass->name, origClass);
1007 /***********************************************************************
1008 * change_class_references
1009 * Change classrefs and superclass pointers from original to imposter
1010 * But if copy!=nil, don't change copy->superclass.
1011 * If changeSuperRefs==YES, also change [super message] classrefs.
1012 * Used by class_poseAs and objc_setFutureClass
1013 * classLock must be locked.
1014 **********************************************************************/
1015 void change_class_references(Class imposter,
1018 bool changeSuperRefs)
1024 // Change all subclasses of the original to point to the imposter.
1025 state = NXInitHashState (class_hash);
1026 while (NXNextHashState (class_hash, &state, (void **) &clsObject))
1028 while ((clsObject) && (clsObject != imposter) &&
1029 (clsObject != copy))
1031 if (clsObject->superclass == original)
1033 clsObject->superclass = imposter;
1034 clsObject->ISA()->superclass = imposter->ISA();
1035 // We must flush caches here!
1039 clsObject = clsObject->superclass;
1043 // Replace the original with the imposter in all class refs
1044 // Major loop - process all headers
1045 for (hInfo = FirstHeader; hInfo != nil; hInfo = hInfo->getNext())
1051 // Fix class refs associated with this header
1052 cls_refs = _getObjcClassRefs(hInfo, &refCount);
1054 for (index = 0; index < refCount; index += 1) {
1055 if (cls_refs[index] == original) {
1056 cls_refs[index] = imposter;
1064 /***********************************************************************
1067 * !!! class_poseAs () does not currently flush any caches.
1068 **********************************************************************/
1069 Class class_poseAs(Class imposter, Class original)
1071 char * imposterNamePtr;
1074 OBJC_WARN_DEPRECATED;
1076 // Trivial case is easy
1077 if (imposter == original)
1080 // Imposter must be an immediate subclass of the original
1081 if (imposter->superclass != original) {
1082 __objc_error(imposter,
1083 "[%s poseAs:%s]: target not immediate superclass",
1084 imposter->name, original->name);
1087 // Can't pose when you have instance variables (how could it work?)
1088 if (imposter->ivars) {
1089 __objc_error(imposter,
1090 "[%s poseAs:%s]: %s defines new instance variables",
1091 imposter->name, original->name, imposter->name);
1094 // Build a string to use to replace the name of the original class.
1096 # define imposterNamePrefix "_%"
1097 imposterNamePtr = malloc(strlen(original->name) + strlen(imposterNamePrefix) + 1);
1098 strcpy(imposterNamePtr, imposterNamePrefix);
1099 strcat(imposterNamePtr, original->name);
1100 # undef imposterNamePrefix
1102 asprintf(&imposterNamePtr, "_%%%s", original->name);
1105 // We lock the class hashtable, so we are thread safe with respect to
1106 // calls to objc_getClass (). However, the class names are not
1107 // changed atomically, nor are all of the subclasses updated
1108 // atomically. I have ordered the operations so that you will
1109 // never crash, but you may get inconsistent results....
1111 // Register the original class so that [super ..] knows
1112 // exactly which classes are the "original" classes.
1113 _objc_addOrigClass (original);
1114 _objc_addOrigClass (imposter);
1116 // Copy the imposter, so that the imposter can continue
1117 // its normal life in addition to changing the behavior of
1118 // the original. As a hack we don't bother to copy the metaclass.
1119 // For some reason we modify the original rather than the copy.
1120 copy = (Class)malloc(sizeof(objc_class));
1121 memmove(copy, imposter, sizeof(objc_class));
1123 mutex_locker_t lock(classLock);
1125 // Remove both the imposter and the original class.
1126 NXHashRemove (class_hash, imposter);
1127 NXHashRemove (class_hash, original);
1129 NXHashInsert (class_hash, copy);
1131 // Mark the imposter as such
1132 imposter->setInfo(CLS_POSING);
1133 imposter->ISA()->setInfo(CLS_POSING);
1135 // Change the name of the imposter to that of the original class.
1136 imposter->name = original->name;
1137 imposter->ISA()->name = original->ISA()->name;
1139 // Also copy the version field to avoid archiving problems.
1140 imposter->version = original->version;
1142 // Change classrefs and superclass pointers
1143 // Don't change copy->superclass
1144 // Don't change [super ...] messages
1145 change_class_references(imposter, original, copy, NO);
1147 // Change the name of the original class.
1148 original->name = imposterNamePtr + 1;
1149 original->ISA()->name = imposterNamePtr;
1151 // Restore the imposter and the original class with their new names.
1152 NXHashInsert (class_hash, imposter);
1153 NXHashInsert (class_hash, original);
1159 /***********************************************************************
1160 * _objc_flush_caches. Flush the instance and class method caches
1161 * of cls and all its subclasses.
1163 * Specifying Nil for the class "all classes."
1164 **********************************************************************/
1165 static void flush_caches(Class target, bool flush_meta)
1167 bool collectALot = (target == nil);
1170 #ifdef OBJC_INSTRUMENTED
1171 unsigned int classesVisited;
1172 unsigned int subclassCount;
1175 mutex_locker_t lock(classLock);
1176 mutex_locker_t lock2(cacheUpdateLock);
1178 // Leaf classes are fastest because there are no subclass caches to flush.
1180 if (target && (target->info & CLS_LEAF)) {
1181 _cache_flush (target);
1183 if (target->ISA() && (target->ISA()->info & CLS_LEAF)) {
1184 _cache_flush (target->ISA());
1187 // Reset target and handle it by one of the methods below.
1188 target = target->ISA();
1194 state = NXInitHashState(class_hash);
1196 // Handle nil and root instance class specially: flush all
1197 // instance and class method caches. Nice that this
1198 // loop is linear vs the N-squared loop just below.
1199 if (!target || !target->superclass)
1201 #ifdef OBJC_INSTRUMENTED
1202 LinearFlushCachesCount += 1;
1206 // Traverse all classes in the hash table
1207 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1209 Class metaClsObject;
1210 #ifdef OBJC_INSTRUMENTED
1211 classesVisited += 1;
1214 // Skip class that is known not to be a subclass of this root
1215 // (the isa pointer of any meta class points to the meta class
1217 // NOTE: When is an isa pointer of a hash tabled class ever nil?
1218 metaClsObject = clsObject->ISA();
1219 if (target && metaClsObject && target->ISA() != metaClsObject->ISA()) {
1223 #ifdef OBJC_INSTRUMENTED
1227 _cache_flush (clsObject);
1228 if (flush_meta && metaClsObject != nil) {
1229 _cache_flush (metaClsObject);
1232 #ifdef OBJC_INSTRUMENTED
1233 LinearFlushCachesVisitedCount += classesVisited;
1234 if (classesVisited > MaxLinearFlushCachesVisitedCount)
1235 MaxLinearFlushCachesVisitedCount = classesVisited;
1236 IdealFlushCachesCount += subclassCount;
1237 if (subclassCount > MaxIdealFlushCachesCount)
1238 MaxIdealFlushCachesCount = subclassCount;
1244 // Outer loop - flush any cache that could now get a method from
1245 // cls (i.e. the cache associated with cls and any of its subclasses).
1246 #ifdef OBJC_INSTRUMENTED
1247 NonlinearFlushCachesCount += 1;
1251 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1255 #ifdef OBJC_INSTRUMENTED
1256 NonlinearFlushCachesClassCount += 1;
1259 // Inner loop - Process a given class
1260 clsIter = clsObject;
1264 #ifdef OBJC_INSTRUMENTED
1265 classesVisited += 1;
1267 // Flush clsObject instance method cache if
1268 // clsObject is a subclass of cls, or is cls itself
1269 // Flush the class method cache if that was asked for
1270 if (clsIter == target)
1272 #ifdef OBJC_INSTRUMENTED
1275 _cache_flush (clsObject);
1277 _cache_flush (clsObject->ISA());
1283 // Flush clsObject class method cache if cls is
1284 // the meta class of clsObject or of one
1285 // of clsObject's superclasses
1286 else if (clsIter->ISA() == target)
1288 #ifdef OBJC_INSTRUMENTED
1291 _cache_flush (clsObject->ISA());
1295 // Move up superclass chain
1296 // else if (clsIter->isInitialized())
1297 clsIter = clsIter->superclass;
1299 // clsIter is not initialized, so its cache
1300 // must be empty. This happens only when
1301 // clsIter == clsObject, because
1302 // superclasses are initialized before
1303 // subclasses, and this loop traverses
1304 // from sub- to super- classes.
1309 #ifdef OBJC_INSTRUMENTED
1310 NonlinearFlushCachesVisitedCount += classesVisited;
1311 if (classesVisited > MaxNonlinearFlushCachesVisitedCount)
1312 MaxNonlinearFlushCachesVisitedCount = classesVisited;
1313 IdealFlushCachesCount += subclassCount;
1314 if (subclassCount > MaxIdealFlushCachesCount)
1315 MaxIdealFlushCachesCount = subclassCount;
1321 _cache_collect(true);
1326 void _objc_flush_caches(Class target)
1328 flush_caches(target, YES);
1333 /***********************************************************************
1334 * flush_marked_caches. Flush the method cache of any class marked
1335 * CLS_FLUSH_CACHE (and all subclasses thereof)
1337 **********************************************************************/
1338 void flush_marked_caches(void)
1344 mutex_locker_t lock(classLock);
1345 mutex_locker_t lock2(cacheUpdateLock);
1347 state = NXInitHashState(class_hash);
1348 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1349 for (supercls = cls; supercls; supercls = supercls->superclass) {
1350 if (supercls->info & CLS_FLUSH_CACHE) {
1356 for (supercls = cls->ISA(); supercls; supercls = supercls->superclass) {
1357 if (supercls->info & CLS_FLUSH_CACHE) {
1358 _cache_flush(cls->ISA());
1364 state = NXInitHashState(class_hash);
1365 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1366 if (cls->info & CLS_FLUSH_CACHE) {
1367 cls->clearInfo(CLS_FLUSH_CACHE);
1369 if (cls->ISA()->info & CLS_FLUSH_CACHE) {
1370 cls->ISA()->clearInfo(CLS_FLUSH_CACHE);
1376 /***********************************************************************
1377 * get_base_method_list
1378 * Returns the method list containing the class's own methods,
1379 * ignoring any method lists added by categories or class_addMethods.
1380 * Called only by add_class_to_loadable_list.
1381 * Does not hold methodListLock because add_class_to_loadable_list
1382 * does not manipulate in-use classes.
1383 **********************************************************************/
1384 static old_method_list *get_base_method_list(Class cls)
1386 old_method_list **ptr;
1388 if (!cls->methodLists) return nil;
1389 if (cls->info & CLS_NO_METHOD_ARRAY) return (old_method_list *)cls->methodLists;
1390 ptr = cls->methodLists;
1391 if (!*ptr || *ptr == END_OF_METHODS_LIST) return nil;
1392 while ( *ptr != 0 && *ptr != END_OF_METHODS_LIST ) { ptr++; }
1398 static IMP _class_getLoadMethod_nocheck(Class cls)
1400 old_method_list *mlist;
1401 mlist = get_base_method_list(cls->ISA());
1403 return lookupNamedMethodInMethodList (mlist, "load");
1409 bool _class_hasLoadMethod(Class cls)
1411 if (cls->ISA()->info & CLS_HAS_LOAD_METHOD) return YES;
1412 return _class_getLoadMethod_nocheck(cls);
1416 /***********************************************************************
1417 * objc_class::getLoadMethod
1418 * Returns cls's +load implementation, or nil if it doesn't have one.
1419 **********************************************************************/
1420 IMP objc_class::getLoadMethod()
1422 if (ISA()->info & CLS_HAS_LOAD_METHOD) {
1423 return _class_getLoadMethod_nocheck((Class)this);
1428 ptrdiff_t ivar_getOffset(Ivar ivar)
1430 return oldivar(ivar)->ivar_offset;
1433 const char *ivar_getName(Ivar ivar)
1435 return oldivar(ivar)->ivar_name;
1438 const char *ivar_getTypeEncoding(Ivar ivar)
1440 return oldivar(ivar)->ivar_type;
1444 IMP method_getImplementation(Method m)
1447 return oldmethod(m)->method_imp;
1450 SEL method_getName(Method m)
1453 return oldmethod(m)->method_name;
1456 const char *method_getTypeEncoding(Method m)
1459 return oldmethod(m)->method_types;
1462 unsigned int method_getSizeOfArguments(Method m)
1464 OBJC_WARN_DEPRECATED;
1466 return encoding_getSizeOfArguments(method_getTypeEncoding(m));
1469 // This function was accidentally un-exported beginning in macOS 10.9.
1470 // As of macOS 10.13 nobody had complained.
1472 unsigned int method_getArgumentInfo(Method m, int arg,
1473 const char **type, int *offset)
1475 OBJC_WARN_DEPRECATED;
1477 return encoding_getArgumentInfo(method_getTypeEncoding(m),
1485 IMP method_setImplementation(Method m_gen, IMP imp)
1488 old_method *m = oldmethod(m_gen);
1490 if (!imp) return nil;
1493 old = m->method_imp;
1494 m->method_imp = imp;
1500 void method_exchangeImplementations(Method m1_gen, Method m2_gen)
1503 old_method *m1 = oldmethod(m1_gen);
1504 old_method *m2 = oldmethod(m2_gen);
1505 if (!m1 || !m2) return;
1508 m1_imp = m1->method_imp;
1509 m1->method_imp = m2->method_imp;
1510 m2->method_imp = m1_imp;
1515 struct objc_method_description * method_getDescription(Method m)
1518 return (struct objc_method_description *)oldmethod(m);
1522 const char *property_getName(objc_property_t prop)
1524 return oldproperty(prop)->name;
1527 const char *property_getAttributes(objc_property_t prop)
1529 return oldproperty(prop)->attributes;
1532 objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
1533 unsigned int *outCount)
1536 if (outCount) *outCount = 0;
1540 mutex_locker_t lock(classLock);
1541 return copyPropertyAttributeList(oldproperty(prop)->attributes,outCount);
1544 char * property_copyAttributeValue(objc_property_t prop, const char *name)
1546 if (!prop || !name || *name == '\0') return nil;
1548 mutex_locker_t lock(classLock);
1549 return copyPropertyAttributeValue(oldproperty(prop)->attributes, name);
1553 /***********************************************************************
1555 **********************************************************************/
1556 static IMP _class_addMethod(Class cls, SEL name, IMP imp,
1557 const char *types, bool replace)
1562 if (!types) types = "";
1564 mutex_locker_t lock(methodListLock);
1566 if ((m = _findMethodInClass(cls, name))) {
1569 result = method_getImplementation((Method)m);
1571 method_setImplementation((Method)m, imp);
1574 // fixme could be faster
1575 old_method_list *mlist =
1576 (old_method_list *)calloc(sizeof(old_method_list), 1);
1577 mlist->obsolete = fixed_up_method_list;
1578 mlist->method_count = 1;
1579 mlist->method_list[0].method_name = name;
1580 mlist->method_list[0].method_types = strdup(types);
1581 mlist->method_list[0].method_imp = imp;
1583 _objc_insertMethods(cls, mlist, nil);
1584 if (!(cls->info & CLS_CONSTRUCTING)) {
1585 flush_caches(cls, NO);
1587 // in-construction class has no subclasses
1597 /***********************************************************************
1599 **********************************************************************/
1600 BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
1603 if (!cls) return NO;
1605 old = _class_addMethod(cls, name, imp, types, NO);
1610 /***********************************************************************
1611 * class_replaceMethod
1612 **********************************************************************/
1613 IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
1615 if (!cls) return nil;
1617 return _class_addMethod(cls, name, imp, types, YES);
1621 /***********************************************************************
1623 **********************************************************************/
1624 BOOL class_addIvar(Class cls, const char *name, size_t size,
1625 uint8_t alignment, const char *type)
1629 if (!cls) return NO;
1630 if (ISMETA(cls)) return NO;
1631 if (!(cls->info & CLS_CONSTRUCTING)) return NO;
1633 if (!type) type = "";
1634 if (name && 0 == strcmp(name, "")) name = nil;
1636 mutex_locker_t lock(classLock);
1638 // Check for existing ivar with this name
1639 // fixme check superclasses?
1642 for (i = 0; i < cls->ivars->ivar_count; i++) {
1643 if (0 == strcmp(cls->ivars->ivar_list[i].ivar_name, name)) {
1651 old_ivar_list *old = cls->ivars;
1659 oldSize = sizeof(old_ivar_list) +
1660 (old->ivar_count - 1) * sizeof(old_ivar);
1661 newCount = 1 + old->ivar_count;
1663 oldSize = sizeof(old_ivar_list) - sizeof(old_ivar);
1667 // allocate new ivar list
1668 cls->ivars = (old_ivar_list *)
1669 calloc(oldSize+sizeof(old_ivar), 1);
1670 if (old) memcpy(cls->ivars, old, oldSize);
1671 if (old && malloc_size(old)) free(old);
1672 cls->ivars->ivar_count = newCount;
1673 ivar = &cls->ivars->ivar_list[newCount-1];
1675 // set ivar name and type
1676 ivar->ivar_name = strdup(name);
1677 ivar->ivar_type = strdup(type);
1679 // align if necessary
1680 alignBytes = 1 << alignment;
1681 misalign = cls->instance_size % alignBytes;
1682 if (misalign) cls->instance_size += (long)(alignBytes - misalign);
1684 // set ivar offset and increase instance size
1685 ivar->ivar_offset = (int)cls->instance_size;
1686 cls->instance_size += (long)size;
1693 /***********************************************************************
1695 **********************************************************************/
1696 BOOL class_addProtocol(Class cls, Protocol *protocol_gen)
1698 old_protocol *protocol = oldprotocol(protocol_gen);
1699 old_protocol_list *plist;
1701 if (!cls) return NO;
1702 if (class_conformsToProtocol(cls, protocol_gen)) return NO;
1704 mutex_locker_t lock(classLock);
1706 // fixme optimize - protocol list doesn't escape?
1707 plist = (old_protocol_list*)calloc(sizeof(old_protocol_list), 1);
1709 plist->list[0] = protocol;
1710 plist->next = cls->protocols;
1711 cls->protocols = plist;
1719 /***********************************************************************
1720 * _class_addProperties
1721 * Internal helper to add properties to a class.
1722 * Used by category attachment and class_addProperty()
1723 * Locking: acquires classLock
1724 **********************************************************************/
1726 _class_addProperties(Class cls,
1727 old_property_list *additions)
1729 old_property_list *newlist;
1731 if (!(cls->info & CLS_EXT)) return NO;
1733 newlist = (old_property_list *)
1734 memdup(additions, sizeof(*newlist) - sizeof(newlist->first)
1735 + (additions->entsize * additions->count));
1737 mutex_locker_t lock(classLock);
1740 if (!cls->ext->propertyLists) {
1741 // cls has no properties - simply use this list
1742 cls->ext->propertyLists = (old_property_list **)newlist;
1743 cls->setInfo(CLS_NO_PROPERTY_ARRAY);
1745 else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
1746 // cls has one property list - make a new array
1747 old_property_list **newarray = (old_property_list **)
1748 malloc(3 * sizeof(*newarray));
1749 newarray[0] = newlist;
1750 newarray[1] = (old_property_list *)cls->ext->propertyLists;
1752 cls->ext->propertyLists = newarray;
1753 cls->clearInfo(CLS_NO_PROPERTY_ARRAY);
1756 // cls has a property array - make a bigger one
1757 old_property_list **newarray;
1759 while (cls->ext->propertyLists[count]) count++;
1760 newarray = (old_property_list **)
1761 malloc((count+2) * sizeof(*newarray));
1762 newarray[0] = newlist;
1763 memcpy(&newarray[1], &cls->ext->propertyLists[0],
1764 count * sizeof(*newarray));
1765 newarray[count+1] = nil;
1766 free(cls->ext->propertyLists);
1767 cls->ext->propertyLists = newarray;
1774 /***********************************************************************
1776 * Adds a property to a class. Returns NO if the proeprty already exists.
1777 * Locking: acquires classLock
1778 **********************************************************************/
1780 _class_addProperty(Class cls, const char *name,
1781 const objc_property_attribute_t *attrs, unsigned int count,
1784 if (!cls) return NO;
1785 if (!name) return NO;
1787 old_property *prop = oldproperty(class_getProperty(cls, name));
1788 if (prop && !replace) {
1789 // already exists, refuse to replace
1794 mutex_locker_t lock(classLock);
1795 try_free(prop->attributes);
1796 prop->attributes = copyPropertyAttributeString(attrs, count);
1801 old_property_list proplist;
1802 proplist.entsize = sizeof(old_property);
1804 proplist.first.name = strdup(name);
1805 proplist.first.attributes = copyPropertyAttributeString(attrs, count);
1807 return _class_addProperties(cls, &proplist);
1812 class_addProperty(Class cls, const char *name,
1813 const objc_property_attribute_t *attrs, unsigned int n)
1815 return _class_addProperty(cls, name, attrs, n, NO);
1819 class_replaceProperty(Class cls, const char *name,
1820 const objc_property_attribute_t *attrs, unsigned int n)
1822 _class_addProperty(cls, name, attrs, n, YES);
1826 /***********************************************************************
1827 * class_copyProtocolList. Returns a heap block containing the
1828 * protocols implemented by the class, or nil if the class
1829 * implements no protocols. Caller must free the block.
1830 * Does not copy any superclass's protocols.
1831 **********************************************************************/
1832 Protocol * __unsafe_unretained *
1833 class_copyProtocolList(Class cls, unsigned int *outCount)
1835 old_protocol_list *plist;
1836 Protocol **result = nil;
1837 unsigned int count = 0;
1841 if (outCount) *outCount = 0;
1845 mutex_locker_t lock(classLock);
1847 for (plist = cls->protocols; plist != nil; plist = plist->next) {
1848 count += (int)plist->count;
1852 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
1854 for (p = 0, plist = cls->protocols;
1856 plist = plist->next)
1859 for (i = 0; i < plist->count; i++) {
1860 result[p++] = (Protocol *)plist->list[i];
1866 if (outCount) *outCount = count;
1871 /***********************************************************************
1872 * class_getProperty. Return the named property.
1873 **********************************************************************/
1874 objc_property_t class_getProperty(Class cls, const char *name)
1876 if (!cls || !name) return nil;
1878 mutex_locker_t lock(classLock);
1880 for (; cls; cls = cls->superclass) {
1881 uintptr_t iterator = 0;
1882 old_property_list *plist;
1883 while ((plist = nextPropertyList(cls, &iterator))) {
1885 for (i = 0; i < plist->count; i++) {
1886 old_property *p = property_list_nth(plist, i);
1887 if (0 == strcmp(name, p->name)) {
1888 return (objc_property_t)p;
1898 /***********************************************************************
1899 * class_copyPropertyList. Returns a heap block containing the
1900 * properties declared in the class, or nil if the class
1901 * declares no properties. Caller must free the block.
1902 * Does not copy any superclass's properties.
1903 **********************************************************************/
1904 objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
1906 old_property_list *plist;
1907 uintptr_t iterator = 0;
1908 old_property **result = nil;
1909 unsigned int count = 0;
1913 if (outCount) *outCount = 0;
1917 mutex_locker_t lock(classLock);
1920 while ((plist = nextPropertyList(cls, &iterator))) {
1921 count += plist->count;
1925 result = (old_property **)malloc((count+1) * sizeof(old_property *));
1929 while ((plist = nextPropertyList(cls, &iterator))) {
1930 for (i = 0; i < plist->count; i++) {
1931 result[p++] = property_list_nth(plist, i);
1937 if (outCount) *outCount = count;
1938 return (objc_property_t *)result;
1942 /***********************************************************************
1943 * class_copyMethodList. Returns a heap block containing the
1944 * methods implemented by the class, or nil if the class
1945 * implements no methods. Caller must free the block.
1946 * Does not copy any superclass's methods.
1947 **********************************************************************/
1948 Method *class_copyMethodList(Class cls, unsigned int *outCount)
1950 old_method_list *mlist;
1951 void *iterator = nil;
1952 Method *result = nil;
1953 unsigned int count = 0;
1957 if (outCount) *outCount = 0;
1961 mutex_locker_t lock(methodListLock);
1964 while ((mlist = nextMethodList(cls, &iterator))) {
1965 count += mlist->method_count;
1969 result = (Method *)malloc((count+1) * sizeof(Method));
1973 while ((mlist = nextMethodList(cls, &iterator))) {
1975 for (i = 0; i < mlist->method_count; i++) {
1976 result[m++] = (Method)&mlist->method_list[i];
1982 if (outCount) *outCount = count;
1987 /***********************************************************************
1988 * class_copyIvarList. Returns a heap block containing the
1989 * ivars declared in the class, or nil if the class
1990 * declares no ivars. Caller must free the block.
1991 * Does not copy any superclass's ivars.
1992 **********************************************************************/
1993 Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
1996 unsigned int count = 0;
2000 if (outCount) *outCount = 0;
2005 count = cls->ivars->ivar_count;
2009 result = (Ivar *)malloc((count+1) * sizeof(Ivar));
2011 for (i = 0; i < cls->ivars->ivar_count; i++) {
2012 result[i] = (Ivar)&cls->ivars->ivar_list[i];
2017 if (outCount) *outCount = count;
2022 /***********************************************************************
2023 * objc_allocateClass.
2024 **********************************************************************/
2026 void set_superclass(Class cls, Class supercls, bool cls_is_new)
2028 Class meta = cls->ISA();
2031 cls->superclass = supercls;
2032 meta->superclass = supercls->ISA();
2033 meta->initIsa(supercls->ISA()->ISA());
2035 // Propagate C++ cdtors from superclass.
2036 if (supercls->info & CLS_HAS_CXX_STRUCTORS) {
2037 if (cls_is_new) cls->info |= CLS_HAS_CXX_STRUCTORS;
2038 else cls->setInfo(CLS_HAS_CXX_STRUCTORS);
2041 // Superclass is no longer a leaf for cache flushing
2042 if (supercls->info & CLS_LEAF) {
2043 supercls->clearInfo(CLS_LEAF);
2044 supercls->ISA()->clearInfo(CLS_LEAF);
2047 cls->superclass = Nil; // superclass of root class is nil
2048 meta->superclass = cls; // superclass of root metaclass is root class
2049 meta->initIsa(meta); // metaclass of root metaclass is root metaclass
2051 // Root class is never a leaf for cache flushing, because the
2052 // root metaclass is a subclass. (This could be optimized, but
2053 // is too uncommon to bother.)
2054 cls->clearInfo(CLS_LEAF);
2055 meta->clearInfo(CLS_LEAF);
2059 // &UnsetLayout is the default ivar layout during class construction
2060 static const uint8_t UnsetLayout = 0;
2062 Class objc_initializeClassPair(Class supercls, const char *name, Class cls, Class meta)
2064 // Connect to superclasses and metaclasses
2066 set_superclass(cls, supercls, YES);
2069 cls->name = strdup(name);
2070 meta->name = strdup(name);
2073 cls->info = CLS_CLASS | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2074 meta->info = CLS_META | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2076 // Set instance size based on superclass.
2078 cls->instance_size = supercls->instance_size;
2079 meta->instance_size = supercls->ISA()->instance_size;
2081 cls->instance_size = sizeof(Class); // just an isa
2082 meta->instance_size = sizeof(objc_class);
2085 // No ivars. No methods. Empty cache. No protocols. No layout. Empty ext.
2087 cls->methodLists = nil;
2088 cls->cache = (Cache)&_objc_empty_cache;
2089 cls->protocols = nil;
2090 cls->ivar_layout = &UnsetLayout;
2093 cls->ext->weak_ivar_layout = &UnsetLayout;
2096 meta->methodLists = nil;
2097 meta->cache = (Cache)&_objc_empty_cache;
2098 meta->protocols = nil;
2104 Class objc_allocateClassPair(Class supercls, const char *name,
2109 if (objc_getClass(name)) return nil;
2110 // fixme reserve class name against simultaneous allocation
2112 if (supercls && (supercls->info & CLS_CONSTRUCTING)) {
2113 // Can't make subclass of an in-construction class
2117 // Allocate new classes.
2119 cls = _calloc_class(supercls->ISA()->alignedInstanceSize() + extraBytes);
2120 meta = _calloc_class(supercls->ISA()->ISA()->alignedInstanceSize() + extraBytes);
2122 cls = _calloc_class(sizeof(objc_class) + extraBytes);
2123 meta = _calloc_class(sizeof(objc_class) + extraBytes);
2127 objc_initializeClassPair(supercls, name, cls, meta);
2133 void objc_registerClassPair(Class cls)
2135 if ((cls->info & CLS_CONSTRUCTED) ||
2136 (cls->ISA()->info & CLS_CONSTRUCTED))
2138 _objc_inform("objc_registerClassPair: class '%s' was already "
2139 "registered!", cls->name);
2143 if (!(cls->info & CLS_CONSTRUCTING) ||
2144 !(cls->ISA()->info & CLS_CONSTRUCTING))
2146 _objc_inform("objc_registerClassPair: class '%s' was not "
2147 "allocated with objc_allocateClassPair!", cls->name);
2152 _objc_inform("objc_registerClassPair: class '%s' is a metaclass, "
2153 "not a class!", cls->name);
2157 mutex_locker_t lock(classLock);
2159 // Clear "under construction" bit, set "done constructing" bit
2160 cls->info &= ~CLS_CONSTRUCTING;
2161 cls->ISA()->info &= ~CLS_CONSTRUCTING;
2162 cls->info |= CLS_CONSTRUCTED;
2163 cls->ISA()->info |= CLS_CONSTRUCTED;
2165 NXHashInsertIfAbsent(class_hash, cls);
2169 Class objc_duplicateClass(Class original, const char *name, size_t extraBytes)
2171 unsigned int count, i;
2172 old_method **originalMethods;
2173 old_method_list *duplicateMethods;
2174 // Don't use sizeof(objc_class) here because
2175 // instance_size has historically contained two extra words,
2176 // and instance_size is what objc_getIndexedIvars() actually uses.
2178 _calloc_class(original->ISA()->alignedInstanceSize() + extraBytes);
2180 duplicate->initIsa(original->ISA());
2181 duplicate->superclass = original->superclass;
2182 duplicate->name = strdup(name);
2183 duplicate->version = original->version;
2184 duplicate->info = original->info & (CLS_CLASS|CLS_META|CLS_INITIALIZED|CLS_JAVA_HYBRID|CLS_JAVA_CLASS|CLS_HAS_CXX_STRUCTORS|CLS_HAS_LOAD_METHOD);
2185 duplicate->instance_size = original->instance_size;
2186 duplicate->ivars = original->ivars;
2187 // methodLists handled below
2188 duplicate->cache = (Cache)&_objc_empty_cache;
2189 duplicate->protocols = original->protocols;
2190 if (original->info & CLS_EXT) {
2191 duplicate->info |= original->info & (CLS_EXT|CLS_NO_PROPERTY_ARRAY);
2192 duplicate->ivar_layout = original->ivar_layout;
2193 if (original->ext) {
2194 duplicate->ext = (old_class_ext *)malloc(original->ext->size);
2195 memcpy(duplicate->ext, original->ext, original->ext->size);
2197 duplicate->ext = nil;
2201 // Method lists are deep-copied so they can be stomped.
2202 originalMethods = (old_method **)class_copyMethodList(original, &count);
2203 if (originalMethods) {
2204 duplicateMethods = (old_method_list *)
2205 calloc(sizeof(old_method_list) +
2206 (count-1)*sizeof(old_method), 1);
2207 duplicateMethods->obsolete = fixed_up_method_list;
2208 duplicateMethods->method_count = count;
2209 for (i = 0; i < count; i++) {
2210 duplicateMethods->method_list[i] = *(originalMethods[i]);
2212 duplicate->methodLists = (old_method_list **)duplicateMethods;
2213 duplicate->info |= CLS_NO_METHOD_ARRAY;
2214 free(originalMethods);
2217 mutex_locker_t lock(classLock);
2218 NXHashInsert(class_hash, duplicate);
2224 void objc_disposeClassPair(Class cls)
2226 if (!(cls->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)) ||
2227 !(cls->ISA()->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)))
2229 // class not allocated with objc_allocateClassPair
2230 // disposing still-unregistered class is OK!
2231 _objc_inform("objc_disposeClassPair: class '%s' was not "
2232 "allocated with objc_allocateClassPair!", cls->name);
2237 _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
2238 "not a class!", cls->name);
2242 mutex_locker_t lock(classLock);
2243 NXHashRemove(class_hash, cls);
2244 unload_class(cls->ISA());
2249 /***********************************************************************
2250 * objc_constructInstance
2251 * Creates an instance of `cls` at the location pointed to by `bytes`.
2252 * `bytes` must point to at least class_getInstanceSize(cls) bytes of
2253 * well-aligned zero-filled memory.
2254 * The new object's isa is set. Any C++ constructors are called.
2255 * Returns `bytes` if successful. Returns nil if `cls` or `bytes` is
2256 * nil, or if C++ constructors fail.
2257 **********************************************************************/
2259 objc_constructInstance(Class cls, void *bytes)
2261 if (!cls || !bytes) return nil;
2267 if (cls->hasCxxCtor()) {
2268 return object_cxxConstructFromClass(obj, cls);
2275 /***********************************************************************
2276 * _class_createInstanceFromZone. Allocate an instance of the
2277 * specified class with the specified number of bytes for indexed
2278 * variables, in the specified zone. The isa field is set to the
2279 * class, C++ default constructors are called, and all other fields are zeroed.
2280 **********************************************************************/
2282 _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
2287 // Can't create something for nothing
2288 if (!cls) return nil;
2290 // Allocate and initialize
2291 size = cls->alignedInstanceSize() + extraBytes;
2293 // CF requires all objects be at least 16 bytes.
2294 if (size < 16) size = 16;
2297 bytes = malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
2299 bytes = calloc(1, size);
2302 return objc_constructInstance(cls, bytes);
2306 /***********************************************************************
2307 * _class_createInstance. Allocate an instance of the specified
2308 * class with the specified number of bytes for indexed variables, in
2309 * the default zone, using _class_createInstanceFromZone.
2310 **********************************************************************/
2311 static id _class_createInstance(Class cls, size_t extraBytes)
2313 return _class_createInstanceFromZone (cls, extraBytes, nil);
2317 static id _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
2322 if (!oldObj) return nil;
2324 obj = (*_zoneAlloc)(oldObj->ISA(), extraBytes, zone);
2325 size = oldObj->ISA()->alignedInstanceSize() + extraBytes;
2327 // fixme need C++ copy constructor
2328 memmove(obj, oldObj, size);
2330 fixupCopiedIvars(obj, oldObj);
2336 /***********************************************************************
2337 * objc_destructInstance
2338 * Destroys an instance without freeing memory.
2339 * Calls C++ destructors.
2340 * Removes associative references.
2341 * Returns `obj`. Does nothing if `obj` is nil.
2342 * CoreFoundation and other clients do call this under GC.
2343 **********************************************************************/
2344 void *objc_destructInstance(id obj)
2347 Class isa = obj->getIsa();
2349 if (isa->hasCxxDtor()) {
2350 object_cxxDestruct(obj);
2353 if (isa->instancesHaveAssociatedObjects()) {
2354 _object_remove_assocations(obj);
2357 objc_clear_deallocating(obj);
2364 _object_dispose(id anObject)
2366 if (anObject==nil) return nil;
2368 objc_destructInstance(anObject);
2370 anObject->initIsa(_objc_getFreedObjectClass ());
2376 static id _object_copy(id oldObj, size_t extraBytes)
2378 void *z = malloc_zone_from_ptr(oldObj);
2379 return _object_copyFromZone(oldObj, extraBytes,
2380 z ? z : malloc_default_zone());
2383 static id _object_reallocFromZone(id anObject, size_t nBytes, void *zone)
2388 if (anObject == nil)
2389 __objc_error(nil, "reallocating nil object");
2391 if (anObject->ISA() == _objc_getFreedObjectClass ())
2392 __objc_error(anObject, "reallocating freed object");
2394 if (nBytes < anObject->ISA()->alignedInstanceSize())
2395 __objc_error(anObject, "(%s, %zu) requested size too small",
2396 object_getClassName(anObject), nBytes);
2398 // fixme need C++ copy constructor
2400 // Make sure not to modify space that has been declared free
2401 tmp = anObject->ISA();
2402 anObject->initIsa(_objc_getFreedObjectClass ());
2403 newObject = (id)malloc_zone_realloc((malloc_zone_t *)zone, anObject, nBytes);
2405 newObject->initIsa(tmp);
2407 // realloc failed, anObject is still alive
2408 anObject->initIsa(tmp);
2414 static id _object_realloc(id anObject, size_t nBytes)
2416 void *z = malloc_zone_from_ptr(anObject);
2417 return _object_reallocFromZone(anObject,
2419 z ? z : malloc_default_zone());
2422 id (*_alloc)(Class, size_t) = _class_createInstance;
2423 id (*_copy)(id, size_t) = _object_copy;
2424 id (*_realloc)(id, size_t) = _object_realloc;
2425 id (*_dealloc)(id) = _object_dispose;
2426 id (*_zoneAlloc)(Class, size_t, void *) = _class_createInstanceFromZone;
2427 id (*_zoneCopy)(id, size_t, void *) = _object_copyFromZone;
2428 id (*_zoneRealloc)(id, size_t, void *) = _object_reallocFromZone;
2429 void (*_error)(id, const char *, va_list) = _objc_error;
2432 id class_createInstance(Class cls, size_t extraBytes)
2434 return (*_alloc)(cls, extraBytes);
2437 id class_createInstanceFromZone(Class cls, size_t extraBytes, void *z)
2439 OBJC_WARN_DEPRECATED;
2440 return (*_zoneAlloc)(cls, extraBytes, z);
2443 unsigned class_createInstances(Class cls, size_t extraBytes,
2444 id *results, unsigned num_requested)
2446 if (_alloc == &_class_createInstance) {
2447 return _class_createInstancesFromZone(cls, extraBytes, nil,
2448 results, num_requested);
2450 // _alloc in use, which isn't understood by the batch allocator
2455 id object_copy(id obj, size_t extraBytes)
2457 return (*_copy)(obj, extraBytes);
2460 id object_copyFromZone(id obj, size_t extraBytes, void *z)
2462 OBJC_WARN_DEPRECATED;
2463 return (*_zoneCopy)(obj, extraBytes, z);
2466 id object_dispose(id obj)
2468 return (*_dealloc)(obj);
2471 id object_realloc(id obj, size_t nBytes)
2473 OBJC_WARN_DEPRECATED;
2474 return (*_realloc)(obj, nBytes);
2477 id object_reallocFromZone(id obj, size_t nBytes, void *z)
2479 OBJC_WARN_DEPRECATED;
2480 return (*_zoneRealloc)(obj, nBytes, z);
2484 /***********************************************************************
2485 * object_getIndexedIvars.
2486 **********************************************************************/
2487 void *object_getIndexedIvars(id obj)
2489 // ivars are tacked onto the end of the object
2490 if (!obj) return nil;
2491 if (obj->isTaggedPointer()) return nil;
2492 return ((char *) obj) + obj->ISA()->alignedInstanceSize();
2497 Class class_setSuperclass(Class cls, Class newSuper)
2499 Class oldSuper = cls->superclass;
2500 set_superclass(cls, newSuper, NO);
2501 flush_caches(cls, YES);