2 * Copyright (c) 1999-2007 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 /***********************************************************************
26 * Support for old-ABI classes and images.
27 **********************************************************************/
29 /***********************************************************************
30 * Class loading and connecting (GrP 2004-2-11)
32 * When images are loaded (during program startup or otherwise), the
33 * runtime needs to load classes and categories from the images, connect
34 * classes to superclasses and categories to parent classes, and call
37 * The Objective-C runtime can cope with classes arriving in any order.
38 * That is, a class may be discovered by the runtime before some
39 * superclass is known. To handle out-of-order class loads, the
40 * runtime uses a "pending class" system.
43 * Panther and earlier: many classes arrived out-of-order because of
44 * the poorly-ordered callback from dyld. However, the runtime's
45 * pending mechanism only handled "missing superclass" and not
46 * "present superclass but missing higher class". See Radar #3225652.
47 * Tiger: The runtime's pending mechanism was augmented to handle
48 * arbitrary missing classes. In addition, dyld was rewritten and
49 * now sends the callbacks in strictly bottom-up link order.
50 * The pending mechanism may now be needed only for rare and
51 * hard to construct programs.
52 * (End historical note)
54 * A class when first seen in an image is considered "unconnected".
55 * It is stored in `unconnected_class_hash`. If all of the class's
56 * superclasses exist and are already "connected", then the new class
57 * can be connected to its superclasses and moved to `class_hash` for
58 * normal use. Otherwise, the class waits in `unconnected_class_hash`
59 * until the superclasses finish connecting.
61 * A "connected" class is
62 * (1) in `class_hash`,
63 * (2) connected to its superclasses,
64 * (3) has no unconnected superclasses,
65 * (4) is otherwise initialized and ready for use, and
66 * (5) is eligible for +load if +load has not already been called.
68 * An "unconnected" class is
69 * (1) in `unconnected_class_hash`,
70 * (2) not connected to its superclasses,
71 * (3) has an immediate superclass which is either missing or unconnected,
72 * (4) is not ready for use, and
73 * (5) is not yet eligible for +load.
75 * Image mapping is NOT CURRENTLY THREAD-SAFE with respect to just about
76 * anything. Image mapping IS RE-ENTRANT in several places: superclass
77 * lookup may cause ZeroLink to load another image, and +load calls may
78 * cause dyld to load another image.
80 * Image mapping sequence:
82 * Read all classes in all new images.
83 * Add them all to unconnected_class_hash.
84 * Note any +load implementations before categories are attached.
85 * Attach any pending categories.
86 * Read all categories in all new images.
87 * Attach categories whose parent class exists (connected or not),
89 * Mark them all eligible for +load (if implemented), even if the
90 * parent class is missing.
91 * Try to connect all classes in all new images.
92 * If the superclass is missing, pend the class
93 * If the superclass is unconnected, try to recursively connect it
94 * If the superclass is connected:
96 * mark the class eligible for +load, if implemented
97 * fix up any pended classrefs referring to the class
98 * connect any pended subclasses of the class
99 * Resolve selector refs and class refs in all new images.
100 * Class refs whose classes still do not exist are pended.
101 * Fix up protocol objects in all new images.
102 * Call +load for classes and categories.
103 * May include classes or categories that are not in these images,
104 * but are newly eligible because of these image.
105 * Class +loads will be called superclass-first because of the
106 * superclass-first nature of the connecting process.
107 * Category +load needs to be deferred until the parent class is
108 * connected and has had its +load called.
110 * Performance: all classes are read before any categories are read.
111 * Fewer categories need be pended for lack of a parent class.
113 * Performance: all categories are attempted to be attached before
114 * any classes are connected. Fewer class caches need be flushed.
115 * (Unconnected classes and their respective subclasses are guaranteed
116 * to be un-messageable, so their caches will be empty.)
118 * Performance: all classes are read before any classes are connected.
119 * Fewer classes need be pended for lack of a superclass.
121 * Correctness: all selector and class refs are fixed before any
122 * protocol fixups or +load methods. libobjc itself contains selector
123 * and class refs which are used in protocol fixup and +load.
125 * Correctness: +load methods are scheduled in bottom-up link order.
126 * This constraint is in addition to superclass order. Some +load
127 * implementations expect to use another class in a linked-to library,
128 * even if the two classes don't share a direct superclass relationship.
130 * Correctness: all classes are scanned for +load before any categories
131 * are attached. Otherwise, if a category implements +load and its class
132 * has no class methods, the class's +load scan would find the category's
133 * +load method, which would then be called twice.
135 * Correctness: pended class refs are not fixed up until the class is
136 * connected. Classes with missing weak superclasses remain unconnected.
137 * Class refs to classes with missing weak superclasses must be nil.
138 * Therefore class refs to unconnected classes must remain un-fixed.
140 **********************************************************************/
144 #include "objc-private.h"
145 #include "objc-runtime-old.h"
146 #include "objc-file-old.h"
147 #include "objc-cache-old.h"
148 #include "objc-loadmethod.h"
151 typedef struct _objc_unresolved_category
153 struct _objc_unresolved_category *next;
154 old_category *cat; // may be nil
156 } _objc_unresolved_category;
158 typedef struct _PendingSubclass
160 Class subclass; // subclass to finish connecting; may be nil
161 struct _PendingSubclass *next;
164 typedef struct _PendingClassRef
166 Class *ref; // class reference to fix up; may be nil
167 // (ref & 1) is a metaclass reference
168 struct _PendingClassRef *next;
172 static uintptr_t classHash(void *info, Class data);
173 static int classIsEqual(void *info, Class name, Class cls);
174 static int _objc_defaultClassHandler(const char *clsName);
175 static inline NXMapTable *pendingClassRefsMapTable(void);
176 static inline NXMapTable *pendingSubclassesMapTable(void);
177 static void pendClassInstallation(Class cls, const char *superName);
178 static void pendClassReference(Class *ref, const char *className, BOOL isMeta);
179 static void resolve_references_to_class(Class cls);
180 static void resolve_subclasses_of_class(Class cls);
181 static void really_connect_class(Class cls, Class supercls);
182 static BOOL connect_class(Class cls);
183 static void map_method_descs (struct objc_method_description_list * methods, BOOL copy);
184 static void _objcTweakMethodListPointerForClass(Class cls);
185 static inline void _objc_add_category(Class cls, old_category *category, int version);
186 static BOOL _objc_add_category_flush_caches(Class cls, old_category *category, int version);
187 static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat);
188 static void resolve_categories_for_class(Class cls);
189 static BOOL _objc_register_category(old_category *cat, int version);
192 // Function called when a class is loaded from an image
193 void (*callbackFunction)(Class, Category) = 0;
195 // Hash table of classes
196 NXHashTable * class_hash = 0;
197 static NXHashTablePrototype classHashPrototype =
199 (uintptr_t (*) (const void *, const void *)) classHash,
200 (int (*)(const void *, const void *, const void *)) classIsEqual,
204 // Hash table of unconnected classes
205 static NXHashTable *unconnected_class_hash = nil;
207 // Exported copy of class_hash variable (hook for debugging tools)
208 NXHashTable *_objc_debug_class_hash = nil;
210 // Category and class registries
211 // Keys are COPIES of strings, to prevent stale pointers with unloaded bundles
212 // Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove
213 static NXMapTable * category_hash = nil;
215 // Keys are COPIES of strings, to prevent stale pointers with unloaded bundles
216 // Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove
217 static NXMapTable * pendingClassRefsMap = nil;
218 static NXMapTable * pendingSubclassesMap = nil;
221 static NXMapTable *protocol_map = nil; // name -> protocol
222 static NXMapTable *protocol_ext_map = nil; // protocol -> protocol ext
224 // Function pointer objc_getClass calls through when class is not found
225 static int (*objc_classHandler) (const char *) = _objc_defaultClassHandler;
227 // Function pointer called by objc_getClass and objc_lookupClass when
228 // class is not found. _objc_classLoader is called before objc_classHandler.
229 static BOOL (*_objc_classLoader)(const char *) = nil;
232 /***********************************************************************
233 * objc_dump_class_hash. Log names of all known classes.
234 **********************************************************************/
235 void objc_dump_class_hash(void)
244 state = NXInitHashState (table);
245 while (NXNextHashState (table, &state, (void **) &data))
246 printf ("class %d: %s\n", ++count, data->getName());
250 /***********************************************************************
251 * _objc_init_class_hash. Return the class lookup table, create it if
253 **********************************************************************/
254 void _objc_init_class_hash(void)
256 // Do nothing if class hash table already exists
260 // class_hash starts small, with only enough capacity for libobjc itself.
261 // If a second library is found by map_images(), class_hash is immediately
262 // resized to capacity 1024 to cut down on rehashes.
263 // Old numbers: A smallish Foundation+AppKit program will have
264 // about 520 classes. Larger apps (like IB or WOB) have more like
265 // 800 classes. Some customers have massive quantities of classes.
266 // Foundation-only programs aren't likely to notice the ~6K loss.
267 class_hash = NXCreateHashTableFromZone (classHashPrototype,
270 _objc_internal_zone ());
271 _objc_debug_class_hash = class_hash;
275 /***********************************************************************
276 * objc_getClassList. Return the known classes.
277 **********************************************************************/
278 int objc_getClassList(Class *buffer, int bufferLen)
284 mutex_lock(&classLock);
286 mutex_unlock(&classLock);
289 num = NXCountHashTable(class_hash);
291 mutex_unlock(&classLock);
295 state = NXInitHashState(class_hash);
296 while (cnt < bufferLen &&
297 NXNextHashState(class_hash, &state, (void **)&cls))
301 mutex_unlock(&classLock);
306 /***********************************************************************
308 * Returns pointers to all classes.
309 * This requires all classes be realized, which is regretfully non-lazy.
311 * outCount may be nil. *outCount is the number of classes returned.
312 * If the returned array is not nil, it is nil-terminated and must be
314 * Locking: acquires classLock
315 **********************************************************************/
317 objc_copyClassList(unsigned int *outCount)
322 mutex_lock(&classLock);
324 count = class_hash ? NXCountHashTable(class_hash) : 0;
328 NXHashState state = NXInitHashState(class_hash);
329 result = (Class *)malloc((1+count) * sizeof(Class));
331 while (NXNextHashState(class_hash, &state, (void **)&cls)) {
332 result[count++] = cls;
336 mutex_unlock(&classLock);
338 if (outCount) *outCount = count;
343 /***********************************************************************
344 * objc_copyProtocolList
345 * Returns pointers to all protocols.
346 * Locking: acquires classLock
347 **********************************************************************/
348 Protocol * __unsafe_unretained *
349 objc_copyProtocolList(unsigned int *outCount)
357 mutex_lock(&classLock);
359 count = NXCountMapTable(protocol_map);
361 mutex_unlock(&classLock);
362 if (outCount) *outCount = 0;
366 result = (Protocol **)calloc(1 + count, sizeof(Protocol *));
369 state = NXInitMapState(protocol_map);
370 while (NXNextMapState(protocol_map, &state,
371 (const void **)&name, (const void **)&proto))
377 assert(i == count+1);
379 mutex_unlock(&classLock);
381 if (outCount) *outCount = count;
386 /***********************************************************************
387 * objc_getClasses. Return class lookup table.
389 * NOTE: This function is very dangerous, since you cannot safely use
390 * the hashtable without locking it, and the lock is private!
391 **********************************************************************/
392 void *objc_getClasses(void)
394 OBJC_WARN_DEPRECATED;
396 // Return the class lookup hash table
401 /***********************************************************************
403 **********************************************************************/
404 static uintptr_t classHash(void *info, Class data)
406 // Nil classes hash to zero
410 // Call through to real hash function
411 return _objc_strhash (data->getName());
414 /***********************************************************************
415 * classIsEqual. Returns whether the class names match. If we ever
416 * check more than the name, routines like objc_lookUpClass have to
418 **********************************************************************/
419 static int classIsEqual(void *info, Class name, Class cls)
421 // Standard string comparison
422 return strcmp(name->getName(), cls->getName()) == 0;
426 // Unresolved future classes
427 static NXHashTable *future_class_hash = nil;
429 // Resolved future<->original classes
430 static NXMapTable *future_class_to_original_class_map = nil;
431 static NXMapTable *original_class_to_future_class_map = nil;
433 // CF requests about 20 future classes; HIToolbox requests one.
434 #define FUTURE_COUNT 32
437 /***********************************************************************
438 * setOriginalClassForFutureClass
439 * Record resolution of a future class.
440 **********************************************************************/
441 static void setOriginalClassForFutureClass(Class futureClass,
444 if (!future_class_to_original_class_map) {
445 future_class_to_original_class_map =
446 NXCreateMapTableFromZone (NXPtrValueMapPrototype, FUTURE_COUNT,
447 _objc_internal_zone ());
448 original_class_to_future_class_map =
449 NXCreateMapTableFromZone (NXPtrValueMapPrototype, FUTURE_COUNT,
450 _objc_internal_zone ());
453 NXMapInsert (future_class_to_original_class_map,
454 futureClass, originalClass);
455 NXMapInsert (original_class_to_future_class_map,
456 originalClass, futureClass);
459 _objc_inform("FUTURE: using %p instead of %p for %s", (void*)futureClass, (void*)originalClass, originalClass->name);
463 /***********************************************************************
464 * getOriginalClassForFutureClass
465 * getFutureClassForOriginalClass
466 * Switch between a future class and its corresponding original class.
467 * The future class is the one actually in use.
468 * The original class is the one from disk.
469 **********************************************************************/
472 getOriginalClassForFutureClass(Class futureClass)
474 if (!future_class_to_original_class_map) return Nil;
475 return NXMapGet (future_class_to_original_class_map, futureClass);
479 getFutureClassForOriginalClass(Class originalClass)
481 if (!original_class_to_future_class_map) return Nil;
482 return (Class)NXMapGet(original_class_to_future_class_map, originalClass);
486 /***********************************************************************
488 * Initialize the memory in *cls with an unresolved future class with the
489 * given name. The memory is recorded in future_class_hash.
490 **********************************************************************/
491 static void makeFutureClass(Class cls, const char *name)
493 // CF requests about 20 future classes, plus HIToolbox has one.
494 if (!future_class_hash) {
496 NXCreateHashTableFromZone(classHashPrototype, FUTURE_COUNT,
497 nil, _objc_internal_zone());
500 cls->name = _strdup_internal(name);
501 NXHashInsert(future_class_hash, cls);
504 _objc_inform("FUTURE: reserving %p for %s", (void*)cls, name);
509 /***********************************************************************
510 * _objc_allocateFutureClass
511 * Allocate an unresolved future class for the given class name.
512 * Returns any existing allocation if one was already made.
513 * Assumes the named class doesn't exist yet.
515 **********************************************************************/
516 Class _objc_allocateFutureClass(const char *name)
520 if (future_class_hash) {
523 if ((cls = (Class)NXHashGet(future_class_hash, &query))) {
524 // Already have a future class for this name.
529 cls = _calloc_class(sizeof(objc_class));
530 makeFutureClass(cls, name);
535 /***********************************************************************
536 * objc_setFutureClass.
537 * Like objc_getFutureClass, but uses the provided memory block.
538 * If the class already exists, a posing-like substitution is performed.
540 **********************************************************************/
541 void objc_setFutureClass(Class cls, const char *name)
544 Class newcls = cls; // Not a real class!
546 if ((oldcls = look_up_class(name, NO/*unconnected*/, NO/*classhandler*/))) {
547 setOriginalClassForFutureClass(newcls, oldcls);
549 memcpy(newcls, oldcls, sizeof(struct objc_class));
550 newcls->info &= ~CLS_EXT;
552 mutex_lock(&classLock);
553 NXHashRemove(class_hash, oldcls);
554 objc_removeRegisteredClass(oldcls);
555 change_class_references(newcls, oldcls, nil, YES);
556 NXHashInsert(class_hash, newcls);
557 objc_addRegisteredClass(newcls);
558 mutex_unlock(&classLock);
560 makeFutureClass(newcls, name);
565 BOOL _class_isFutureClass(Class cls)
567 return cls && future_class_hash && NXHashGet(future_class_hash, cls);
571 /***********************************************************************
572 * _objc_defaultClassHandler. Default objc_classHandler. Does nothing.
573 **********************************************************************/
574 static int _objc_defaultClassHandler(const char *clsName)
576 // Return zero so objc_getClass doesn't bother re-searching
580 /***********************************************************************
581 * objc_setClassHandler. Set objc_classHandler to the specified value.
583 * NOTE: This should probably deal with userSuppliedHandler being nil,
584 * because the objc_classHandler caller does not check... it would bus
585 * error. It would make sense to handle nil by restoring the default
586 * handler. Is anyone hacking with this, though?
587 **********************************************************************/
588 void objc_setClassHandler(int (*userSuppliedHandler)(const char *))
590 OBJC_WARN_DEPRECATED;
592 objc_classHandler = userSuppliedHandler;
596 /***********************************************************************
597 * _objc_setClassLoader
598 * Similar to objc_setClassHandler, but objc_classLoader is used for
599 * both objc_getClass() and objc_lookupClass(), and objc_classLoader
600 * pre-empts objc_classHandler.
601 **********************************************************************/
602 void _objc_setClassLoader(BOOL (*newClassLoader)(const char *))
604 _objc_classLoader = newClassLoader;
608 /***********************************************************************
610 * Get a protocol by name, or nil.
611 **********************************************************************/
612 Protocol *objc_getProtocol(const char *name)
615 if (!protocol_map) return nil;
616 mutex_lock(&classLock);
617 result = (Protocol *)NXMapGet(protocol_map, name);
618 mutex_unlock(&classLock);
623 /***********************************************************************
625 * Map a class name to a class using various methods.
626 * This is the common implementation of objc_lookUpClass and objc_getClass,
627 * and is also used internally to get additional search options.
630 * 2. unconnected_class_hash (optional)
631 * 3. classLoader callback
632 * 4. classHandler callback (optional)
633 **********************************************************************/
634 Class look_up_class(const char *aClassName, BOOL includeUnconnected, BOOL includeClassHandler)
636 BOOL includeClassLoader = YES; // class loader cannot be skipped
638 struct objc_class query;
640 query.name = aClassName;
644 if (!result && class_hash) {
645 // Check ordinary classes
646 mutex_lock (&classLock);
647 result = (Class)NXHashGet(class_hash, &query);
648 mutex_unlock (&classLock);
651 if (!result && includeUnconnected && unconnected_class_hash) {
652 // Check not-yet-connected classes
653 mutex_lock(&classLock);
654 result = (Class)NXHashGet(unconnected_class_hash, &query);
655 mutex_unlock(&classLock);
658 if (!result && includeClassLoader && _objc_classLoader) {
659 // Try class loader callback
660 if ((*_objc_classLoader)(aClassName)) {
661 // Re-try lookup without class loader
662 includeClassLoader = NO;
667 if (!result && includeClassHandler && objc_classHandler) {
668 // Try class handler callback
669 if ((*objc_classHandler)(aClassName)) {
670 // Re-try lookup without class handler or class loader
671 includeClassLoader = NO;
672 includeClassHandler = NO;
681 /***********************************************************************
682 * objc_class::isConnected
683 * Returns TRUE if class cls is connected.
684 * A connected class has either a connected superclass or a nil superclass,
685 * and is present in class_hash.
686 **********************************************************************/
687 bool objc_class::isConnected()
690 mutex_lock(&classLock);
691 result = NXHashMember(class_hash, this);
692 mutex_unlock(&classLock);
697 /***********************************************************************
698 * pendingClassRefsMapTable. Return a pointer to the lookup table for
699 * pending class refs.
700 **********************************************************************/
701 static inline NXMapTable *pendingClassRefsMapTable(void)
703 // Allocate table if needed
704 if (!pendingClassRefsMap) {
705 pendingClassRefsMap =
706 NXCreateMapTableFromZone(NXStrValueMapPrototype,
707 10, _objc_internal_zone ());
710 // Return table pointer
711 return pendingClassRefsMap;
715 /***********************************************************************
716 * pendingSubclassesMapTable. Return a pointer to the lookup table for
717 * pending subclasses.
718 **********************************************************************/
719 static inline NXMapTable *pendingSubclassesMapTable(void)
721 // Allocate table if needed
722 if (!pendingSubclassesMap) {
723 pendingSubclassesMap =
724 NXCreateMapTableFromZone(NXStrValueMapPrototype,
725 10, _objc_internal_zone ());
728 // Return table pointer
729 return pendingSubclassesMap;
733 /***********************************************************************
734 * pendClassInstallation
735 * Finish connecting class cls when its superclass becomes connected.
736 * Check for multiple pends of the same class because connect_class does not.
737 **********************************************************************/
738 static void pendClassInstallation(Class cls, const char *superName)
741 PendingSubclass *pending;
742 PendingSubclass *oldList;
745 // Create and/or locate pending class lookup table
746 table = pendingSubclassesMapTable ();
748 // Make sure this class isn't already in the pending list.
749 oldList = (PendingSubclass *)NXMapGet(table, superName);
750 for (l = oldList; l != nil; l = l->next) {
751 if (l->subclass == cls) return; // already here, nothing to do
754 // Create entry referring to this class
755 pending = (PendingSubclass *)_malloc_internal(sizeof(PendingSubclass));
756 pending->subclass = cls;
758 // Link new entry into head of list of entries for this class
759 pending->next = oldList;
761 // (Re)place entry list in the table
762 NXMapKeyCopyingInsert (table, superName, pending);
766 /***********************************************************************
768 * Fix up a class ref when the class with the given name becomes connected.
769 **********************************************************************/
770 static void pendClassReference(Class *ref, const char *className, BOOL isMeta)
773 PendingClassRef *pending;
775 // Create and/or locate pending class lookup table
776 table = pendingClassRefsMapTable ();
778 // Create entry containing the class reference
779 pending = (PendingClassRef *)_malloc_internal(sizeof(PendingClassRef));
782 pending->ref = (Class *)((uintptr_t)pending->ref | 1);
785 // Link new entry into head of list of entries for this class
786 pending->next = (PendingClassRef *)NXMapGet(table, className);
788 // (Re)place entry list in the table
789 NXMapKeyCopyingInsert (table, className, pending);
791 if (PrintConnecting) {
792 _objc_inform("CONNECT: pended reference to class '%s%s' at %p",
793 className, isMeta ? " (meta)" : "", (void *)ref);
798 /***********************************************************************
799 * resolve_references_to_class
800 * Fix up any pending class refs to this class.
801 **********************************************************************/
802 static void resolve_references_to_class(Class cls)
804 PendingClassRef *pending;
806 if (!pendingClassRefsMap) return; // no unresolved refs for any class
808 pending = (PendingClassRef *)NXMapGet(pendingClassRefsMap, cls->name);
809 if (!pending) return; // no unresolved refs for this class
811 NXMapKeyFreeingRemove(pendingClassRefsMap, cls->name);
813 if (PrintConnecting) {
814 _objc_inform("CONNECT: resolving references to class '%s'", cls->name);
818 PendingClassRef *next = pending->next;
820 BOOL isMeta = ((uintptr_t)pending->ref & 1) ? YES : NO;
822 (Class *)((uintptr_t)pending->ref & ~(uintptr_t)1);
823 *ref = isMeta ? cls->ISA() : cls;
825 _free_internal(pending);
829 if (NXCountMapTable(pendingClassRefsMap) == 0) {
830 NXFreeMapTable(pendingClassRefsMap);
831 pendingClassRefsMap = nil;
836 /***********************************************************************
837 * resolve_subclasses_of_class
838 * Fix up any pending subclasses of this class.
839 **********************************************************************/
840 static void resolve_subclasses_of_class(Class cls)
842 PendingSubclass *pending;
844 if (!pendingSubclassesMap) return; // no unresolved subclasses
846 pending = (PendingSubclass *)NXMapGet(pendingSubclassesMap, cls->name);
847 if (!pending) return; // no unresolved subclasses for this class
849 NXMapKeyFreeingRemove(pendingSubclassesMap, cls->name);
851 // Destroy the pending table if it's now empty, to save memory.
852 if (NXCountMapTable(pendingSubclassesMap) == 0) {
853 NXFreeMapTable(pendingSubclassesMap);
854 pendingSubclassesMap = nil;
857 if (PrintConnecting) {
858 _objc_inform("CONNECT: resolving subclasses of class '%s'", cls->name);
862 PendingSubclass *next = pending->next;
863 if (pending->subclass) connect_class(pending->subclass);
864 _free_internal(pending);
870 /***********************************************************************
871 * really_connect_class
872 * Connect cls to superclass supercls unconditionally.
873 * Also adjust the class hash tables and handle pended subclasses.
875 * This should be called from connect_class() ONLY.
876 **********************************************************************/
877 static void really_connect_class(Class cls,
882 // Connect superclass pointers.
883 set_superclass(cls, supercls, YES);
886 // For paranoia, this is a conservative update:
887 // only non-strong -> strong and weak -> strong are corrected.
888 if (UseGC && supercls &&
889 (cls->info & CLS_EXT) && (supercls->info & CLS_EXT))
892 layout_bitmap ivarBitmap =
893 layout_bitmap_create(cls->ivar_layout,
895 cls->instance_size, NO);
897 layout_bitmap superBitmap =
898 layout_bitmap_create(supercls->ivar_layout,
899 supercls->instance_size,
900 supercls->instance_size, NO);
902 // non-strong -> strong: bits set in super should be set in sub
903 layoutChanged = layout_bitmap_or(ivarBitmap, superBitmap, cls->name);
904 layout_bitmap_free(superBitmap);
907 layout_bitmap weakBitmap = {};
908 BOOL weakLayoutChanged = NO;
910 if (cls->ext && cls->ext->weak_ivar_layout) {
911 // weak -> strong: strong bits should be cleared in weak layout
912 // This is a subset of non-strong -> strong
914 layout_bitmap_create(cls->ext->weak_ivar_layout,
916 cls->instance_size, YES);
919 layout_bitmap_clear(weakBitmap, ivarBitmap, cls->name);
921 // no existing weak ivars, so no weak -> strong changes
924 // Rebuild layout strings.
926 _objc_inform("IVARS: gc layout changed "
927 "for class %s (super %s)",
928 cls->name, supercls->name);
929 if (weakLayoutChanged) {
930 _objc_inform("IVARS: gc weak layout changed "
931 "for class %s (super %s)",
932 cls->name, supercls->name);
935 cls->ivar_layout = layout_string_create(ivarBitmap);
936 if (weakLayoutChanged) {
937 cls->ext->weak_ivar_layout = layout_string_create(weakBitmap);
940 layout_bitmap_free(weakBitmap);
943 layout_bitmap_free(ivarBitmap);
947 cls->info |= CLS_CONNECTED;
949 mutex_lock(&classLock);
951 // Update hash tables.
952 NXHashRemove(unconnected_class_hash, cls);
953 oldCls = (Class)NXHashInsert(class_hash, cls);
954 objc_addRegisteredClass(cls);
956 // Delete unconnected_class_hash if it is now empty.
957 if (NXCountHashTable(unconnected_class_hash) == 0) {
958 NXFreeHashTable(unconnected_class_hash);
959 unconnected_class_hash = nil;
962 // No duplicate classes allowed.
963 // Duplicates should have been rejected by _objc_read_classes_from_image.
966 mutex_unlock(&classLock);
968 // Fix up pended class refs to this class, if any
969 resolve_references_to_class(cls);
971 // Connect newly-connectable subclasses
972 resolve_subclasses_of_class(cls);
974 // GC debugging: make sure all classes with -dealloc also have -finalize
975 if (DebugFinalizers) {
976 extern IMP findIMPInClass(Class cls, SEL sel);
977 if (findIMPInClass(cls, sel_getUid("dealloc")) &&
978 ! findIMPInClass(cls, sel_getUid("finalize")))
980 _objc_inform("GC: class '%s' implements -dealloc but not -finalize", cls->name);
984 // Debugging: if this class has ivars, make sure this class's ivars don't
985 // overlap with its super's. This catches some broken fragile base classes.
986 // Do not use super->instance_size vs. self->ivar[0] to check this.
987 // Ivars may be packed across instance_size boundaries.
988 if (DebugFragileSuperclasses && cls->ivars && cls->ivars->ivar_count) {
989 Class ivar_cls = supercls;
991 // Find closest superclass that has some ivars, if one exists.
993 (!ivar_cls->ivars || ivar_cls->ivars->ivar_count == 0))
995 ivar_cls = ivar_cls->superclass;
999 // Compare superclass's last ivar to this class's first ivar
1000 old_ivar *super_ivar =
1001 &ivar_cls->ivars->ivar_list[ivar_cls->ivars->ivar_count - 1];
1002 old_ivar *self_ivar =
1003 &cls->ivars->ivar_list[0];
1005 // fixme could be smarter about super's ivar size
1006 if (self_ivar->ivar_offset <= super_ivar->ivar_offset) {
1007 _objc_inform("WARNING: ivars of superclass '%s' and "
1008 "subclass '%s' overlap; superclass may have "
1009 "changed since subclass was compiled",
1010 ivar_cls->name, cls->name);
1017 /***********************************************************************
1019 * Connect class cls to its superclasses, if possible.
1020 * If cls becomes connected, move it from unconnected_class_hash
1021 * to connected_class_hash.
1022 * Returns TRUE if cls is connected.
1023 * Returns FALSE if cls could not be connected for some reason
1024 * (missing superclass or still-unconnected superclass)
1025 **********************************************************************/
1026 static BOOL connect_class(Class cls)
1028 if (cls->isConnected()) {
1029 // This class is already connected to its superclass.
1033 else if (cls->superclass == nil) {
1034 // This class is a root class.
1035 // Connect it to itself.
1037 if (PrintConnecting) {
1038 _objc_inform("CONNECT: class '%s' now connected (root class)",
1042 really_connect_class(cls, nil);
1046 // This class is not a root class and is not yet connected.
1047 // Connect it if its superclass and root class are already connected.
1048 // Otherwise, add this class to the to-be-connected list,
1049 // pending the completion of its superclass and root class.
1051 // At this point, cls->superclass and cls->ISA()->ISA() are still STRINGS
1052 char *supercls_name = (char *)cls->superclass;
1055 // YES unconnected, YES class handler
1056 if (nil == (supercls = look_up_class(supercls_name, YES, YES))) {
1057 // Superclass does not exist yet.
1058 // pendClassInstallation will handle duplicate pends of this class
1059 pendClassInstallation(cls, supercls_name);
1061 if (PrintConnecting) {
1062 _objc_inform("CONNECT: class '%s' NOT connected (missing super)", cls->name);
1067 if (! connect_class(supercls)) {
1068 // Superclass exists but is not yet connected.
1069 // pendClassInstallation will handle duplicate pends of this class
1070 pendClassInstallation(cls, supercls_name);
1072 if (PrintConnecting) {
1073 _objc_inform("CONNECT: class '%s' NOT connected (unconnected super)", cls->name);
1078 // Superclass exists and is connected.
1079 // Connect this class to the superclass.
1081 if (PrintConnecting) {
1082 _objc_inform("CONNECT: class '%s' now connected", cls->name);
1085 really_connect_class(cls, supercls);
1091 /***********************************************************************
1092 * _objc_read_categories_from_image.
1093 * Read all categories from the given image.
1094 * Install them on their parent classes, or register them for later
1096 * Returns YES if some method caches now need to be flushed.
1097 **********************************************************************/
1098 static BOOL _objc_read_categories_from_image (header_info * hi)
1102 BOOL needFlush = NO;
1104 if (_objcHeaderIsReplacement(hi)) {
1105 // Ignore any categories in this image
1110 // Major loop - process all modules in the header
1113 // NOTE: The module and category lists are traversed backwards
1114 // to preserve the pre-10.4 processing order. Changing the order
1115 // would have a small chance of introducing binary compatibility bugs.
1116 midx = hi->mod_count;
1117 while (midx-- > 0) {
1121 // Nothing to do for a module without a symbol table
1122 if (mods[midx].symtab == nil)
1125 // Total entries in symbol table (class entries followed
1126 // by category entries)
1127 total = mods[midx].symtab->cls_def_cnt +
1128 mods[midx].symtab->cat_def_cnt;
1130 // Minor loop - register all categories from given module
1132 while (index-- > mods[midx].symtab->cls_def_cnt) {
1133 old_category *cat = (old_category *)mods[midx].symtab->defs[index];
1134 needFlush |= _objc_register_category(cat, (int)mods[midx].version);
1142 /***********************************************************************
1143 * _objc_read_classes_from_image.
1144 * Read classes from the given image, perform assorted minor fixups,
1145 * scan for +load implementation.
1146 * Does not connect classes to superclasses.
1147 * Does attach pended categories to the classes.
1148 * Adds all classes to unconnected_class_hash. class_hash is unchanged.
1149 **********************************************************************/
1150 static void _objc_read_classes_from_image(header_info *hi)
1155 int isBundle = headerIsBundle(hi);
1157 if (_objcHeaderIsReplacement(hi)) {
1158 // Ignore any classes in this image
1162 // class_hash starts small, enough only for libobjc itself.
1163 // If other Objective-C libraries are found, immediately resize
1164 // class_hash, assuming that Foundation and AppKit are about
1165 // to add lots of classes.
1166 mutex_lock(&classLock);
1167 if (hi->mhdr != libobjc_header && _NXHashCapacity(class_hash) < 1024) {
1168 _NXHashRehashToCapacity(class_hash, 1024);
1170 mutex_unlock(&classLock);
1172 // Major loop - process all modules in the image
1174 for (midx = 0; midx < hi->mod_count; midx += 1)
1176 // Skip module containing no classes
1177 if (mods[midx].symtab == nil)
1180 // Minor loop - process all the classes in given module
1181 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
1183 Class newCls, oldCls;
1186 // Locate the class description pointer
1187 newCls = (Class)mods[midx].symtab->defs[index];
1189 // Classes loaded from Mach-O bundles can be unloaded later.
1190 // Nothing uses this class yet, so cls->setInfo is not needed.
1191 if (isBundle) newCls->info |= CLS_FROM_BUNDLE;
1192 if (isBundle) newCls->ISA()->info |= CLS_FROM_BUNDLE;
1194 // Use common static empty cache instead of nil
1195 if (newCls->cache == nil)
1196 newCls->cache = (Cache) &_objc_empty_cache;
1197 if (newCls->ISA()->cache == nil)
1198 newCls->ISA()->cache = (Cache) &_objc_empty_cache;
1200 // Set metaclass version
1201 newCls->ISA()->version = mods[midx].version;
1203 // methodLists is nil or a single list, not an array
1204 newCls->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY;
1205 newCls->ISA()->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY;
1207 // class has no subclasses for cache flushing
1208 newCls->info |= CLS_LEAF;
1209 newCls->ISA()->info |= CLS_LEAF;
1211 if (mods[midx].version >= 6) {
1212 // class structure has ivar_layout and ext fields
1213 newCls->info |= CLS_EXT;
1214 newCls->ISA()->info |= CLS_EXT;
1217 // Check for +load implementation before categories are attached
1218 if (_class_hasLoadMethod(newCls)) {
1219 newCls->ISA()->info |= CLS_HAS_LOAD_METHOD;
1222 // Install into unconnected_class_hash.
1223 mutex_lock(&classLock);
1225 if (future_class_hash) {
1226 Class futureCls = (Class)
1227 NXHashRemove(future_class_hash, newCls);
1229 // Another class structure for this class was already
1230 // prepared by objc_getFutureClass(). Use it instead.
1231 _free_internal((char *)futureCls->name);
1232 memcpy(futureCls, newCls, sizeof(objc_class));
1233 setOriginalClassForFutureClass(futureCls, newCls);
1236 if (NXCountHashTable(future_class_hash) == 0) {
1237 NXFreeHashTable(future_class_hash);
1238 future_class_hash = nil;
1243 if (!unconnected_class_hash) {
1244 unconnected_class_hash =
1245 NXCreateHashTableFromZone(classHashPrototype, 128,
1246 nil, _objc_internal_zone());
1249 if ((oldCls = (Class)NXHashGet(class_hash, newCls)) ||
1250 (oldCls = (Class)NXHashGet(unconnected_class_hash, newCls)))
1252 // Another class with this name exists. Complain and reject.
1253 inform_duplicate(newCls->name, oldCls, newCls);
1257 NXHashInsert(unconnected_class_hash, newCls);
1261 mutex_unlock(&classLock);
1264 // Attach pended categories for this class, if any
1265 resolve_categories_for_class(newCls);
1272 /***********************************************************************
1273 * _objc_connect_classes_from_image.
1274 * Connect the classes in the given image to their superclasses,
1275 * or register them for later connection if any superclasses are missing.
1276 **********************************************************************/
1277 static void _objc_connect_classes_from_image(header_info *hi)
1282 BOOL replacement = _objcHeaderIsReplacement(hi);
1284 // Major loop - process all modules in the image
1286 for (midx = 0; midx < hi->mod_count; midx += 1)
1288 // Skip module containing no classes
1289 if (mods[midx].symtab == nil)
1292 // Minor loop - process all the classes in given module
1293 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
1295 Class cls = (Class)mods[midx].symtab->defs[index];
1296 if (! replacement) {
1298 Class futureCls = getFutureClassForOriginalClass(cls);
1300 // objc_getFutureClass() requested a different class
1301 // struct. Fix up the original struct's superclass
1302 // field for [super ...] use, but otherwise perform
1303 // fixups on the new class struct only.
1304 const char *super_name = (const char *) cls->superclass;
1305 if (super_name) cls->superclass = objc_getClass(super_name);
1308 connected = connect_class(cls);
1309 if (connected && callbackFunction) {
1310 (*callbackFunction)(cls, 0);
1313 // Replacement image - fix up superclass only (#3704817)
1314 // And metaclass's superclass (#5351107)
1315 const char *super_name = (const char *) cls->superclass;
1317 cls->superclass = objc_getClass(super_name);
1318 // metaclass's superclass is superclass's metaclass
1319 cls->ISA()->superclass = cls->superclass->ISA();
1321 // Replacement for a root class
1322 // cls->superclass already nil
1323 // root metaclass's superclass is root class
1324 cls->ISA()->superclass = cls;
1332 /***********************************************************************
1333 * _objc_map_class_refs_for_image. Convert the class ref entries from
1334 * a class name string pointer to a class pointer. If the class does
1335 * not yet exist, the reference is added to a list of pending references
1336 * to be fixed up at a later date.
1337 **********************************************************************/
1338 static void fix_class_ref(Class *ref, const char *name, BOOL isMeta)
1342 // Get pointer to class of this name
1343 // NO unconnected, YES class loader
1344 // (real class with weak-missing superclass is unconnected now)
1345 cls = look_up_class(name, NO, YES);
1347 // Referenced class exists. Fix up the reference.
1348 *ref = isMeta ? cls->ISA() : cls;
1350 // Referenced class does not exist yet. Insert nil for now
1351 // (weak-linking) and fix up the reference if the class arrives later.
1352 pendClassReference (ref, name, isMeta);
1357 static void _objc_map_class_refs_for_image (header_info * hi)
1363 // Locate class refs in image
1364 cls_refs = _getObjcClassRefs (hi, &count);
1366 // Process each class ref
1367 for (index = 0; index < count; index += 1) {
1368 // Ref is initially class name char*
1369 const char *name = (const char *) cls_refs[index];
1370 if (!name) continue;
1371 fix_class_ref(&cls_refs[index], name, NO /*never meta*/);
1377 /***********************************************************************
1378 * _objc_remove_pending_class_refs_in_image
1379 * Delete any pending class ref fixups for class refs in the given image,
1380 * because the image is about to be unloaded.
1381 **********************************************************************/
1382 static void removePendingReferences(Class *refs, size_t count)
1384 Class *end = refs + count;
1387 if (!pendingClassRefsMap) return;
1389 // Search the pending class ref table for class refs in this range.
1390 // The class refs may have already been stomped with nil,
1391 // so there's no way to recover the original class name.
1395 PendingClassRef *pending;
1396 NXMapState state = NXInitMapState(pendingClassRefsMap);
1397 while(NXNextMapState(pendingClassRefsMap, &state,
1398 (const void **)&key, (const void **)&pending))
1400 for ( ; pending != nil; pending = pending->next) {
1401 if (pending->ref >= refs && pending->ref < end) {
1409 static void _objc_remove_pending_class_refs_in_image(header_info *hi)
1414 // Locate class refs in this image
1415 cls_refs = _getObjcClassRefs(hi, &count);
1416 removePendingReferences(cls_refs, count);
1420 /***********************************************************************
1421 * map_selrefs. For each selector in the specified array,
1422 * replace the name pointer with a uniqued selector.
1423 * If copy is TRUE, all selector data is always copied. This is used
1424 * for registering selectors from unloadable bundles, so the selector
1425 * can still be used after the bundle's data segment is unmapped.
1426 * Returns YES if dst was written to, NO if it was unchanged.
1427 **********************************************************************/
1428 static inline void map_selrefs(SEL *sels, size_t count, BOOL copy)
1436 // Process each selector
1437 for (index = 0; index < count; index += 1)
1441 // Lookup pointer to uniqued string
1442 sel = sel_registerNameNoLock((const char *) sels[index], copy);
1444 // Replace this selector with uniqued one (avoid
1445 // modifying the VM page if this would be a NOP)
1446 if (sels[index] != sel) {
1455 /***********************************************************************
1456 * map_method_descs. For each method in the specified method list,
1457 * replace the name pointer with a uniqued selector.
1458 * If copy is TRUE, all selector data is always copied. This is used
1459 * for registering selectors from unloadable bundles, so the selector
1460 * can still be used after the bundle's data segment is unmapped.
1461 **********************************************************************/
1462 static void map_method_descs (struct objc_method_description_list * methods, BOOL copy)
1466 if (!methods) return;
1470 // Process each method
1471 for (index = 0; index < methods->count; index += 1)
1473 struct objc_method_description * method;
1476 // Get method entry to fix up
1477 method = &methods->list[index];
1479 // Lookup pointer to uniqued string
1480 sel = sel_registerNameNoLock((const char *) method->name, copy);
1482 // Replace this selector with uniqued one (avoid
1483 // modifying the VM page if this would be a NOP)
1484 if (method->name != sel)
1492 /***********************************************************************
1494 * Returns the protocol extension for the given protocol.
1495 * Returns nil if the protocol has no extension.
1496 **********************************************************************/
1497 static old_protocol_ext *ext_for_protocol(old_protocol *proto)
1499 if (!proto) return nil;
1500 if (!protocol_ext_map) return nil;
1501 else return (old_protocol_ext *)NXMapGet(protocol_ext_map, proto);
1505 /***********************************************************************
1507 * Search a protocol method list for a selector.
1508 **********************************************************************/
1509 static struct objc_method_description *
1510 lookup_method(struct objc_method_description_list *mlist, SEL aSel)
1514 for (i = 0; i < mlist->count; i++) {
1515 if (mlist->list[i].name == aSel) {
1516 return mlist->list+i;
1524 /***********************************************************************
1525 * lookup_protocol_method
1526 * Search for a selector in a protocol
1527 * (and optionally recursively all incorporated protocols)
1528 **********************************************************************/
1529 struct objc_method_description *
1530 lookup_protocol_method(old_protocol *proto, SEL aSel,
1531 BOOL isRequiredMethod, BOOL isInstanceMethod,
1534 struct objc_method_description *m = nil;
1535 old_protocol_ext *ext;
1537 if (isRequiredMethod) {
1538 if (isInstanceMethod) {
1539 m = lookup_method(proto->instance_methods, aSel);
1541 m = lookup_method(proto->class_methods, aSel);
1543 } else if ((ext = ext_for_protocol(proto))) {
1544 if (isInstanceMethod) {
1545 m = lookup_method(ext->optional_instance_methods, aSel);
1547 m = lookup_method(ext->optional_class_methods, aSel);
1551 if (!m && recursive && proto->protocol_list) {
1553 for (i = 0; !m && i < proto->protocol_list->count; i++) {
1554 m = lookup_protocol_method(proto->protocol_list->list[i], aSel,
1555 isRequiredMethod,isInstanceMethod,true);
1563 /***********************************************************************
1565 * Returns the name of the given protocol.
1566 **********************************************************************/
1567 const char *protocol_getName(Protocol *p)
1569 old_protocol *proto = oldprotocol(p);
1570 if (!proto) return "nil";
1571 return proto->protocol_name;
1575 /***********************************************************************
1576 * protocol_getMethodDescription
1577 * Returns the description of a named method.
1578 * Searches either required or optional methods.
1579 * Searches either instance or class methods.
1580 **********************************************************************/
1581 struct objc_method_description
1582 protocol_getMethodDescription(Protocol *p, SEL aSel,
1583 BOOL isRequiredMethod, BOOL isInstanceMethod)
1585 struct objc_method_description empty = {nil, nil};
1586 old_protocol *proto = oldprotocol(p);
1587 struct objc_method_description *desc;
1588 if (!proto) return empty;
1590 desc = lookup_protocol_method(proto, aSel,
1591 isRequiredMethod, isInstanceMethod, true);
1592 if (desc) return *desc;
1597 /***********************************************************************
1598 * protocol_copyMethodDescriptionList
1599 * Returns an array of method descriptions from a protocol.
1600 * Copies either required or optional methods.
1601 * Copies either instance or class methods.
1602 **********************************************************************/
1603 struct objc_method_description *
1604 protocol_copyMethodDescriptionList(Protocol *p,
1605 BOOL isRequiredMethod,
1606 BOOL isInstanceMethod,
1607 unsigned int *outCount)
1609 struct objc_method_description_list *mlist = nil;
1610 old_protocol *proto = oldprotocol(p);
1611 old_protocol_ext *ext;
1612 unsigned int i, count;
1613 struct objc_method_description *result;
1616 if (outCount) *outCount = 0;
1620 if (isRequiredMethod) {
1621 if (isInstanceMethod) {
1622 mlist = proto->instance_methods;
1624 mlist = proto->class_methods;
1626 } else if ((ext = ext_for_protocol(proto))) {
1627 if (isInstanceMethod) {
1628 mlist = ext->optional_instance_methods;
1630 mlist = ext->optional_class_methods;
1635 if (outCount) *outCount = 0;
1639 count = mlist->count;
1640 result = (struct objc_method_description *)
1641 calloc(count + 1, sizeof(struct objc_method_description));
1642 for (i = 0; i < count; i++) {
1643 result[i] = mlist->list[i];
1646 if (outCount) *outCount = count;
1651 objc_property_t protocol_getProperty(Protocol *p, const char *name,
1652 BOOL isRequiredProperty, BOOL isInstanceProperty)
1654 old_protocol *proto = oldprotocol(p);
1655 old_protocol_ext *ext;
1656 old_protocol_list *proto_list;
1658 if (!proto || !name) return nil;
1660 if (!isRequiredProperty || !isInstanceProperty) {
1661 // Only required instance properties are currently supported
1665 if ((ext = ext_for_protocol(proto))) {
1666 old_property_list *plist;
1667 if ((plist = ext->instance_properties)) {
1669 for (i = 0; i < plist->count; i++) {
1670 old_property *prop = property_list_nth(plist, i);
1671 if (0 == strcmp(name, prop->name)) {
1672 return (objc_property_t)prop;
1678 if ((proto_list = proto->protocol_list)) {
1680 for (i = 0; i < proto_list->count; i++) {
1681 objc_property_t prop =
1682 protocol_getProperty((Protocol *)proto_list->list[i], name,
1683 isRequiredProperty, isInstanceProperty);
1684 if (prop) return prop;
1692 objc_property_t *protocol_copyPropertyList(Protocol *p, unsigned int *outCount)
1694 old_property **result = nil;
1695 old_protocol_ext *ext;
1696 old_property_list *plist;
1698 old_protocol *proto = oldprotocol(p);
1699 if (! (ext = ext_for_protocol(proto))) {
1700 if (outCount) *outCount = 0;
1704 plist = ext->instance_properties;
1705 result = copyPropertyList(plist, outCount);
1707 return (objc_property_t *)result;
1711 /***********************************************************************
1712 * protocol_copyProtocolList
1713 * Copies this protocol's incorporated protocols.
1714 * Does not copy those protocol's incorporated protocols in turn.
1715 **********************************************************************/
1716 Protocol * __unsafe_unretained *
1717 protocol_copyProtocolList(Protocol *p, unsigned int *outCount)
1719 unsigned int count = 0;
1720 Protocol **result = nil;
1721 old_protocol *proto = oldprotocol(p);
1724 if (outCount) *outCount = 0;
1728 if (proto->protocol_list) {
1729 count = (unsigned int)proto->protocol_list->count;
1733 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
1735 for (i = 0; i < count; i++) {
1736 result[i] = (Protocol *)proto->protocol_list->list[i];
1741 if (outCount) *outCount = count;
1746 BOOL protocol_conformsToProtocol(Protocol *self_gen, Protocol *other_gen)
1748 old_protocol *self = oldprotocol(self_gen);
1749 old_protocol *other = oldprotocol(other_gen);
1751 if (!self || !other) {
1755 if (0 == strcmp(self->protocol_name, other->protocol_name)) {
1759 if (self->protocol_list) {
1761 for (i = 0; i < self->protocol_list->count; i++) {
1762 old_protocol *proto = self->protocol_list->list[i];
1763 if (0 == strcmp(other->protocol_name, proto->protocol_name)) {
1766 if (protocol_conformsToProtocol((Protocol *)proto, other_gen)) {
1776 BOOL protocol_isEqual(Protocol *self, Protocol *other)
1778 if (self == other) return YES;
1779 if (!self || !other) return NO;
1781 if (!protocol_conformsToProtocol(self, other)) return NO;
1782 if (!protocol_conformsToProtocol(other, self)) return NO;
1788 /***********************************************************************
1789 * _protocol_getMethodTypeEncoding
1790 * Return the @encode string for the requested protocol method.
1791 * Returns nil if the compiler did not emit any extended @encode data.
1792 * Locking: runtimeLock must not be held by the caller
1793 **********************************************************************/
1795 _protocol_getMethodTypeEncoding(Protocol *proto_gen, SEL sel,
1796 BOOL isRequiredMethod, BOOL isInstanceMethod)
1798 old_protocol *proto = oldprotocol(proto_gen);
1799 if (!proto) return nil;
1800 old_protocol_ext *ext = ext_for_protocol(proto);
1801 if (!ext) return nil;
1802 if (ext->size < offsetof(old_protocol_ext, extendedMethodTypes) + sizeof(ext->extendedMethodTypes)) return nil;
1803 if (! ext->extendedMethodTypes) return nil;
1805 struct objc_method_description *m =
1806 lookup_protocol_method(proto, sel,
1807 isRequiredMethod, isInstanceMethod, false);
1809 // No method with that name. Search incorporated protocols.
1810 if (proto->protocol_list) {
1811 for (int i = 0; i < proto->protocol_list->count; i++) {
1813 _protocol_getMethodTypeEncoding((Protocol *)proto->protocol_list->list[i], sel, isRequiredMethod, isInstanceMethod);
1814 if (enc) return enc;
1821 if (isRequiredMethod && isInstanceMethod) {
1822 i += ((uintptr_t)m - (uintptr_t)proto->instance_methods) / sizeof(proto->instance_methods->list[0]);
1824 } else if (proto->instance_methods) {
1825 i += proto->instance_methods->count;
1828 if (isRequiredMethod && !isInstanceMethod) {
1829 i += ((uintptr_t)m - (uintptr_t)proto->class_methods) / sizeof(proto->class_methods->list[0]);
1831 } else if (proto->class_methods) {
1832 i += proto->class_methods->count;
1835 if (!isRequiredMethod && isInstanceMethod) {
1836 i += ((uintptr_t)m - (uintptr_t)ext->optional_instance_methods) / sizeof(ext->optional_instance_methods->list[0]);
1838 } else if (ext->optional_instance_methods) {
1839 i += ext->optional_instance_methods->count;
1842 if (!isRequiredMethod && !isInstanceMethod) {
1843 i += ((uintptr_t)m - (uintptr_t)ext->optional_class_methods) / sizeof(ext->optional_class_methods->list[0]);
1845 } else if (ext->optional_class_methods) {
1846 i += ext->optional_class_methods->count;
1850 return ext->extendedMethodTypes[i];
1854 /***********************************************************************
1855 * objc_allocateProtocol
1856 * Creates a new protocol. The protocol may not be used until
1857 * objc_registerProtocol() is called.
1858 * Returns nil if a protocol with the same name already exists.
1859 * Locking: acquires classLock
1860 **********************************************************************/
1862 objc_allocateProtocol(const char *name)
1864 Class cls = objc_getClass("__IncompleteProtocol");
1866 mutex_lock(&classLock);
1868 if (NXMapGet(protocol_map, name)) {
1869 mutex_unlock(&classLock);
1873 old_protocol *result = (old_protocol *)
1874 _calloc_internal(1, sizeof(old_protocol)
1875 + sizeof(old_protocol_ext));
1876 old_protocol_ext *ext = (old_protocol_ext *)(result+1);
1879 result->protocol_name = _strdup_internal(name);
1880 ext->size = sizeof(old_protocol_ext);
1882 // fixme reserve name without installing
1884 NXMapInsert(protocol_ext_map, result, result+1);
1886 mutex_unlock(&classLock);
1888 return (Protocol *)result;
1892 /***********************************************************************
1893 * objc_registerProtocol
1894 * Registers a newly-constructed protocol. The protocol is now
1895 * ready for use and immutable.
1896 * Locking: acquires classLock
1897 **********************************************************************/
1898 void objc_registerProtocol(Protocol *proto_gen)
1900 old_protocol *proto = oldprotocol(proto_gen);
1902 Class oldcls = objc_getClass("__IncompleteProtocol");
1903 Class cls = objc_getClass("Protocol");
1905 mutex_lock(&classLock);
1907 if (proto->isa == cls) {
1908 _objc_inform("objc_registerProtocol: protocol '%s' was already "
1909 "registered!", proto->protocol_name);
1910 mutex_unlock(&classLock);
1913 if (proto->isa != oldcls) {
1914 _objc_inform("objc_registerProtocol: protocol '%s' was not allocated "
1915 "with objc_allocateProtocol!", proto->protocol_name);
1916 mutex_unlock(&classLock);
1922 NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto);
1924 mutex_unlock(&classLock);
1928 /***********************************************************************
1929 * protocol_addProtocol
1930 * Adds an incorporated protocol to another protocol.
1931 * No method enforcement is performed.
1932 * `proto` must be under construction. `addition` must not.
1933 * Locking: acquires classLock
1934 **********************************************************************/
1936 protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen)
1938 old_protocol *proto = oldprotocol(proto_gen);
1939 old_protocol *addition = oldprotocol(addition_gen);
1941 Class cls = objc_getClass("__IncompleteProtocol");
1943 if (!proto_gen) return;
1944 if (!addition_gen) return;
1946 mutex_lock(&classLock);
1948 if (proto->isa != cls) {
1949 _objc_inform("protocol_addProtocol: modified protocol '%s' is not "
1950 "under construction!", proto->protocol_name);
1951 mutex_unlock(&classLock);
1954 if (addition->isa == cls) {
1955 _objc_inform("protocol_addProtocol: added protocol '%s' is still "
1956 "under construction!", addition->protocol_name);
1957 mutex_unlock(&classLock);
1961 old_protocol_list *protolist = proto->protocol_list;
1963 size_t size = sizeof(old_protocol_list)
1964 + protolist->count * sizeof(protolist->list[0]);
1965 protolist = (old_protocol_list *)
1966 _realloc_internal(protolist, size);
1968 protolist = (old_protocol_list *)
1969 _calloc_internal(1, sizeof(old_protocol_list));
1972 protolist->list[protolist->count++] = addition;
1973 proto->protocol_list = protolist;
1975 mutex_unlock(&classLock);
1979 /***********************************************************************
1980 * protocol_addMethodDescription
1981 * Adds a method to a protocol. The protocol must be under construction.
1982 * Locking: acquires classLock
1983 **********************************************************************/
1985 _protocol_addMethod(struct objc_method_description_list **list, SEL name, const char *types)
1988 *list = (struct objc_method_description_list *)
1989 _calloc_internal(sizeof(struct objc_method_description_list), 1);
1991 size_t size = sizeof(struct objc_method_description_list)
1992 + (*list)->count * sizeof(struct objc_method_description);
1993 *list = (struct objc_method_description_list *)
1994 _realloc_internal(*list, size);
1997 struct objc_method_description *desc = &(*list)->list[(*list)->count++];
1999 desc->types = _strdup_internal(types ?: "");
2003 protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types,
2004 BOOL isRequiredMethod, BOOL isInstanceMethod)
2006 old_protocol *proto = oldprotocol(proto_gen);
2008 Class cls = objc_getClass("__IncompleteProtocol");
2010 if (!proto_gen) return;
2012 mutex_lock(&classLock);
2014 if (proto->isa != cls) {
2015 _objc_inform("protocol_addMethodDescription: protocol '%s' is not "
2016 "under construction!", proto->protocol_name);
2017 mutex_unlock(&classLock);
2021 if (isRequiredMethod && isInstanceMethod) {
2022 _protocol_addMethod(&proto->instance_methods, name, types);
2023 } else if (isRequiredMethod && !isInstanceMethod) {
2024 _protocol_addMethod(&proto->class_methods, name, types);
2025 } else if (!isRequiredMethod && isInstanceMethod) {
2026 old_protocol_ext *ext = (old_protocol_ext *)(proto+1);
2027 _protocol_addMethod(&ext->optional_instance_methods, name, types);
2028 } else /* !isRequiredMethod && !isInstanceMethod) */ {
2029 old_protocol_ext *ext = (old_protocol_ext *)(proto+1);
2030 _protocol_addMethod(&ext->optional_class_methods, name, types);
2033 mutex_unlock(&classLock);
2037 /***********************************************************************
2038 * protocol_addProperty
2039 * Adds a property to a protocol. The protocol must be under construction.
2040 * Locking: acquires classLock
2041 **********************************************************************/
2043 _protocol_addProperty(old_property_list **plist, const char *name,
2044 const objc_property_attribute_t *attrs,
2048 *plist = (old_property_list *)
2049 _calloc_internal(sizeof(old_property_list), 1);
2050 (*plist)->entsize = sizeof(old_property);
2052 *plist = (old_property_list *)
2053 _realloc_internal(*plist, sizeof(old_property_list)
2054 + (*plist)->count * (*plist)->entsize);
2057 old_property *prop = property_list_nth(*plist, (*plist)->count++);
2058 prop->name = _strdup_internal(name);
2059 prop->attributes = copyPropertyAttributeString(attrs, count);
2063 protocol_addProperty(Protocol *proto_gen, const char *name,
2064 const objc_property_attribute_t *attrs,
2066 BOOL isRequiredProperty, BOOL isInstanceProperty)
2068 old_protocol *proto = oldprotocol(proto_gen);
2070 Class cls = objc_getClass("__IncompleteProtocol");
2075 mutex_lock(&classLock);
2077 if (proto->isa != cls) {
2078 _objc_inform("protocol_addProperty: protocol '%s' is not "
2079 "under construction!", proto->protocol_name);
2080 mutex_unlock(&classLock);
2084 old_protocol_ext *ext = ext_for_protocol(proto);
2086 if (isRequiredProperty && isInstanceProperty) {
2087 _protocol_addProperty(&ext->instance_properties, name, attrs, count);
2089 //else if (isRequiredProperty && !isInstanceProperty) {
2090 // _protocol_addProperty(&ext->class_properties, name, attrs, count);
2091 //} else if (!isRequiredProperty && isInstanceProperty) {
2092 // _protocol_addProperty(&ext->optional_instance_properties, name, attrs, count);
2093 //} else /* !isRequiredProperty && !isInstanceProperty) */ {
2094 // _protocol_addProperty(&ext->optional_class_properties, name, attrs, count);
2097 mutex_unlock(&classLock);
2101 /***********************************************************************
2102 * _objc_fixup_protocol_objects_for_image. For each protocol in the
2103 * specified image, selectorize the method names and add to the protocol hash.
2104 **********************************************************************/
2106 static BOOL versionIsExt(uintptr_t version, const char *names, size_t size)
2108 // CodeWarrior used isa field for string "Protocol"
2109 // from section __OBJC,__class_names. rdar://4951638
2110 // gcc (10.4 and earlier) used isa field for version number;
2111 // the only version number used on Mac OS X was 2.
2112 // gcc (10.5 and later) uses isa field for ext pointer
2114 if (version < PAGE_SIZE) {
2118 if (version >= (uintptr_t)names && version < (uintptr_t)(names + size)) {
2125 static void fix_protocol(old_protocol *proto, Class protocolClass,
2126 BOOL isBundle, const char *names, size_t names_size)
2131 version = (uintptr_t)proto->isa;
2133 // Set the protocol's isa
2134 proto->isa = protocolClass;
2136 // Fix up method lists
2137 // fixme share across duplicates
2138 map_method_descs (proto->instance_methods, isBundle);
2139 map_method_descs (proto->class_methods, isBundle);
2141 // Fix up ext, if any
2142 if (versionIsExt(version, names, names_size)) {
2143 old_protocol_ext *ext = (old_protocol_ext *)version;
2144 NXMapInsert(protocol_ext_map, proto, ext);
2145 map_method_descs (ext->optional_instance_methods, isBundle);
2146 map_method_descs (ext->optional_class_methods, isBundle);
2149 // Record the protocol it if we don't have one with this name yet
2150 // fixme bundles - copy protocol
2152 if (!NXMapGet(protocol_map, proto->protocol_name)) {
2153 NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto);
2154 if (PrintProtocols) {
2155 _objc_inform("PROTOCOLS: protocol at %p is %s",
2156 proto, proto->protocol_name);
2159 // duplicate - do nothing
2160 if (PrintProtocols) {
2161 _objc_inform("PROTOCOLS: protocol at %p is %s (duplicate)",
2162 proto, proto->protocol_name);
2167 static void _objc_fixup_protocol_objects_for_image (header_info * hi)
2169 Class protocolClass = objc_getClass("Protocol");
2171 old_protocol **protos;
2172 int isBundle = headerIsBundle(hi);
2176 mutex_lock(&classLock);
2178 // Allocate the protocol registry if necessary.
2179 if (!protocol_map) {
2181 NXCreateMapTableFromZone(NXStrValueMapPrototype, 32,
2182 _objc_internal_zone());
2184 if (!protocol_ext_map) {
2186 NXCreateMapTableFromZone(NXPtrValueMapPrototype, 32,
2187 _objc_internal_zone());
2190 protos = _getObjcProtocols(hi, &count);
2191 names = _getObjcClassNames(hi, &names_size);
2192 for (i = 0; i < count; i++) {
2193 fix_protocol(protos[i], protocolClass, isBundle, names, names_size);
2196 mutex_unlock(&classLock);
2200 /***********************************************************************
2201 * _objc_fixup_selector_refs. Register all of the selectors in each
2202 * image, and fix them all up.
2203 **********************************************************************/
2204 static void _objc_fixup_selector_refs (const header_info *hi)
2210 if (sel_preoptimizationValid(hi)) {
2211 _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors in %s",
2214 else if (_objcHeaderOptimizedByDyld(hi)) {
2215 _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors in %s",
2220 if (sel_preoptimizationValid(hi)) return;
2222 sels = _getObjcSelectorRefs (hi, &count);
2224 map_selrefs(sels, count, headerIsBundle(hi));
2227 static inline BOOL _is_threaded() {
2231 return pthread_is_threaded_np() != 0;
2235 #if !TARGET_OS_WIN32
2236 /***********************************************************************
2238 * Process the given image which is about to be unmapped by dyld.
2239 * mh is mach_header instead of headerType because that's what
2240 * dyld_priv.h says even for 64-bit.
2241 **********************************************************************/
2243 unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide)
2245 recursive_mutex_lock(&loadMethodLock);
2246 unmap_image_nolock(mh);
2247 recursive_mutex_unlock(&loadMethodLock);
2251 /***********************************************************************
2253 * Process the given images which are being mapped in by dyld.
2254 * Calls ABI-agnostic code after taking ABI-specific locks.
2255 **********************************************************************/
2257 map_images(enum dyld_image_states state, uint32_t infoCount,
2258 const struct dyld_image_info infoList[])
2262 recursive_mutex_lock(&loadMethodLock);
2263 err = map_images_nolock(state, infoCount, infoList);
2264 recursive_mutex_unlock(&loadMethodLock);
2270 /***********************************************************************
2272 * Process +load in the given images which are being mapped in by dyld.
2273 * Calls ABI-agnostic code after taking ABI-specific locks.
2275 * Locking: acquires classLock and loadMethodLock
2276 **********************************************************************/
2278 load_images(enum dyld_image_states state, uint32_t infoCount,
2279 const struct dyld_image_info infoList[])
2283 recursive_mutex_lock(&loadMethodLock);
2285 // Discover +load methods
2286 found = load_images_nolock(state, infoCount, infoList);
2288 // Call +load methods (without classLock - re-entrant)
2290 call_load_methods();
2293 recursive_mutex_unlock(&loadMethodLock);
2300 /***********************************************************************
2302 * Perform metadata processing for hCount images starting with firstNewHeader
2303 **********************************************************************/
2304 void _read_images(header_info **hList, uint32_t hCount)
2307 BOOL categoriesLoaded = NO;
2309 if (!class_hash) _objc_init_class_hash();
2311 // Parts of this order are important for correctness or performance.
2313 // Read classes from all images.
2314 for (i = 0; i < hCount; i++) {
2315 _objc_read_classes_from_image(hList[i]);
2318 // Read categories from all images.
2319 // But not if any other threads are running - they might
2320 // call a category method before the fixups below are complete.
2321 if (!_is_threaded()) {
2322 BOOL needFlush = NO;
2323 for (i = 0; i < hCount; i++) {
2324 needFlush |= _objc_read_categories_from_image(hList[i]);
2326 if (needFlush) flush_marked_caches();
2327 categoriesLoaded = YES;
2330 // Connect classes from all images.
2331 for (i = 0; i < hCount; i++) {
2332 _objc_connect_classes_from_image(hList[i]);
2335 // Fix up class refs, selector refs, and protocol objects from all images.
2336 for (i = 0; i < hCount; i++) {
2337 _objc_map_class_refs_for_image(hList[i]);
2338 _objc_fixup_selector_refs(hList[i]);
2339 _objc_fixup_protocol_objects_for_image(hList[i]);
2342 // Read categories from all images.
2343 // But not if this is the only thread - it's more
2344 // efficient to attach categories earlier if safe.
2345 if (!categoriesLoaded) {
2346 BOOL needFlush = NO;
2347 for (i = 0; i < hCount; i++) {
2348 needFlush |= _objc_read_categories_from_image(hList[i]);
2350 if (needFlush) flush_marked_caches();
2353 // Multi-threaded category load MUST BE LAST to avoid a race.
2357 /***********************************************************************
2358 * prepare_load_methods
2359 * Schedule +load for classes in this image, any un-+load-ed
2360 * superclasses in other images, and any categories in this image.
2361 **********************************************************************/
2362 // Recursively schedule +load for cls and any un-+load-ed superclasses.
2363 // cls must already be connected.
2364 static void schedule_class_load(Class cls)
2366 if (cls->info & CLS_LOADED) return;
2367 if (cls->superclass) schedule_class_load(cls->superclass);
2368 add_class_to_loadable_list(cls);
2369 cls->info |= CLS_LOADED;
2372 void prepare_load_methods(header_info *hi)
2378 if (_objcHeaderIsReplacement(hi)) {
2379 // Ignore any classes in this image
2383 // Major loop - process all modules in the image
2385 for (midx = 0; midx < hi->mod_count; midx += 1)
2389 // Skip module containing no classes
2390 if (mods[midx].symtab == nil)
2393 // Minor loop - process all the classes in given module
2394 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
2396 // Locate the class description pointer
2397 Class cls = (Class)mods[midx].symtab->defs[index];
2398 if (cls->info & CLS_CONNECTED) {
2399 schedule_class_load(cls);
2405 // Major loop - process all modules in the header
2408 // NOTE: The module and category lists are traversed backwards
2409 // to preserve the pre-10.4 processing order. Changing the order
2410 // would have a small chance of introducing binary compatibility bugs.
2411 midx = (unsigned int)hi->mod_count;
2412 while (midx-- > 0) {
2415 Symtab symtab = mods[midx].symtab;
2417 // Nothing to do for a module without a symbol table
2418 if (mods[midx].symtab == nil)
2420 // Total entries in symbol table (class entries followed
2421 // by category entries)
2422 total = mods[midx].symtab->cls_def_cnt +
2423 mods[midx].symtab->cat_def_cnt;
2425 // Minor loop - register all categories from given module
2427 while (index-- > mods[midx].symtab->cls_def_cnt) {
2428 old_category *cat = (old_category *)symtab->defs[index];
2429 add_category_to_loadable_list((Category)cat);
2437 void unload_class(Class cls)
2443 /***********************************************************************
2444 * _objc_remove_classes_in_image
2445 * Remove all classes in the given image from the runtime, because
2446 * the image is about to be unloaded.
2447 * Things to clean up:
2449 * unconnected_class_hash
2450 * pending subclasses list (only if class is still unconnected)
2451 * loadable class list
2452 * class's method caches
2453 * class refs in all other images
2454 **********************************************************************/
2455 // Re-pend any class references in refs that point into [start..end)
2456 static void rependClassReferences(Class *refs, size_t count,
2457 uintptr_t start, uintptr_t end)
2463 // Process each class ref
2464 for (i = 0; i < count; i++) {
2465 if ((uintptr_t)(refs[i]) >= start && (uintptr_t)(refs[i]) < end) {
2466 pendClassReference(&refs[i], refs[i]->name,
2467 (refs[i]->info & CLS_META) ? YES : NO);
2474 void try_free(const void *p)
2476 if (p && malloc_size(p)) free((void *)p);
2479 // Deallocate all memory in a method list
2480 static void unload_mlist(old_method_list *mlist)
2483 for (i = 0; i < mlist->method_count; i++) {
2484 try_free(mlist->method_list[i].method_types);
2489 static void unload_property_list(old_property_list *proplist)
2493 if (!proplist) return;
2495 for (i = 0; i < proplist->count; i++) {
2496 old_property *prop = property_list_nth(proplist, i);
2497 try_free(prop->name);
2498 try_free(prop->attributes);
2504 // Deallocate all memory in a class.
2505 void unload_class(Class cls)
2507 // Free method cache
2508 // This dereferences the cache contents; do this before freeing methods
2509 if (cls->cache && cls->cache != &_objc_empty_cache) {
2510 _cache_free(cls->cache);
2516 for (i = 0; i < cls->ivars->ivar_count; i++) {
2517 try_free(cls->ivars->ivar_list[i].ivar_name);
2518 try_free(cls->ivars->ivar_list[i].ivar_type);
2520 try_free(cls->ivars);
2523 // Free fixed-up method lists and method list array
2524 if (cls->methodLists) {
2525 // more than zero method lists
2526 if (cls->info & CLS_NO_METHOD_ARRAY) {
2528 unload_mlist((old_method_list *)cls->methodLists);
2531 // more than one method list
2532 old_method_list **mlistp;
2533 for (mlistp = cls->methodLists;
2534 *mlistp != nil && *mlistp != END_OF_METHODS_LIST;
2537 unload_mlist(*mlistp);
2539 free(cls->methodLists);
2543 // Free protocol list
2544 old_protocol_list *protos = cls->protocols;
2546 old_protocol_list *dead = protos;
2547 protos = protos->next;
2551 if ((cls->info & CLS_EXT)) {
2553 // Free property lists and property list array
2554 if (cls->ext->propertyLists) {
2555 // more than zero property lists
2556 if (cls->info & CLS_NO_PROPERTY_ARRAY) {
2557 // one property list
2558 old_property_list *proplist =
2559 (old_property_list *)cls->ext->propertyLists;
2560 unload_property_list(proplist);
2562 // more than one property list
2563 old_property_list **plistp;
2564 for (plistp = cls->ext->propertyLists;
2568 unload_property_list(*plistp);
2570 try_free(cls->ext->propertyLists);
2574 // Free weak ivar layout
2575 try_free(cls->ext->weak_ivar_layout);
2581 // Free non-weak ivar layout
2582 try_free(cls->ivar_layout);
2586 try_free(cls->name);
2593 static void _objc_remove_classes_in_image(header_info *hi)
2599 mutex_lock(&classLock);
2601 // Major loop - process all modules in the image
2603 for (midx = 0; midx < hi->mod_count; midx += 1)
2605 // Skip module containing no classes
2606 if (mods[midx].symtab == nil)
2609 // Minor loop - process all the classes in given module
2610 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
2614 // Locate the class description pointer
2615 cls = (Class)mods[midx].symtab->defs[index];
2617 // Remove from loadable class list, if present
2618 remove_class_from_loadable_list(cls);
2620 // Remove from unconnected_class_hash and pending subclasses
2621 if (unconnected_class_hash && NXHashMember(unconnected_class_hash, cls)) {
2622 NXHashRemove(unconnected_class_hash, cls);
2623 if (pendingSubclassesMap) {
2624 // Find this class in its superclass's pending list
2625 char *supercls_name = (char *)cls->superclass;
2626 PendingSubclass *pending = (PendingSubclass *)
2627 NXMapGet(pendingSubclassesMap, supercls_name);
2628 for ( ; pending != nil; pending = pending->next) {
2629 if (pending->subclass == cls) {
2630 pending->subclass = Nil;
2637 // Remove from class_hash
2638 NXHashRemove(class_hash, cls);
2639 objc_removeRegisteredClass(cls);
2641 // Free heap memory pointed to by the class
2642 unload_class(cls->ISA());
2648 // Search all other images for class refs that point back to this range.
2649 // Un-fix and re-pend any such class refs.
2651 // Get the location of the dying image's __OBJC segment
2653 unsigned long seg_size;
2654 seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size);
2656 header_info *other_hi;
2657 for (other_hi = FirstHeader; other_hi != nil; other_hi = other_hi->next) {
2660 if (other_hi == hi) continue; // skip the image being unloaded
2662 // Fix class refs in the other image
2663 other_refs = _getObjcClassRefs(other_hi, &count);
2664 rependClassReferences(other_refs, count, seg, seg+seg_size);
2667 mutex_unlock(&classLock);
2671 /***********************************************************************
2672 * _objc_remove_categories_in_image
2673 * Remove all categories in the given image from the runtime, because
2674 * the image is about to be unloaded.
2675 * Things to clean up:
2676 * unresolved category list
2677 * loadable category list
2678 **********************************************************************/
2679 static void _objc_remove_categories_in_image(header_info *hi)
2684 // Major loop - process all modules in the header
2687 for (midx = 0; midx < hi->mod_count; midx++) {
2690 Symtab symtab = mods[midx].symtab;
2692 // Nothing to do for a module without a symbol table
2693 if (symtab == nil) continue;
2695 // Total entries in symbol table (class entries followed
2696 // by category entries)
2697 total = symtab->cls_def_cnt + symtab->cat_def_cnt;
2699 // Minor loop - check all categories from given module
2700 for (index = symtab->cls_def_cnt; index < total; index++) {
2701 old_category *cat = (old_category *)symtab->defs[index];
2703 // Clean up loadable category list
2704 remove_category_from_loadable_list((Category)cat);
2706 // Clean up category_hash
2707 if (category_hash) {
2708 _objc_unresolved_category *cat_entry = (_objc_unresolved_category *)NXMapGet(category_hash, cat->class_name);
2709 for ( ; cat_entry != nil; cat_entry = cat_entry->next) {
2710 if (cat_entry->cat == cat) {
2711 cat_entry->cat = nil;
2721 /***********************************************************************
2723 * Various paranoid debugging checks that look for poorly-behaving
2724 * unloadable bundles.
2725 * Called by _objc_unmap_image when OBJC_UNLOAD_DEBUG is set.
2726 **********************************************************************/
2727 static void unload_paranoia(header_info *hi)
2729 // Get the location of the dying image's __OBJC segment
2731 unsigned long seg_size;
2732 seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size);
2734 _objc_inform("UNLOAD DEBUG: unloading image '%s' [%p..%p]",
2735 hi->fname, (void *)seg, (void*)(seg+seg_size));
2737 mutex_lock(&classLock);
2739 // Make sure the image contains no categories on surviving classes.
2744 // Major loop - process all modules in the header
2747 for (midx = 0; midx < hi->mod_count; midx++) {
2750 Symtab symtab = mods[midx].symtab;
2752 // Nothing to do for a module without a symbol table
2753 if (symtab == nil) continue;
2755 // Total entries in symbol table (class entries followed
2756 // by category entries)
2757 total = symtab->cls_def_cnt + symtab->cat_def_cnt;
2759 // Minor loop - check all categories from given module
2760 for (index = symtab->cls_def_cnt; index < total; index++) {
2761 old_category *cat = (old_category *)symtab->defs[index];
2762 struct objc_class query;
2764 query.name = cat->class_name;
2765 if (NXHashMember(class_hash, &query)) {
2766 _objc_inform("UNLOAD DEBUG: dying image contains category '%s(%s)' on surviving class '%s'!", cat->class_name, cat->category_name, cat->class_name);
2772 // Make sure no surviving class is in the dying image.
2773 // Make sure no surviving class has a superclass in the dying image.
2774 // fixme check method implementations too
2779 state = NXInitHashState(class_hash);
2780 while (NXNextHashState(class_hash, &state, (void **)&cls)) {
2781 if ((vm_address_t)cls >= seg &&
2782 (vm_address_t)cls < seg+seg_size)
2784 _objc_inform("UNLOAD DEBUG: dying image contains surviving class '%s'!", cls->name);
2787 if ((vm_address_t)cls->superclass >= seg &&
2788 (vm_address_t)cls->superclass < seg+seg_size)
2790 _objc_inform("UNLOAD DEBUG: dying image contains superclass '%s' of surviving class '%s'!", cls->superclass->name, cls->name);
2795 mutex_unlock(&classLock);
2799 /***********************************************************************
2801 * Only handles MH_BUNDLE for now.
2802 * Locking: loadMethodLock acquired by unmap_image
2803 **********************************************************************/
2804 void _unload_image(header_info *hi)
2806 recursive_mutex_assert_locked(&loadMethodLock);
2809 // Remove image's classes from the class list and free auxiliary data.
2810 // Remove image's unresolved or loadable categories and free auxiliary data
2811 // Remove image's unresolved class refs.
2812 _objc_remove_classes_in_image(hi);
2813 _objc_remove_categories_in_image(hi);
2814 _objc_remove_pending_class_refs_in_image(hi);
2816 // Perform various debugging checks if requested.
2817 if (DebugUnload) unload_paranoia(hi);
2823 /***********************************************************************
2824 * objc_addClass. Add the specified class to the table of known classes,
2825 * after doing a little verification and fixup.
2826 **********************************************************************/
2827 void objc_addClass (Class cls)
2829 OBJC_WARN_DEPRECATED;
2831 // Synchronize access to hash table
2832 mutex_lock (&classLock);
2834 // Make sure both the class and the metaclass have caches!
2835 // Clear all bits of the info fields except CLS_CLASS and CLS_META.
2836 // Normally these bits are already clear but if someone tries to cons
2837 // up their own class on the fly they might need to be cleared.
2838 if (cls->cache == nil) {
2839 cls->cache = (Cache) &_objc_empty_cache;
2840 cls->info = CLS_CLASS;
2843 if (cls->ISA()->cache == nil) {
2844 cls->ISA()->cache = (Cache) &_objc_empty_cache;
2845 cls->ISA()->info = CLS_META;
2848 // methodLists should be:
2849 // 1. nil (Tiger and later only)
2850 // 2. A -1 terminated method list array
2851 // In either case, CLS_NO_METHOD_ARRAY remains clear.
2852 // If the user manipulates the method list directly,
2853 // they must use the magic private format.
2855 // Add the class to the table
2856 (void) NXHashInsert (class_hash, cls);
2857 objc_addRegisteredClass(cls);
2859 // Superclass is no longer a leaf for cache flushing
2860 if (cls->superclass && (cls->superclass->info & CLS_LEAF)) {
2861 cls->superclass->clearInfo(CLS_LEAF);
2862 cls->superclass->ISA()->clearInfo(CLS_LEAF);
2866 mutex_unlock (&classLock);
2869 /***********************************************************************
2870 * _objcTweakMethodListPointerForClass.
2871 * Change the class's method list pointer to a method list array.
2872 * Does nothing if the method list pointer is already a method list array.
2873 * If the class is currently in use, methodListLock must be held by the caller.
2874 **********************************************************************/
2875 static void _objcTweakMethodListPointerForClass(Class cls)
2877 old_method_list * originalList;
2878 const int initialEntries = 4;
2880 old_method_list ** ptr;
2882 // Do nothing if methodLists is already an array.
2883 if (cls->methodLists && !(cls->info & CLS_NO_METHOD_ARRAY)) return;
2885 // Remember existing list
2886 originalList = (old_method_list *) cls->methodLists;
2888 // Allocate and zero a method list array
2889 mallocSize = sizeof(old_method_list *) * initialEntries;
2890 ptr = (old_method_list **) _calloc_internal(1, mallocSize);
2892 // Insert the existing list into the array
2893 ptr[initialEntries - 1] = END_OF_METHODS_LIST;
2894 ptr[0] = originalList;
2896 // Replace existing list with array
2897 cls->methodLists = ptr;
2898 cls->clearInfo(CLS_NO_METHOD_ARRAY);
2902 /***********************************************************************
2903 * _objc_insertMethods.
2904 * Adds methods to a class.
2905 * Does not flush any method caches.
2906 * Does not take any locks.
2907 * If the class is already in use, use class_addMethods() instead.
2908 **********************************************************************/
2909 void _objc_insertMethods(Class cls, old_method_list *mlist, old_category *cat)
2911 old_method_list ***list;
2912 old_method_list **ptr;
2917 if (!cls->methodLists) {
2918 // cls has no methods - simply use this method list
2919 cls->methodLists = (old_method_list **)mlist;
2920 cls->setInfo(CLS_NO_METHOD_ARRAY);
2924 // Log any existing methods being replaced
2925 if (PrintReplacedMethods) {
2927 for (i = 0; i < mlist->method_count; i++) {
2928 extern IMP findIMPInClass(Class cls, SEL sel);
2929 SEL sel = sel_registerName((char *)mlist->method_list[i].method_name);
2930 IMP newImp = mlist->method_list[i].method_imp;
2933 if ((oldImp = findIMPInClass(cls, sel))) {
2934 logReplacedMethod(cls->name, sel, ISMETA(cls),
2935 cat ? cat->category_name : nil,
2941 // Create method list array if necessary
2942 _objcTweakMethodListPointerForClass(cls);
2944 list = &cls->methodLists;
2946 // Locate unused entry for insertion point
2948 while ((*ptr != 0) && (*ptr != END_OF_METHODS_LIST))
2951 // If array is full, add to it
2952 if (*ptr == END_OF_METHODS_LIST)
2954 // Calculate old and new dimensions
2955 endIndex = ptr - *list;
2956 oldSize = (endIndex + 1) * sizeof(void *);
2957 newSize = oldSize + sizeof(old_method_list *); // only increase by 1
2959 // Grow the method list array by one.
2960 // This block may be from user code; don't use _realloc_internal
2961 *list = (old_method_list **)realloc(*list, newSize);
2963 // Zero out addition part of new array
2964 bzero (&((*list)[endIndex]), newSize - oldSize);
2966 // Place new end marker
2967 (*list)[(newSize/sizeof(void *)) - 1] = END_OF_METHODS_LIST;
2969 // Insertion point corresponds to old array end
2970 ptr = &((*list)[endIndex]);
2973 // Right shift existing entries by one
2974 bcopy (*list, (*list) + 1, (uint8_t *)ptr - (uint8_t *)*list);
2976 // Insert at method list at beginning of array
2980 /***********************************************************************
2981 * _objc_removeMethods.
2982 * Remove methods from a class.
2983 * Does not take any locks.
2984 * Does not flush any method caches.
2985 * If the class is currently in use, use class_removeMethods() instead.
2986 **********************************************************************/
2987 void _objc_removeMethods(Class cls, old_method_list *mlist)
2989 old_method_list ***list;
2990 old_method_list **ptr;
2992 if (cls->methodLists == nil) {
2993 // cls has no methods
2996 if (cls->methodLists == (old_method_list **)mlist) {
2997 // mlist is the class's only method list - erase it
2998 cls->methodLists = nil;
3001 if (cls->info & CLS_NO_METHOD_ARRAY) {
3002 // cls has only one method list, and this isn't it - do nothing
3006 // cls has a method list array - search it
3008 list = &cls->methodLists;
3010 // Locate list in the array
3012 while (*ptr != mlist) {
3013 // fix for radar # 2538790
3014 if ( *ptr == END_OF_METHODS_LIST ) return;
3018 // Remove this entry
3021 // Left shift the following entries
3022 while (*(++ptr) != END_OF_METHODS_LIST)
3027 /***********************************************************************
3028 * _objc_add_category. Install the specified category's methods and
3029 * protocols into the class it augments.
3030 * The class is assumed not to be in use yet: no locks are taken and
3031 * no method caches are flushed.
3032 **********************************************************************/
3033 static inline void _objc_add_category(Class cls, old_category *category, int version)
3035 if (PrintConnecting) {
3036 _objc_inform("CONNECT: attaching category '%s (%s)'", cls->name, category->category_name);
3039 // Augment instance methods
3040 if (category->instance_methods)
3041 _objc_insertMethods (cls, category->instance_methods, category);
3043 // Augment class methods
3044 if (category->class_methods)
3045 _objc_insertMethods (cls->ISA(), category->class_methods, category);
3047 // Augment protocols
3048 if ((version >= 5) && category->protocols)
3050 if (cls->ISA()->version >= 5)
3052 category->protocols->next = cls->protocols;
3053 cls->protocols = category->protocols;
3054 cls->ISA()->protocols = category->protocols;
3058 _objc_inform ("unable to add protocols from category %s...\n", category->category_name);
3059 _objc_inform ("class `%s' must be recompiled\n", category->class_name);
3063 // Augment properties
3064 if (version >= 7 && category->instance_properties) {
3065 if (cls->ISA()->version >= 6) {
3066 _class_addProperties(cls, category->instance_properties);
3068 _objc_inform ("unable to add properties from category %s...\n", category->category_name);
3069 _objc_inform ("class `%s' must be recompiled\n", category->class_name);
3074 /***********************************************************************
3075 * _objc_add_category_flush_caches. Install the specified category's
3076 * methods into the class it augments, and flush the class' method cache.
3077 * Return YES if some method caches now need to be flushed.
3078 **********************************************************************/
3079 static BOOL _objc_add_category_flush_caches(Class cls, old_category *category, int version)
3081 BOOL needFlush = NO;
3083 // Install the category's methods into its intended class
3084 mutex_lock(&methodListLock);
3085 _objc_add_category (cls, category, version);
3086 mutex_unlock(&methodListLock);
3088 // Queue for cache flushing so category's methods can get called
3089 if (category->instance_methods) {
3090 cls->setInfo(CLS_FLUSH_CACHE);
3093 if (category->class_methods) {
3094 cls->ISA()->setInfo(CLS_FLUSH_CACHE);
3102 /***********************************************************************
3104 * Reverse the given linked list of pending categories.
3105 * The pending category list is built backwards, and needs to be
3106 * reversed before actually attaching the categories to a class.
3107 * Returns the head of the new linked list.
3108 **********************************************************************/
3109 static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat)
3111 _objc_unresolved_category *prev;
3112 _objc_unresolved_category *cur;
3113 _objc_unresolved_category *ahead;
3115 if (!cat) return nil;
3132 /***********************************************************************
3133 * resolve_categories_for_class.
3134 * Install all existing categories intended for the specified class.
3135 * cls must be a true class and not a metaclass.
3136 **********************************************************************/
3137 static void resolve_categories_for_class(Class cls)
3139 _objc_unresolved_category * pending;
3140 _objc_unresolved_category * next;
3142 // Nothing to do if there are no categories at all
3143 if (!category_hash) return;
3145 // Locate and remove first element in category list
3146 // associated with this class
3147 pending = (_objc_unresolved_category *)
3148 NXMapKeyFreeingRemove (category_hash, cls->name);
3150 // Traverse the list of categories, if any, registered for this class
3152 // The pending list is built backwards. Reverse it and walk forwards.
3153 pending = reverse_cat(pending);
3157 // Install the category
3158 // use the non-flush-cache version since we are only
3159 // called from the class intialization code
3160 _objc_add_category(cls, pending->cat, (int)pending->version);
3163 // Delink and reclaim this registration
3164 next = pending->next;
3165 _free_internal(pending);
3171 /***********************************************************************
3172 * _objc_resolve_categories_for_class.
3173 * Public version of resolve_categories_for_class. This was
3174 * exported pre-10.4 for Omni et al. to workaround a problem
3175 * with too-lazy category attachment.
3176 * cls should be a class, but this function can also cope with metaclasses.
3177 **********************************************************************/
3178 void _objc_resolve_categories_for_class(Class cls)
3180 // If cls is a metaclass, get the class.
3181 // resolve_categories_for_class() requires a real class to work correctly.
3183 if (strncmp(cls->name, "_%", 2) == 0) {
3184 // Posee's meta's name is smashed and isn't in the class_hash,
3185 // so objc_getClass doesn't work.
3186 const char *baseName = strchr(cls->name, '%'); // get posee's real name
3187 cls = objc_getClass(baseName);
3189 cls = objc_getClass(cls->name);
3193 resolve_categories_for_class(cls);
3197 /***********************************************************************
3198 * _objc_register_category.
3199 * Process a category read from an image.
3200 * If the category's class exists, attach the category immediately.
3201 * Classes that need cache flushing are marked but not flushed.
3202 * If the category's class does not exist yet, pend the category for
3203 * later attachment. Pending categories are attached in the order
3204 * they were discovered.
3205 * Returns YES if some method caches now need to be flushed.
3206 **********************************************************************/
3207 static BOOL _objc_register_category(old_category *cat, int version)
3209 _objc_unresolved_category * new_cat;
3210 _objc_unresolved_category * old;
3213 // If the category's class exists, attach the category.
3214 if ((theClass = objc_lookUpClass(cat->class_name))) {
3215 return _objc_add_category_flush_caches(theClass, cat, version);
3218 // If the category's class exists but is unconnected,
3219 // then attach the category to the class but don't bother
3220 // flushing any method caches (because they must be empty).
3221 // YES unconnected, NO class_handler
3222 if ((theClass = look_up_class(cat->class_name, YES, NO))) {
3223 _objc_add_category(theClass, cat, version);
3228 // Category's class does not exist yet.
3229 // Save the category for later attachment.
3231 if (PrintConnecting) {
3232 _objc_inform("CONNECT: pending category '%s (%s)'", cat->class_name, cat->category_name);
3235 // Create category lookup table if needed
3237 category_hash = NXCreateMapTableFromZone (NXStrValueMapPrototype,
3239 _objc_internal_zone ());
3241 // Locate an existing list of categories, if any, for the class.
3242 old = (_objc_unresolved_category *)
3243 NXMapGet (category_hash, cat->class_name);
3245 // Register the category to be fixed up later.
3246 // The category list is built backwards, and is reversed again
3247 // by resolve_categories_for_class().
3248 new_cat = (_objc_unresolved_category *)
3249 _malloc_internal(sizeof(_objc_unresolved_category));
3250 new_cat->next = old;
3252 new_cat->version = version;
3253 (void) NXMapKeyCopyingInsert (category_hash, cat->class_name, new_cat);
3260 _objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount)
3273 for (m = 0; m < hi->mod_count; m++) {
3276 if (!mods[m].symtab) continue;
3278 for (d = 0; d < mods[m].symtab->cls_def_cnt; d++) {
3279 Class cls = (Class)mods[m].symtab->defs[d];
3280 // fixme what about future-ified classes?
3281 if (cls->isConnected()) {
3282 if (count == allocated) {
3283 allocated = allocated*2 + 16;
3284 list = (const char **)
3285 realloc((void *)list, allocated * sizeof(char *));
3287 list[count++] = cls->name;
3293 // nil-terminate non-empty list
3294 if (count == allocated) {
3295 allocated = allocated+1;
3296 list = (const char **)
3297 realloc((void *)list, allocated * sizeof(char *));
3302 if (outCount) *outCount = count;
3306 Class gdb_class_getClass(Class cls)
3308 const char *className = cls->name;
3309 if(!className || !strlen(className)) return Nil;
3310 Class rCls = look_up_class(className, NO, NO);
3315 Class gdb_object_getClass(id obj)
3317 if (!obj) return nil;
3318 return gdb_class_getClass(obj->getIsa());
3322 /***********************************************************************
3324 **********************************************************************/
3325 rwlock_t selLock = {};
3326 mutex_t classLock = MUTEX_INITIALIZER;
3327 mutex_t methodListLock = MUTEX_INITIALIZER;
3328 mutex_t cacheUpdateLock = MUTEX_INITIALIZER;
3329 recursive_mutex_t loadMethodLock = RECURSIVE_MUTEX_INITIALIZER;
3331 void lock_init(void)
3333 rwlock_init(&selLock);
3334 recursive_mutex_init(&loadMethodLock);