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 Class _class_getNonMetaClass(Class cls, id obj);
40 static void flush_caches(Class cls, bool flush_meta);
43 // Freed objects have their isa set to point to this dummy class.
44 // This avoids the need to check for Nil classes in the messenger.
45 static const void* freedObjectClass[12] =
55 (Cache) &_objc_empty_cache, // cache
62 /***********************************************************************
63 * _class_getFreedObjectClass. Return a pointer to the dummy freed
64 * object class. Freed objects get their isa pointers replaced with
65 * a pointer to the freedObjectClass, so that we can catch usages of
67 **********************************************************************/
68 static Class _class_getFreedObjectClass(void)
70 return (Class)freedObjectClass;
74 /***********************************************************************
75 * _objc_getFreedObjectClass. Return a pointer to the dummy freed
76 * object class. Freed objects get their isa pointers replaced with
77 * a pointer to the freedObjectClass, so that we can catch usages of
79 **********************************************************************/
80 Class _objc_getFreedObjectClass(void)
82 return _class_getFreedObjectClass();
86 static void allocateExt(Class cls)
88 if (! (cls->info & CLS_EXT)) {
89 _objc_inform("class '%s' needs to be recompiled", cls->name);
93 uint32_t size = (uint32_t)sizeof(old_class_ext);
94 cls->ext = (old_class_ext *)calloc(size, 1);
95 cls->ext->size = size;
100 static inline old_method *_findNamedMethodInList(old_method_list * mlist, const char *meth_name) {
102 if (!mlist) return nil;
103 for (i = 0; i < mlist->method_count; i++) {
104 old_method *m = &mlist->method_list[i];
105 if (0 == strcmp((const char *)(m->method_name), meth_name)) {
113 /***********************************************************************
114 * Method list fixup markers.
115 * mlist->obsolete == fixed_up_method_list marks method lists with real SELs
116 * versus method lists with un-uniqued char*.
117 * PREOPTIMIZED VERSION:
118 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP
119 * dyld shared cache sets this for method lists it preoptimizes.
120 * UN-PREOPTIMIZED VERSION
121 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP_outside_dyld
122 * dyld shared cache uses OBJC_FIXED_UP, but those aren't trusted.
123 **********************************************************************/
124 #define OBJC_FIXED_UP ((void *)1771)
125 #define OBJC_FIXED_UP_outside_dyld ((void *)1773)
126 static void *fixed_up_method_list = OBJC_FIXED_UP;
128 // sel_init() decided that selectors in the dyld shared cache are untrustworthy
129 void disableSharedCacheOptimizations(void)
131 fixed_up_method_list = OBJC_FIXED_UP_outside_dyld;
134 /***********************************************************************
135 * fixupSelectorsInMethodList
136 * Uniques selectors in the given method list.
137 * The given method list must be non-nil and not already fixed-up.
138 * If the class was loaded from a bundle:
139 * fixes up the given list in place with heap-allocated selector strings
140 * If the class was not from a bundle:
141 * allocates a copy of the method list, fixes up the copy, and returns
142 * the copy. The given list is unmodified.
144 * If cls is already in use, methodListLock must be held by the caller.
145 **********************************************************************/
146 static old_method_list *fixupSelectorsInMethodList(Class cls, old_method_list *mlist)
151 old_method_list *old_mlist;
153 if ( ! mlist ) return nil;
154 if ( mlist->obsolete == fixed_up_method_list ) {
157 bool isBundle = cls->info & CLS_FROM_BUNDLE;
160 size = sizeof(old_method_list) - sizeof(old_method) + old_mlist->method_count * sizeof(old_method);
161 mlist = (old_method_list *)malloc(size);
162 memmove(mlist, old_mlist, size);
164 // Mach-O bundles are fixed up in place.
165 // This prevents leaks when a bundle is unloaded.
167 mutex_locker_t lock(selLock);
168 for ( i = 0; i < mlist->method_count; i += 1 ) {
169 method = &mlist->method_list[i];
170 method->method_name =
171 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 /***********************************************************************
329 * _class_resolveClassMethod
330 * Call +resolveClassMethod, looking for a method to be added to class cls.
331 * cls should be a metaclass.
332 * Does not check if the method already exists.
333 **********************************************************************/
334 static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
336 assert(cls->isMetaClass());
338 if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
339 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
341 // Resolver not implemented.
345 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
346 bool resolved = msg(_class_getNonMetaClass(cls, inst),
347 SEL_resolveClassMethod, sel);
349 // Cache the result (good or bad) so the resolver doesn't fire next time.
350 // +resolveClassMethod adds to self->ISA() a.k.a. cls
351 IMP imp = lookUpImpOrNil(cls, sel, inst,
352 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
354 if (resolved && PrintResolving) {
356 _objc_inform("RESOLVE: method %c[%s %s] "
357 "dynamically resolved to %p",
358 cls->isMetaClass() ? '+' : '-',
359 cls->nameForLogging(), sel_getName(sel), imp);
362 // Method resolver didn't add anything?
363 _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
364 ", but no new implementation of %c[%s %s] was found",
365 cls->nameForLogging(), sel_getName(sel),
366 cls->isMetaClass() ? '+' : '-',
367 cls->nameForLogging(), sel_getName(sel));
373 /***********************************************************************
374 * _class_resolveInstanceMethod
375 * Call +resolveInstanceMethod, looking for a method to be added to class cls.
376 * cls may be a metaclass or a non-meta class.
377 * Does not check if the method already exists.
378 **********************************************************************/
379 static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
381 if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
382 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
384 // Resolver not implemented.
388 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
389 bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
391 // Cache the result (good or bad) so the resolver doesn't fire next time.
392 // +resolveInstanceMethod adds to self a.k.a. cls
393 IMP imp = lookUpImpOrNil(cls, sel, inst,
394 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
396 if (resolved && PrintResolving) {
398 _objc_inform("RESOLVE: method %c[%s %s] "
399 "dynamically resolved to %p",
400 cls->isMetaClass() ? '+' : '-',
401 cls->nameForLogging(), sel_getName(sel), imp);
404 // Method resolver didn't add anything?
405 _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
406 ", but no new implementation of %c[%s %s] was found",
407 cls->nameForLogging(), sel_getName(sel),
408 cls->isMetaClass() ? '+' : '-',
409 cls->nameForLogging(), sel_getName(sel));
415 /***********************************************************************
416 * _class_resolveMethod
417 * Call +resolveClassMethod or +resolveInstanceMethod.
418 * Returns nothing; any result would be potentially out-of-date already.
419 * Does not check if the method already exists.
420 **********************************************************************/
421 void _class_resolveMethod(Class cls, SEL sel, id inst)
423 if (! cls->isMetaClass()) {
424 // try [cls resolveInstanceMethod:sel]
425 _class_resolveInstanceMethod(cls, sel, inst);
428 // try [nonMetaClass resolveClassMethod:sel]
429 // and [cls resolveInstanceMethod:sel]
430 _class_resolveClassMethod(cls, sel, inst);
431 if (!lookUpImpOrNil(cls, sel, inst,
432 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
434 _class_resolveInstanceMethod(cls, sel, inst);
440 /***********************************************************************
442 * Log this method call. If the logger permits it, fill the method cache.
443 * cls is the method whose cache should be filled.
444 * implementer is the class that owns the implementation in question.
445 **********************************************************************/
447 log_and_fill_cache(Class cls, Class implementer, Method meth, SEL sel)
449 #if SUPPORT_MESSAGE_LOGGING
450 if (objcMsgLogEnabled) {
451 bool cacheIt = logMessageSend(implementer->isMetaClass(),
452 cls->nameForLogging(),
453 implementer->nameForLogging(),
455 if (!cacheIt) return;
458 _cache_fill (cls, meth, sel);
462 /***********************************************************************
463 * _class_lookupMethodAndLoadCache.
464 * Method lookup for dispatchers ONLY. OTHER CODE SHOULD USE lookUpImp().
465 * This lookup avoids optimistic cache scan because the dispatcher
466 * already tried that.
467 **********************************************************************/
468 IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
470 return lookUpImpOrForward(cls, sel, obj,
471 YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
475 /***********************************************************************
476 * lookUpImpOrForward.
477 * The standard IMP lookup.
478 * initialize==NO tries to avoid +initialize (but sometimes fails)
479 * cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
480 * Most callers should use initialize==YES and cache==YES.
481 * inst is an instance of cls or a subclass thereof, or nil if none is known.
482 * If cls is an un-initialized metaclass then a non-nil inst is faster.
483 * May return _objc_msgForward_impcache. IMPs destined for external use
484 * must be converted to _objc_msgForward or _objc_msgForward_stret.
485 * If you don't want forwarding at all, use lookUpImpOrNil() instead.
486 **********************************************************************/
487 IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
488 bool initialize, bool cache, bool resolver)
493 bool triedResolver = NO;
495 methodListLock.assertUnlocked();
497 // Optimistic cache lookup
499 methodPC = _cache_getImp(cls, sel);
500 if (methodPC) return methodPC;
503 // Check for freed class
504 if (cls == _class_getFreedObjectClass())
505 return (IMP) _freedHandler;
507 // Check for +initialize
508 if (initialize && !cls->isInitialized()) {
509 initializeNonMetaClass (_class_getNonMetaClass(cls, inst));
510 // If sel == initialize, initializeNonMetaClass will send +initialize
511 // and then the messenger will send +initialize again after this
512 // procedure finishes. Of course, if this is not being called
513 // from the messenger then it won't happen. 2778172
516 // The lock is held to make method-lookup + cache-fill atomic
517 // with respect to method addition. Otherwise, a category could
518 // be added but ignored indefinitely because the cache was re-filled
519 // with the old value after the cache flush on behalf of the category.
521 methodListLock.lock();
523 // Try this class's cache.
525 methodPC = _cache_getImp(cls, sel);
526 if (methodPC) goto done;
528 // Try this class's method lists.
530 meth = _class_getMethodNoSuper_nolock(cls, sel);
532 log_and_fill_cache(cls, cls, meth, sel);
533 methodPC = method_getImplementation(meth);
537 // Try superclass caches and method lists.
540 while ((curClass = curClass->superclass)) {
542 meth = _cache_getMethod(curClass, sel, _objc_msgForward_impcache);
544 if (meth != (Method)1) {
545 // Found the method in a superclass. Cache it in this class.
546 log_and_fill_cache(cls, curClass, meth, sel);
547 methodPC = method_getImplementation(meth);
551 // Found a forward:: entry in a superclass.
552 // Stop searching, but don't cache yet; call method
553 // resolver for this class first.
558 // Superclass method list.
559 meth = _class_getMethodNoSuper_nolock(curClass, sel);
561 log_and_fill_cache(cls, curClass, meth, sel);
562 methodPC = method_getImplementation(meth);
567 // No implementation found. Try method resolver once.
569 if (resolver && !triedResolver) {
570 methodListLock.unlock();
571 _class_resolveMethod(cls, sel, inst);
576 // No implementation found, and method resolver didn't help.
579 _cache_addForwardEntry(cls, sel);
580 methodPC = _objc_msgForward_impcache;
583 methodListLock.unlock();
589 /***********************************************************************
591 * Like lookUpImpOrForward, but returns nil instead of _objc_msgForward_impcache
592 **********************************************************************/
593 IMP lookUpImpOrNil(Class cls, SEL sel, id inst,
594 bool initialize, bool cache, bool resolver)
596 IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
597 if (imp == _objc_msgForward_impcache) return nil;
602 /***********************************************************************
603 * lookupMethodInClassAndLoadCache.
604 * Like _class_lookupMethodAndLoadCache, but does not search superclasses.
605 * Caches and returns objc_msgForward if the method is not found in the class.
606 **********************************************************************/
607 IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel)
612 // fixme this still has the method list vs method cache race
613 // because it doesn't hold a lock across lookup+cache_fill,
614 // but it's only used for .cxx_construct/destruct and we assume
615 // categories don't change them.
617 // Search cache first.
618 imp = _cache_getImp(cls, sel);
621 // Cache miss. Search method list.
623 meth = _class_getMethodNoSuper(cls, sel);
626 // Hit in method list. Cache it.
627 _cache_fill(cls, meth, sel);
628 return method_getImplementation(meth);
630 // Miss in method list. Cache objc_msgForward.
631 _cache_addForwardEntry(cls, sel);
632 return _objc_msgForward_impcache;
637 /***********************************************************************
638 * _class_getClassForIvar
639 * Given a class and an ivar that is in it or one of its superclasses,
640 * find the actual class that defined the ivar.
641 **********************************************************************/
642 Class _class_getClassForIvar(Class cls, Ivar ivar)
644 for ( ; cls; cls = cls->superclass) {
645 if (auto ivars = cls->ivars) {
646 if (ivar >= &ivars->ivar_list[0] &&
647 ivar < &ivars->ivar_list[ivars->ivar_count])
658 /***********************************************************************
659 * class_getVariable. Return the named instance variable.
660 **********************************************************************/
662 Ivar _class_getVariable(Class cls, const char *name)
664 for (; cls != Nil; cls = cls->superclass) {
667 // Skip class having no ivars
668 if (!cls->ivars) continue;
670 for (i = 0; i < cls->ivars->ivar_count; i++) {
671 // Check this ivar's name. Be careful because the
672 // compiler generates ivar entries with nil ivar_name
673 // (e.g. for anonymous bit fields).
674 old_ivar *ivar = &cls->ivars->ivar_list[i];
675 if (ivar->ivar_name && 0 == strcmp(name, ivar->ivar_name)) {
687 property_list_nth(const old_property_list *plist, uint32_t i)
689 return (old_property *)(i*plist->entsize + (char *)&plist->first);
693 copyPropertyList(old_property_list *plist, unsigned int *outCount)
695 old_property **result = nil;
696 unsigned int count = 0;
699 count = plist->count;
704 result = (old_property **)malloc((count+1) * sizeof(old_property *));
706 for (i = 0; i < count; i++) {
707 result[i] = property_list_nth(plist, i);
712 if (outCount) *outCount = count;
717 static old_property_list *
718 nextPropertyList(Class cls, uintptr_t *indexp)
720 old_property_list *result = nil;
722 classLock.assertLocked();
723 if (! ((cls->info & CLS_EXT) && cls->ext)) {
726 } else if (!cls->ext->propertyLists) {
729 } else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
730 // Only one property list
732 result = (old_property_list *)cls->ext->propertyLists;
737 // More than one property list
738 result = cls->ext->propertyLists[*indexp];
751 /***********************************************************************
752 * class_getIvarLayout
753 * nil means all-scanned. "" means non-scanned.
754 **********************************************************************/
756 class_getIvarLayout(Class cls)
758 if (cls && (cls->info & CLS_EXT)) {
759 return cls->ivar_layout;
761 return nil; // conservative scan
766 /***********************************************************************
767 * class_getWeakIvarLayout
768 * nil means no weak ivars.
769 **********************************************************************/
771 class_getWeakIvarLayout(Class cls)
773 if (cls && (cls->info & CLS_EXT) && cls->ext) {
774 return cls->ext->weak_ivar_layout;
776 return nil; // no weak ivars
781 /***********************************************************************
782 * class_setIvarLayout
783 * nil means all-scanned. "" means non-scanned.
784 **********************************************************************/
785 void class_setIvarLayout(Class cls, const uint8_t *layout)
789 if (! (cls->info & CLS_EXT)) {
790 _objc_inform("class '%s' needs to be recompiled", cls->name);
795 cls->ivar_layout = ustrdupMaybeNil(layout);
799 /***********************************************************************
800 * class_setWeakIvarLayout
801 * nil means no weak ivars.
802 **********************************************************************/
803 void class_setWeakIvarLayout(Class cls, const uint8_t *layout)
807 mutex_locker_t lock(classLock);
812 cls->ext->weak_ivar_layout = ustrdupMaybeNil(layout);
816 /***********************************************************************
817 * class_setVersion. Record the specified version with the class.
818 **********************************************************************/
819 void class_setVersion(Class cls, int version)
822 cls->version = version;
825 /***********************************************************************
826 * class_getVersion. Return the version recorded with the class.
827 **********************************************************************/
828 int class_getVersion(Class cls)
831 return (int)cls->version;
835 /***********************************************************************
837 **********************************************************************/
838 const char *class_getName(Class cls)
840 if (!cls) return "nil";
841 else return cls->demangledName();
845 /***********************************************************************
846 * _class_getNonMetaClass.
847 * Return the ordinary class for this class or metaclass.
848 * Used by +initialize.
849 **********************************************************************/
850 static Class _class_getNonMetaClass(Class cls, id obj)
853 if (cls->isMetaClass()) {
854 if (cls->info & CLS_CONSTRUCTING) {
855 // Class is under construction and isn't in the class_hash,
856 // so objc_getClass doesn't work.
857 cls = obj; // fixme this may be nil in some paths
859 else if (strncmp(cls->name, "_%", 2) == 0) {
860 // Posee's meta's name is smashed and isn't in the class_hash,
861 // so objc_getClass doesn't work.
862 const char *baseName = strchr(cls->name, '%'); // get posee's real name
863 cls = objc_getClass(baseName);
866 cls = objc_getClass(cls->name);
875 Class class_initialize(Class cls, id inst) {
876 if (!cls->isInitialized()) {
877 initializeNonMetaClass (_class_getNonMetaClass(cls, inst));
883 Cache _class_getCache(Class cls)
888 void _class_setCache(Class cls, Cache cache)
893 const char *_category_getName(Category cat)
895 return oldcategory(cat)->category_name;
898 const char *_category_getClassName(Category cat)
900 return oldcategory(cat)->class_name;
903 Class _category_getClass(Category cat)
905 return objc_getClass(oldcategory(cat)->class_name);
908 IMP _category_getLoadMethod(Category cat)
910 old_method_list *mlist = oldcategory(cat)->class_methods;
912 return lookupNamedMethodInMethodList(mlist, "load");
920 /***********************************************************************
921 * class_nextMethodList.
922 * External version of nextMethodList().
924 * This function is not fully thread-safe. A series of calls to
925 * class_nextMethodList() may fail if methods are added to or removed
926 * from the class between calls.
927 * If methods are added between calls to class_nextMethodList(), it may
928 * return previously-returned method lists again, and may fail to return
930 * If methods are removed between calls to class_nextMethodList(), it may
931 * omit surviving method lists or simply crash.
932 **********************************************************************/
933 struct objc_method_list *class_nextMethodList(Class cls, void **it)
935 OBJC_WARN_DEPRECATED;
937 mutex_locker_t lock(methodListLock);
938 return (struct objc_method_list *) nextMethodList(cls, it);
942 /***********************************************************************
945 * Formerly class_addInstanceMethods ()
946 **********************************************************************/
947 void class_addMethods(Class cls, struct objc_method_list *meths)
949 OBJC_WARN_DEPRECATED;
953 mutex_locker_t lock(methodListLock);
954 _objc_insertMethods(cls, (old_method_list *)meths, nil);
957 // Must flush when dynamically adding methods. No need to flush
958 // all the class method caches. If cls is a meta class, though,
959 // this will still flush it and any of its sub-meta classes.
960 flush_caches (cls, NO);
964 /***********************************************************************
965 * class_removeMethods.
966 **********************************************************************/
967 void class_removeMethods(Class cls, struct objc_method_list *meths)
969 OBJC_WARN_DEPRECATED;
971 // Remove the methods
973 mutex_locker_t lock(methodListLock);
974 _objc_removeMethods(cls, (old_method_list *)meths);
977 // Must flush when dynamically removing methods. No need to flush
978 // all the class method caches. If cls is a meta class, though,
979 // this will still flush it and any of its sub-meta classes.
980 flush_caches (cls, NO);
983 /***********************************************************************
984 * lookupNamedMethodInMethodList
985 * Only called to find +load/-.cxx_construct/-.cxx_destruct methods,
986 * without fixing up the entire method list.
987 * The class is not yet in use, so methodListLock is not taken.
988 **********************************************************************/
989 IMP lookupNamedMethodInMethodList(old_method_list *mlist, const char *meth_name)
992 m = meth_name ? _findNamedMethodInList(mlist, meth_name) : nil;
993 return (m ? m->method_imp : nil);
996 static Method _class_getMethod(Class cls, SEL sel)
998 mutex_locker_t lock(methodListLock);
999 return (Method)_getMethod(cls, sel);
1002 static Method _class_getMethodNoSuper(Class cls, SEL sel)
1004 mutex_locker_t lock(methodListLock);
1005 return (Method)_findMethodInClass(cls, sel);
1008 static Method _class_getMethodNoSuper_nolock(Class cls, SEL sel)
1010 methodListLock.assertLocked();
1011 return (Method)_findMethodInClass(cls, sel);
1015 /***********************************************************************
1016 * class_getInstanceMethod. Return the instance method for the
1017 * specified class and selector.
1018 **********************************************************************/
1019 Method class_getInstanceMethod(Class cls, SEL sel)
1021 if (!cls || !sel) return nil;
1023 // This deliberately avoids +initialize because it historically did so.
1025 // This implementation is a bit weird because it's the only place that
1026 // wants a Method instead of an IMP.
1029 meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache);
1030 if (meth == (Method)1) {
1031 // Cache contains forward:: . Stop searching.
1037 // Search method lists, try method resolver, etc.
1038 lookUpImpOrNil(cls, sel, nil,
1039 NO/*initialize*/, NO/*cache*/, YES/*resolver*/);
1041 meth = _cache_getMethod(cls, sel, _objc_msgForward_impcache);
1042 if (meth == (Method)1) {
1043 // Cache contains forward:: . Stop searching.
1049 return _class_getMethod(cls, sel);
1053 BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen)
1055 old_protocol *proto = oldprotocol(proto_gen);
1057 if (!cls) return NO;
1058 if (!proto) return NO;
1060 if (cls->ISA()->version >= 3) {
1061 old_protocol_list *list;
1062 for (list = cls->protocols; list != nil; list = list->next) {
1064 for (i = 0; i < list->count; i++) {
1065 if (list->list[i] == proto) return YES;
1066 if (protocol_conformsToProtocol((Protocol *)list->list[i], proto_gen)) return YES;
1068 if (cls->ISA()->version <= 4) break;
1075 static NXMapTable * posed_class_hash = nil;
1077 /***********************************************************************
1078 * objc_getOrigClass.
1079 **********************************************************************/
1081 Class _objc_getOrigClass(const char *name)
1083 // Look for class among the posers
1085 mutex_locker_t lock(classLock);
1086 if (posed_class_hash) {
1087 Class cls = (Class) NXMapGet (posed_class_hash, name);
1088 if (cls) return cls;
1092 // Not a poser. Do a normal lookup.
1093 Class cls = objc_getClass (name);
1094 if (cls) return cls;
1096 _objc_inform ("class `%s' not linked into application", name);
1100 Class objc_getOrigClass(const char *name)
1102 OBJC_WARN_DEPRECATED;
1103 return _objc_getOrigClass(name);
1106 /***********************************************************************
1107 * _objc_addOrigClass. This function is only used from class_poseAs.
1108 * Registers the original class names, before they get obscured by
1109 * posing, so that [super ..] will work correctly from categories
1110 * in posing classes and in categories in classes being posed for.
1111 **********************************************************************/
1112 static void _objc_addOrigClass (Class origClass)
1114 mutex_locker_t lock(classLock);
1116 // Create the poser's hash table on first use
1117 if (!posed_class_hash)
1119 posed_class_hash = NXCreateMapTable(NXStrValueMapPrototype, 8);
1122 // Add the named class iff it is not already there (or collides?)
1123 if (NXMapGet (posed_class_hash, origClass->name) == 0)
1124 NXMapInsert (posed_class_hash, origClass->name, origClass);
1128 /***********************************************************************
1129 * change_class_references
1130 * Change classrefs and superclass pointers from original to imposter
1131 * But if copy!=nil, don't change copy->superclass.
1132 * If changeSuperRefs==YES, also change [super message] classrefs.
1133 * Used by class_poseAs and objc_setFutureClass
1134 * classLock must be locked.
1135 **********************************************************************/
1136 void change_class_references(Class imposter,
1139 bool changeSuperRefs)
1145 // Change all subclasses of the original to point to the imposter.
1146 state = NXInitHashState (class_hash);
1147 while (NXNextHashState (class_hash, &state, (void **) &clsObject))
1149 while ((clsObject) && (clsObject != imposter) &&
1150 (clsObject != copy))
1152 if (clsObject->superclass == original)
1154 clsObject->superclass = imposter;
1155 clsObject->ISA()->superclass = imposter->ISA();
1156 // We must flush caches here!
1160 clsObject = clsObject->superclass;
1164 // Replace the original with the imposter in all class refs
1165 // Major loop - process all headers
1166 for (hInfo = FirstHeader; hInfo != nil; hInfo = hInfo->getNext())
1172 // Fix class refs associated with this header
1173 cls_refs = _getObjcClassRefs(hInfo, &refCount);
1175 for (index = 0; index < refCount; index += 1) {
1176 if (cls_refs[index] == original) {
1177 cls_refs[index] = imposter;
1185 /***********************************************************************
1188 * !!! class_poseAs () does not currently flush any caches.
1189 **********************************************************************/
1190 Class class_poseAs(Class imposter, Class original)
1192 char * imposterNamePtr;
1195 OBJC_WARN_DEPRECATED;
1197 // Trivial case is easy
1198 if (imposter == original)
1201 // Imposter must be an immediate subclass of the original
1202 if (imposter->superclass != original) {
1203 __objc_error(imposter,
1204 "[%s poseAs:%s]: target not immediate superclass",
1205 imposter->name, original->name);
1208 // Can't pose when you have instance variables (how could it work?)
1209 if (imposter->ivars) {
1210 __objc_error(imposter,
1211 "[%s poseAs:%s]: %s defines new instance variables",
1212 imposter->name, original->name, imposter->name);
1215 // Build a string to use to replace the name of the original class.
1217 # define imposterNamePrefix "_%"
1218 imposterNamePtr = malloc(strlen(original->name) + strlen(imposterNamePrefix) + 1);
1219 strcpy(imposterNamePtr, imposterNamePrefix);
1220 strcat(imposterNamePtr, original->name);
1221 # undef imposterNamePrefix
1223 asprintf(&imposterNamePtr, "_%%%s", original->name);
1226 // We lock the class hashtable, so we are thread safe with respect to
1227 // calls to objc_getClass (). However, the class names are not
1228 // changed atomically, nor are all of the subclasses updated
1229 // atomically. I have ordered the operations so that you will
1230 // never crash, but you may get inconsistent results....
1232 // Register the original class so that [super ..] knows
1233 // exactly which classes are the "original" classes.
1234 _objc_addOrigClass (original);
1235 _objc_addOrigClass (imposter);
1237 // Copy the imposter, so that the imposter can continue
1238 // its normal life in addition to changing the behavior of
1239 // the original. As a hack we don't bother to copy the metaclass.
1240 // For some reason we modify the original rather than the copy.
1241 copy = (Class)malloc(sizeof(objc_class));
1242 memmove(copy, imposter, sizeof(objc_class));
1244 mutex_locker_t lock(classLock);
1246 // Remove both the imposter and the original class.
1247 NXHashRemove (class_hash, imposter);
1248 NXHashRemove (class_hash, original);
1250 NXHashInsert (class_hash, copy);
1252 // Mark the imposter as such
1253 imposter->setInfo(CLS_POSING);
1254 imposter->ISA()->setInfo(CLS_POSING);
1256 // Change the name of the imposter to that of the original class.
1257 imposter->name = original->name;
1258 imposter->ISA()->name = original->ISA()->name;
1260 // Also copy the version field to avoid archiving problems.
1261 imposter->version = original->version;
1263 // Change classrefs and superclass pointers
1264 // Don't change copy->superclass
1265 // Don't change [super ...] messages
1266 change_class_references(imposter, original, copy, NO);
1268 // Change the name of the original class.
1269 original->name = imposterNamePtr + 1;
1270 original->ISA()->name = imposterNamePtr;
1272 // Restore the imposter and the original class with their new names.
1273 NXHashInsert (class_hash, imposter);
1274 NXHashInsert (class_hash, original);
1280 /***********************************************************************
1281 * _objc_flush_caches. Flush the instance and class method caches
1282 * of cls and all its subclasses.
1284 * Specifying Nil for the class "all classes."
1285 **********************************************************************/
1286 static void flush_caches(Class target, bool flush_meta)
1288 bool collectALot = (target == nil);
1291 #ifdef OBJC_INSTRUMENTED
1292 unsigned int classesVisited;
1293 unsigned int subclassCount;
1296 mutex_locker_t lock(classLock);
1297 mutex_locker_t lock2(cacheUpdateLock);
1299 // Leaf classes are fastest because there are no subclass caches to flush.
1301 if (target && (target->info & CLS_LEAF)) {
1302 _cache_flush (target);
1304 if (target->ISA() && (target->ISA()->info & CLS_LEAF)) {
1305 _cache_flush (target->ISA());
1308 // Reset target and handle it by one of the methods below.
1309 target = target->ISA();
1315 state = NXInitHashState(class_hash);
1317 // Handle nil and root instance class specially: flush all
1318 // instance and class method caches. Nice that this
1319 // loop is linear vs the N-squared loop just below.
1320 if (!target || !target->superclass)
1322 #ifdef OBJC_INSTRUMENTED
1323 LinearFlushCachesCount += 1;
1327 // Traverse all classes in the hash table
1328 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1330 Class metaClsObject;
1331 #ifdef OBJC_INSTRUMENTED
1332 classesVisited += 1;
1335 // Skip class that is known not to be a subclass of this root
1336 // (the isa pointer of any meta class points to the meta class
1338 // NOTE: When is an isa pointer of a hash tabled class ever nil?
1339 metaClsObject = clsObject->ISA();
1340 if (target && metaClsObject && target->ISA() != metaClsObject->ISA()) {
1344 #ifdef OBJC_INSTRUMENTED
1348 _cache_flush (clsObject);
1349 if (flush_meta && metaClsObject != nil) {
1350 _cache_flush (metaClsObject);
1353 #ifdef OBJC_INSTRUMENTED
1354 LinearFlushCachesVisitedCount += classesVisited;
1355 if (classesVisited > MaxLinearFlushCachesVisitedCount)
1356 MaxLinearFlushCachesVisitedCount = classesVisited;
1357 IdealFlushCachesCount += subclassCount;
1358 if (subclassCount > MaxIdealFlushCachesCount)
1359 MaxIdealFlushCachesCount = subclassCount;
1365 // Outer loop - flush any cache that could now get a method from
1366 // cls (i.e. the cache associated with cls and any of its subclasses).
1367 #ifdef OBJC_INSTRUMENTED
1368 NonlinearFlushCachesCount += 1;
1372 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1376 #ifdef OBJC_INSTRUMENTED
1377 NonlinearFlushCachesClassCount += 1;
1380 // Inner loop - Process a given class
1381 clsIter = clsObject;
1385 #ifdef OBJC_INSTRUMENTED
1386 classesVisited += 1;
1388 // Flush clsObject instance method cache if
1389 // clsObject is a subclass of cls, or is cls itself
1390 // Flush the class method cache if that was asked for
1391 if (clsIter == target)
1393 #ifdef OBJC_INSTRUMENTED
1396 _cache_flush (clsObject);
1398 _cache_flush (clsObject->ISA());
1404 // Flush clsObject class method cache if cls is
1405 // the meta class of clsObject or of one
1406 // of clsObject's superclasses
1407 else if (clsIter->ISA() == target)
1409 #ifdef OBJC_INSTRUMENTED
1412 _cache_flush (clsObject->ISA());
1416 // Move up superclass chain
1417 // else if (clsIter->isInitialized())
1418 clsIter = clsIter->superclass;
1420 // clsIter is not initialized, so its cache
1421 // must be empty. This happens only when
1422 // clsIter == clsObject, because
1423 // superclasses are initialized before
1424 // subclasses, and this loop traverses
1425 // from sub- to super- classes.
1430 #ifdef OBJC_INSTRUMENTED
1431 NonlinearFlushCachesVisitedCount += classesVisited;
1432 if (classesVisited > MaxNonlinearFlushCachesVisitedCount)
1433 MaxNonlinearFlushCachesVisitedCount = classesVisited;
1434 IdealFlushCachesCount += subclassCount;
1435 if (subclassCount > MaxIdealFlushCachesCount)
1436 MaxIdealFlushCachesCount = subclassCount;
1442 _cache_collect(true);
1447 void _objc_flush_caches(Class target)
1449 flush_caches(target, YES);
1454 /***********************************************************************
1455 * flush_marked_caches. Flush the method cache of any class marked
1456 * CLS_FLUSH_CACHE (and all subclasses thereof)
1458 **********************************************************************/
1459 void flush_marked_caches(void)
1465 mutex_locker_t lock(classLock);
1466 mutex_locker_t lock2(cacheUpdateLock);
1468 state = NXInitHashState(class_hash);
1469 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1470 for (supercls = cls; supercls; supercls = supercls->superclass) {
1471 if (supercls->info & CLS_FLUSH_CACHE) {
1477 for (supercls = cls->ISA(); supercls; supercls = supercls->superclass) {
1478 if (supercls->info & CLS_FLUSH_CACHE) {
1479 _cache_flush(cls->ISA());
1485 state = NXInitHashState(class_hash);
1486 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1487 if (cls->info & CLS_FLUSH_CACHE) {
1488 cls->clearInfo(CLS_FLUSH_CACHE);
1490 if (cls->ISA()->info & CLS_FLUSH_CACHE) {
1491 cls->ISA()->clearInfo(CLS_FLUSH_CACHE);
1497 /***********************************************************************
1498 * get_base_method_list
1499 * Returns the method list containing the class's own methods,
1500 * ignoring any method lists added by categories or class_addMethods.
1501 * Called only by add_class_to_loadable_list.
1502 * Does not hold methodListLock because add_class_to_loadable_list
1503 * does not manipulate in-use classes.
1504 **********************************************************************/
1505 static old_method_list *get_base_method_list(Class cls)
1507 old_method_list **ptr;
1509 if (!cls->methodLists) return nil;
1510 if (cls->info & CLS_NO_METHOD_ARRAY) return (old_method_list *)cls->methodLists;
1511 ptr = cls->methodLists;
1512 if (!*ptr || *ptr == END_OF_METHODS_LIST) return nil;
1513 while ( *ptr != 0 && *ptr != END_OF_METHODS_LIST ) { ptr++; }
1519 static IMP _class_getLoadMethod_nocheck(Class cls)
1521 old_method_list *mlist;
1522 mlist = get_base_method_list(cls->ISA());
1524 return lookupNamedMethodInMethodList (mlist, "load");
1530 bool _class_hasLoadMethod(Class cls)
1532 if (cls->ISA()->info & CLS_HAS_LOAD_METHOD) return YES;
1533 return _class_getLoadMethod_nocheck(cls);
1537 /***********************************************************************
1538 * objc_class::getLoadMethod
1539 * Returns cls's +load implementation, or nil if it doesn't have one.
1540 **********************************************************************/
1541 IMP objc_class::getLoadMethod()
1543 if (ISA()->info & CLS_HAS_LOAD_METHOD) {
1544 return _class_getLoadMethod_nocheck((Class)this);
1549 ptrdiff_t ivar_getOffset(Ivar ivar)
1551 return oldivar(ivar)->ivar_offset;
1554 const char *ivar_getName(Ivar ivar)
1556 return oldivar(ivar)->ivar_name;
1559 const char *ivar_getTypeEncoding(Ivar ivar)
1561 return oldivar(ivar)->ivar_type;
1565 IMP method_getImplementation(Method m)
1568 return oldmethod(m)->method_imp;
1571 SEL method_getName(Method m)
1574 return oldmethod(m)->method_name;
1577 const char *method_getTypeEncoding(Method m)
1580 return oldmethod(m)->method_types;
1583 unsigned int method_getSizeOfArguments(Method m)
1585 OBJC_WARN_DEPRECATED;
1587 return encoding_getSizeOfArguments(method_getTypeEncoding(m));
1590 // This function was accidentally un-exported beginning in macOS 10.9.
1591 // As of macOS 10.13 nobody had complained.
1593 unsigned int method_getArgumentInfo(Method m, int arg,
1594 const char **type, int *offset)
1596 OBJC_WARN_DEPRECATED;
1598 return encoding_getArgumentInfo(method_getTypeEncoding(m),
1606 IMP method_setImplementation(Method m_gen, IMP imp)
1609 old_method *m = oldmethod(m_gen);
1611 if (!imp) return nil;
1614 old = m->method_imp;
1615 m->method_imp = imp;
1621 void method_exchangeImplementations(Method m1_gen, Method m2_gen)
1624 old_method *m1 = oldmethod(m1_gen);
1625 old_method *m2 = oldmethod(m2_gen);
1626 if (!m1 || !m2) return;
1629 m1_imp = m1->method_imp;
1630 m1->method_imp = m2->method_imp;
1631 m2->method_imp = m1_imp;
1636 struct objc_method_description * method_getDescription(Method m)
1639 return (struct objc_method_description *)oldmethod(m);
1643 const char *property_getName(objc_property_t prop)
1645 return oldproperty(prop)->name;
1648 const char *property_getAttributes(objc_property_t prop)
1650 return oldproperty(prop)->attributes;
1653 objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
1654 unsigned int *outCount)
1657 if (outCount) *outCount = 0;
1661 mutex_locker_t lock(classLock);
1662 return copyPropertyAttributeList(oldproperty(prop)->attributes,outCount);
1665 char * property_copyAttributeValue(objc_property_t prop, const char *name)
1667 if (!prop || !name || *name == '\0') return nil;
1669 mutex_locker_t lock(classLock);
1670 return copyPropertyAttributeValue(oldproperty(prop)->attributes, name);
1674 /***********************************************************************
1676 **********************************************************************/
1677 static IMP _class_addMethod(Class cls, SEL name, IMP imp,
1678 const char *types, bool replace)
1683 if (!types) types = "";
1685 mutex_locker_t lock(methodListLock);
1687 if ((m = _findMethodInClass(cls, name))) {
1690 result = method_getImplementation((Method)m);
1692 method_setImplementation((Method)m, imp);
1695 // fixme could be faster
1696 old_method_list *mlist =
1697 (old_method_list *)calloc(sizeof(old_method_list), 1);
1698 mlist->obsolete = fixed_up_method_list;
1699 mlist->method_count = 1;
1700 mlist->method_list[0].method_name = name;
1701 mlist->method_list[0].method_types = strdup(types);
1702 mlist->method_list[0].method_imp = imp;
1704 _objc_insertMethods(cls, mlist, nil);
1705 if (!(cls->info & CLS_CONSTRUCTING)) {
1706 flush_caches(cls, NO);
1708 // in-construction class has no subclasses
1718 /***********************************************************************
1720 **********************************************************************/
1721 BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
1724 if (!cls) return NO;
1726 old = _class_addMethod(cls, name, imp, types, NO);
1731 /***********************************************************************
1732 * class_replaceMethod
1733 **********************************************************************/
1734 IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
1736 if (!cls) return nil;
1738 return _class_addMethod(cls, name, imp, types, YES);
1742 /***********************************************************************
1744 **********************************************************************/
1745 BOOL class_addIvar(Class cls, const char *name, size_t size,
1746 uint8_t alignment, const char *type)
1750 if (!cls) return NO;
1751 if (ISMETA(cls)) return NO;
1752 if (!(cls->info & CLS_CONSTRUCTING)) return NO;
1754 if (!type) type = "";
1755 if (name && 0 == strcmp(name, "")) name = nil;
1757 mutex_locker_t lock(classLock);
1759 // Check for existing ivar with this name
1760 // fixme check superclasses?
1763 for (i = 0; i < cls->ivars->ivar_count; i++) {
1764 if (0 == strcmp(cls->ivars->ivar_list[i].ivar_name, name)) {
1772 old_ivar_list *old = cls->ivars;
1780 oldSize = sizeof(old_ivar_list) +
1781 (old->ivar_count - 1) * sizeof(old_ivar);
1782 newCount = 1 + old->ivar_count;
1784 oldSize = sizeof(old_ivar_list) - sizeof(old_ivar);
1788 // allocate new ivar list
1789 cls->ivars = (old_ivar_list *)
1790 calloc(oldSize+sizeof(old_ivar), 1);
1791 if (old) memcpy(cls->ivars, old, oldSize);
1792 if (old && malloc_size(old)) free(old);
1793 cls->ivars->ivar_count = newCount;
1794 ivar = &cls->ivars->ivar_list[newCount-1];
1796 // set ivar name and type
1797 ivar->ivar_name = strdup(name);
1798 ivar->ivar_type = strdup(type);
1800 // align if necessary
1801 alignBytes = 1 << alignment;
1802 misalign = cls->instance_size % alignBytes;
1803 if (misalign) cls->instance_size += (long)(alignBytes - misalign);
1805 // set ivar offset and increase instance size
1806 ivar->ivar_offset = (int)cls->instance_size;
1807 cls->instance_size += (long)size;
1814 /***********************************************************************
1816 **********************************************************************/
1817 BOOL class_addProtocol(Class cls, Protocol *protocol_gen)
1819 old_protocol *protocol = oldprotocol(protocol_gen);
1820 old_protocol_list *plist;
1822 if (!cls) return NO;
1823 if (class_conformsToProtocol(cls, protocol_gen)) return NO;
1825 mutex_locker_t lock(classLock);
1827 // fixme optimize - protocol list doesn't escape?
1828 plist = (old_protocol_list*)calloc(sizeof(old_protocol_list), 1);
1830 plist->list[0] = protocol;
1831 plist->next = cls->protocols;
1832 cls->protocols = plist;
1840 /***********************************************************************
1841 * _class_addProperties
1842 * Internal helper to add properties to a class.
1843 * Used by category attachment and class_addProperty()
1844 * Locking: acquires classLock
1845 **********************************************************************/
1847 _class_addProperties(Class cls,
1848 old_property_list *additions)
1850 old_property_list *newlist;
1852 if (!(cls->info & CLS_EXT)) return NO;
1854 newlist = (old_property_list *)
1855 memdup(additions, sizeof(*newlist) - sizeof(newlist->first)
1856 + (additions->entsize * additions->count));
1858 mutex_locker_t lock(classLock);
1861 if (!cls->ext->propertyLists) {
1862 // cls has no properties - simply use this list
1863 cls->ext->propertyLists = (old_property_list **)newlist;
1864 cls->setInfo(CLS_NO_PROPERTY_ARRAY);
1866 else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
1867 // cls has one property list - make a new array
1868 old_property_list **newarray = (old_property_list **)
1869 malloc(3 * sizeof(*newarray));
1870 newarray[0] = newlist;
1871 newarray[1] = (old_property_list *)cls->ext->propertyLists;
1873 cls->ext->propertyLists = newarray;
1874 cls->clearInfo(CLS_NO_PROPERTY_ARRAY);
1877 // cls has a property array - make a bigger one
1878 old_property_list **newarray;
1880 while (cls->ext->propertyLists[count]) count++;
1881 newarray = (old_property_list **)
1882 malloc((count+2) * sizeof(*newarray));
1883 newarray[0] = newlist;
1884 memcpy(&newarray[1], &cls->ext->propertyLists[0],
1885 count * sizeof(*newarray));
1886 newarray[count+1] = nil;
1887 free(cls->ext->propertyLists);
1888 cls->ext->propertyLists = newarray;
1895 /***********************************************************************
1897 * Adds a property to a class. Returns NO if the proeprty already exists.
1898 * Locking: acquires classLock
1899 **********************************************************************/
1901 _class_addProperty(Class cls, const char *name,
1902 const objc_property_attribute_t *attrs, unsigned int count,
1905 if (!cls) return NO;
1906 if (!name) return NO;
1908 old_property *prop = oldproperty(class_getProperty(cls, name));
1909 if (prop && !replace) {
1910 // already exists, refuse to replace
1915 mutex_locker_t lock(classLock);
1916 try_free(prop->attributes);
1917 prop->attributes = copyPropertyAttributeString(attrs, count);
1922 old_property_list proplist;
1923 proplist.entsize = sizeof(old_property);
1925 proplist.first.name = strdup(name);
1926 proplist.first.attributes = copyPropertyAttributeString(attrs, count);
1928 return _class_addProperties(cls, &proplist);
1933 class_addProperty(Class cls, const char *name,
1934 const objc_property_attribute_t *attrs, unsigned int n)
1936 return _class_addProperty(cls, name, attrs, n, NO);
1940 class_replaceProperty(Class cls, const char *name,
1941 const objc_property_attribute_t *attrs, unsigned int n)
1943 _class_addProperty(cls, name, attrs, n, YES);
1947 /***********************************************************************
1948 * class_copyProtocolList. Returns a heap block containing the
1949 * protocols implemented by the class, or nil if the class
1950 * implements no protocols. Caller must free the block.
1951 * Does not copy any superclass's protocols.
1952 **********************************************************************/
1953 Protocol * __unsafe_unretained *
1954 class_copyProtocolList(Class cls, unsigned int *outCount)
1956 old_protocol_list *plist;
1957 Protocol **result = nil;
1958 unsigned int count = 0;
1962 if (outCount) *outCount = 0;
1966 mutex_locker_t lock(classLock);
1968 for (plist = cls->protocols; plist != nil; plist = plist->next) {
1969 count += (int)plist->count;
1973 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
1975 for (p = 0, plist = cls->protocols;
1977 plist = plist->next)
1980 for (i = 0; i < plist->count; i++) {
1981 result[p++] = (Protocol *)plist->list[i];
1987 if (outCount) *outCount = count;
1992 /***********************************************************************
1993 * class_getProperty. Return the named property.
1994 **********************************************************************/
1995 objc_property_t class_getProperty(Class cls, const char *name)
1997 if (!cls || !name) return nil;
1999 mutex_locker_t lock(classLock);
2001 for (; cls; cls = cls->superclass) {
2002 uintptr_t iterator = 0;
2003 old_property_list *plist;
2004 while ((plist = nextPropertyList(cls, &iterator))) {
2006 for (i = 0; i < plist->count; i++) {
2007 old_property *p = property_list_nth(plist, i);
2008 if (0 == strcmp(name, p->name)) {
2009 return (objc_property_t)p;
2019 /***********************************************************************
2020 * class_copyPropertyList. Returns a heap block containing the
2021 * properties declared in the class, or nil if the class
2022 * declares no properties. Caller must free the block.
2023 * Does not copy any superclass's properties.
2024 **********************************************************************/
2025 objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
2027 old_property_list *plist;
2028 uintptr_t iterator = 0;
2029 old_property **result = nil;
2030 unsigned int count = 0;
2034 if (outCount) *outCount = 0;
2038 mutex_locker_t lock(classLock);
2041 while ((plist = nextPropertyList(cls, &iterator))) {
2042 count += plist->count;
2046 result = (old_property **)malloc((count+1) * sizeof(old_property *));
2050 while ((plist = nextPropertyList(cls, &iterator))) {
2051 for (i = 0; i < plist->count; i++) {
2052 result[p++] = property_list_nth(plist, i);
2058 if (outCount) *outCount = count;
2059 return (objc_property_t *)result;
2063 /***********************************************************************
2064 * class_copyMethodList. Returns a heap block containing the
2065 * methods implemented by the class, or nil if the class
2066 * implements no methods. Caller must free the block.
2067 * Does not copy any superclass's methods.
2068 **********************************************************************/
2069 Method *class_copyMethodList(Class cls, unsigned int *outCount)
2071 old_method_list *mlist;
2072 void *iterator = nil;
2073 Method *result = nil;
2074 unsigned int count = 0;
2078 if (outCount) *outCount = 0;
2082 mutex_locker_t lock(methodListLock);
2085 while ((mlist = nextMethodList(cls, &iterator))) {
2086 count += mlist->method_count;
2090 result = (Method *)malloc((count+1) * sizeof(Method));
2094 while ((mlist = nextMethodList(cls, &iterator))) {
2096 for (i = 0; i < mlist->method_count; i++) {
2097 result[m++] = (Method)&mlist->method_list[i];
2103 if (outCount) *outCount = count;
2108 /***********************************************************************
2109 * class_copyIvarList. Returns a heap block containing the
2110 * ivars declared in the class, or nil if the class
2111 * declares no ivars. Caller must free the block.
2112 * Does not copy any superclass's ivars.
2113 **********************************************************************/
2114 Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
2117 unsigned int count = 0;
2121 if (outCount) *outCount = 0;
2126 count = cls->ivars->ivar_count;
2130 result = (Ivar *)malloc((count+1) * sizeof(Ivar));
2132 for (i = 0; i < cls->ivars->ivar_count; i++) {
2133 result[i] = (Ivar)&cls->ivars->ivar_list[i];
2138 if (outCount) *outCount = count;
2143 /***********************************************************************
2144 * objc_allocateClass.
2145 **********************************************************************/
2147 void set_superclass(Class cls, Class supercls, bool cls_is_new)
2149 Class meta = cls->ISA();
2152 cls->superclass = supercls;
2153 meta->superclass = supercls->ISA();
2154 meta->initIsa(supercls->ISA()->ISA());
2156 // Propagate C++ cdtors from superclass.
2157 if (supercls->info & CLS_HAS_CXX_STRUCTORS) {
2158 if (cls_is_new) cls->info |= CLS_HAS_CXX_STRUCTORS;
2159 else cls->setInfo(CLS_HAS_CXX_STRUCTORS);
2162 // Superclass is no longer a leaf for cache flushing
2163 if (supercls->info & CLS_LEAF) {
2164 supercls->clearInfo(CLS_LEAF);
2165 supercls->ISA()->clearInfo(CLS_LEAF);
2168 cls->superclass = Nil; // superclass of root class is nil
2169 meta->superclass = cls; // superclass of root metaclass is root class
2170 meta->initIsa(meta); // metaclass of root metaclass is root metaclass
2172 // Root class is never a leaf for cache flushing, because the
2173 // root metaclass is a subclass. (This could be optimized, but
2174 // is too uncommon to bother.)
2175 cls->clearInfo(CLS_LEAF);
2176 meta->clearInfo(CLS_LEAF);
2180 // &UnsetLayout is the default ivar layout during class construction
2181 static const uint8_t UnsetLayout = 0;
2183 Class objc_initializeClassPair(Class supercls, const char *name, Class cls, Class meta)
2185 // Connect to superclasses and metaclasses
2187 set_superclass(cls, supercls, YES);
2190 cls->name = strdup(name);
2191 meta->name = strdup(name);
2194 cls->info = CLS_CLASS | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2195 meta->info = CLS_META | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2197 // Set instance size based on superclass.
2199 cls->instance_size = supercls->instance_size;
2200 meta->instance_size = supercls->ISA()->instance_size;
2202 cls->instance_size = sizeof(Class); // just an isa
2203 meta->instance_size = sizeof(objc_class);
2206 // No ivars. No methods. Empty cache. No protocols. No layout. Empty ext.
2208 cls->methodLists = nil;
2209 cls->cache = (Cache)&_objc_empty_cache;
2210 cls->protocols = nil;
2211 cls->ivar_layout = &UnsetLayout;
2214 cls->ext->weak_ivar_layout = &UnsetLayout;
2217 meta->methodLists = nil;
2218 meta->cache = (Cache)&_objc_empty_cache;
2219 meta->protocols = nil;
2225 Class objc_allocateClassPair(Class supercls, const char *name,
2230 if (objc_getClass(name)) return nil;
2231 // fixme reserve class name against simultaneous allocation
2233 if (supercls && (supercls->info & CLS_CONSTRUCTING)) {
2234 // Can't make subclass of an in-construction class
2238 // Allocate new classes.
2240 cls = _calloc_class(supercls->ISA()->alignedInstanceSize() + extraBytes);
2241 meta = _calloc_class(supercls->ISA()->ISA()->alignedInstanceSize() + extraBytes);
2243 cls = _calloc_class(sizeof(objc_class) + extraBytes);
2244 meta = _calloc_class(sizeof(objc_class) + extraBytes);
2248 objc_initializeClassPair(supercls, name, cls, meta);
2254 void objc_registerClassPair(Class cls)
2256 if ((cls->info & CLS_CONSTRUCTED) ||
2257 (cls->ISA()->info & CLS_CONSTRUCTED))
2259 _objc_inform("objc_registerClassPair: class '%s' was already "
2260 "registered!", cls->name);
2264 if (!(cls->info & CLS_CONSTRUCTING) ||
2265 !(cls->ISA()->info & CLS_CONSTRUCTING))
2267 _objc_inform("objc_registerClassPair: class '%s' was not "
2268 "allocated with objc_allocateClassPair!", cls->name);
2273 _objc_inform("objc_registerClassPair: class '%s' is a metaclass, "
2274 "not a class!", cls->name);
2278 mutex_locker_t lock(classLock);
2280 // Clear "under construction" bit, set "done constructing" bit
2281 cls->info &= ~CLS_CONSTRUCTING;
2282 cls->ISA()->info &= ~CLS_CONSTRUCTING;
2283 cls->info |= CLS_CONSTRUCTED;
2284 cls->ISA()->info |= CLS_CONSTRUCTED;
2286 NXHashInsertIfAbsent(class_hash, cls);
2290 Class objc_duplicateClass(Class original, const char *name, size_t extraBytes)
2292 unsigned int count, i;
2293 old_method **originalMethods;
2294 old_method_list *duplicateMethods;
2295 // Don't use sizeof(objc_class) here because
2296 // instance_size has historically contained two extra words,
2297 // and instance_size is what objc_getIndexedIvars() actually uses.
2299 _calloc_class(original->ISA()->alignedInstanceSize() + extraBytes);
2301 duplicate->initIsa(original->ISA());
2302 duplicate->superclass = original->superclass;
2303 duplicate->name = strdup(name);
2304 duplicate->version = original->version;
2305 duplicate->info = original->info & (CLS_CLASS|CLS_META|CLS_INITIALIZED|CLS_JAVA_HYBRID|CLS_JAVA_CLASS|CLS_HAS_CXX_STRUCTORS|CLS_HAS_LOAD_METHOD);
2306 duplicate->instance_size = original->instance_size;
2307 duplicate->ivars = original->ivars;
2308 // methodLists handled below
2309 duplicate->cache = (Cache)&_objc_empty_cache;
2310 duplicate->protocols = original->protocols;
2311 if (original->info & CLS_EXT) {
2312 duplicate->info |= original->info & (CLS_EXT|CLS_NO_PROPERTY_ARRAY);
2313 duplicate->ivar_layout = original->ivar_layout;
2314 if (original->ext) {
2315 duplicate->ext = (old_class_ext *)malloc(original->ext->size);
2316 memcpy(duplicate->ext, original->ext, original->ext->size);
2318 duplicate->ext = nil;
2322 // Method lists are deep-copied so they can be stomped.
2323 originalMethods = (old_method **)class_copyMethodList(original, &count);
2324 if (originalMethods) {
2325 duplicateMethods = (old_method_list *)
2326 calloc(sizeof(old_method_list) +
2327 (count-1)*sizeof(old_method), 1);
2328 duplicateMethods->obsolete = fixed_up_method_list;
2329 duplicateMethods->method_count = count;
2330 for (i = 0; i < count; i++) {
2331 duplicateMethods->method_list[i] = *(originalMethods[i]);
2333 duplicate->methodLists = (old_method_list **)duplicateMethods;
2334 duplicate->info |= CLS_NO_METHOD_ARRAY;
2335 free(originalMethods);
2338 mutex_locker_t lock(classLock);
2339 NXHashInsert(class_hash, duplicate);
2345 void objc_disposeClassPair(Class cls)
2347 if (!(cls->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)) ||
2348 !(cls->ISA()->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)))
2350 // class not allocated with objc_allocateClassPair
2351 // disposing still-unregistered class is OK!
2352 _objc_inform("objc_disposeClassPair: class '%s' was not "
2353 "allocated with objc_allocateClassPair!", cls->name);
2358 _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
2359 "not a class!", cls->name);
2363 mutex_locker_t lock(classLock);
2364 NXHashRemove(class_hash, cls);
2365 unload_class(cls->ISA());
2370 /***********************************************************************
2371 * objc_constructInstance
2372 * Creates an instance of `cls` at the location pointed to by `bytes`.
2373 * `bytes` must point to at least class_getInstanceSize(cls) bytes of
2374 * well-aligned zero-filled memory.
2375 * The new object's isa is set. Any C++ constructors are called.
2376 * Returns `bytes` if successful. Returns nil if `cls` or `bytes` is
2377 * nil, or if C++ constructors fail.
2378 **********************************************************************/
2380 objc_constructInstance(Class cls, void *bytes)
2382 if (!cls || !bytes) return nil;
2388 if (cls->hasCxxCtor()) {
2389 return object_cxxConstructFromClass(obj, cls);
2396 /***********************************************************************
2397 * _class_createInstanceFromZone. Allocate an instance of the
2398 * specified class with the specified number of bytes for indexed
2399 * variables, in the specified zone. The isa field is set to the
2400 * class, C++ default constructors are called, and all other fields are zeroed.
2401 **********************************************************************/
2403 _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
2408 // Can't create something for nothing
2409 if (!cls) return nil;
2411 // Allocate and initialize
2412 size = cls->alignedInstanceSize() + extraBytes;
2414 // CF requires all objects be at least 16 bytes.
2415 if (size < 16) size = 16;
2418 bytes = malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
2420 bytes = calloc(1, size);
2423 return objc_constructInstance(cls, bytes);
2427 /***********************************************************************
2428 * _class_createInstance. Allocate an instance of the specified
2429 * class with the specified number of bytes for indexed variables, in
2430 * the default zone, using _class_createInstanceFromZone.
2431 **********************************************************************/
2432 static id _class_createInstance(Class cls, size_t extraBytes)
2434 return _class_createInstanceFromZone (cls, extraBytes, nil);
2438 static id _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
2443 if (!oldObj) return nil;
2445 obj = (*_zoneAlloc)(oldObj->ISA(), extraBytes, zone);
2446 size = oldObj->ISA()->alignedInstanceSize() + extraBytes;
2448 // fixme need C++ copy constructor
2449 memmove(obj, oldObj, size);
2451 fixupCopiedIvars(obj, oldObj);
2457 /***********************************************************************
2458 * objc_destructInstance
2459 * Destroys an instance without freeing memory.
2460 * Calls C++ destructors.
2461 * Removes associative references.
2462 * Returns `obj`. Does nothing if `obj` is nil.
2463 * CoreFoundation and other clients do call this under GC.
2464 **********************************************************************/
2465 void *objc_destructInstance(id obj)
2468 Class isa = obj->getIsa();
2470 if (isa->hasCxxDtor()) {
2471 object_cxxDestruct(obj);
2474 if (isa->instancesHaveAssociatedObjects()) {
2475 _object_remove_assocations(obj);
2478 objc_clear_deallocating(obj);
2485 _object_dispose(id anObject)
2487 if (anObject==nil) return nil;
2489 objc_destructInstance(anObject);
2491 anObject->initIsa(_objc_getFreedObjectClass ());
2497 static id _object_copy(id oldObj, size_t extraBytes)
2499 void *z = malloc_zone_from_ptr(oldObj);
2500 return _object_copyFromZone(oldObj, extraBytes,
2501 z ? z : malloc_default_zone());
2504 static id _object_reallocFromZone(id anObject, size_t nBytes, void *zone)
2509 if (anObject == nil)
2510 __objc_error(nil, "reallocating nil object");
2512 if (anObject->ISA() == _objc_getFreedObjectClass ())
2513 __objc_error(anObject, "reallocating freed object");
2515 if (nBytes < anObject->ISA()->alignedInstanceSize())
2516 __objc_error(anObject, "(%s, %zu) requested size too small",
2517 object_getClassName(anObject), nBytes);
2519 // fixme need C++ copy constructor
2521 // Make sure not to modify space that has been declared free
2522 tmp = anObject->ISA();
2523 anObject->initIsa(_objc_getFreedObjectClass ());
2524 newObject = (id)malloc_zone_realloc((malloc_zone_t *)zone, anObject, nBytes);
2526 newObject->initIsa(tmp);
2528 // realloc failed, anObject is still alive
2529 anObject->initIsa(tmp);
2535 static id _object_realloc(id anObject, size_t nBytes)
2537 void *z = malloc_zone_from_ptr(anObject);
2538 return _object_reallocFromZone(anObject,
2540 z ? z : malloc_default_zone());
2543 id (*_alloc)(Class, size_t) = _class_createInstance;
2544 id (*_copy)(id, size_t) = _object_copy;
2545 id (*_realloc)(id, size_t) = _object_realloc;
2546 id (*_dealloc)(id) = _object_dispose;
2547 id (*_zoneAlloc)(Class, size_t, void *) = _class_createInstanceFromZone;
2548 id (*_zoneCopy)(id, size_t, void *) = _object_copyFromZone;
2549 id (*_zoneRealloc)(id, size_t, void *) = _object_reallocFromZone;
2550 void (*_error)(id, const char *, va_list) = _objc_error;
2553 id class_createInstance(Class cls, size_t extraBytes)
2555 return (*_alloc)(cls, extraBytes);
2558 id class_createInstanceFromZone(Class cls, size_t extraBytes, void *z)
2560 OBJC_WARN_DEPRECATED;
2561 return (*_zoneAlloc)(cls, extraBytes, z);
2564 unsigned class_createInstances(Class cls, size_t extraBytes,
2565 id *results, unsigned num_requested)
2567 if (_alloc == &_class_createInstance) {
2568 return _class_createInstancesFromZone(cls, extraBytes, nil,
2569 results, num_requested);
2571 // _alloc in use, which isn't understood by the batch allocator
2576 id object_copy(id obj, size_t extraBytes)
2578 return (*_copy)(obj, extraBytes);
2581 id object_copyFromZone(id obj, size_t extraBytes, void *z)
2583 OBJC_WARN_DEPRECATED;
2584 return (*_zoneCopy)(obj, extraBytes, z);
2587 id object_dispose(id obj)
2589 return (*_dealloc)(obj);
2592 id object_realloc(id obj, size_t nBytes)
2594 OBJC_WARN_DEPRECATED;
2595 return (*_realloc)(obj, nBytes);
2598 id object_reallocFromZone(id obj, size_t nBytes, void *z)
2600 OBJC_WARN_DEPRECATED;
2601 return (*_zoneRealloc)(obj, nBytes, z);
2605 /***********************************************************************
2606 * object_getIndexedIvars.
2607 **********************************************************************/
2608 void *object_getIndexedIvars(id obj)
2610 // ivars are tacked onto the end of the object
2611 if (!obj) return nil;
2612 if (obj->isTaggedPointer()) return nil;
2613 return ((char *) obj) + obj->ISA()->alignedInstanceSize();
2618 Class class_setSuperclass(Class cls, Class newSuper)
2620 Class oldSuper = cls->superclass;
2621 set_superclass(cls, newSuper, NO);
2622 flush_caches(cls, YES);