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 NULL.
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-loadmethod.h"
148 /* NXHashTable SPI */
149 extern unsigned _NXHashCapacity(NXHashTable *table);
150 extern void _NXHashRehashToCapacity(NXHashTable *table, unsigned newCapacity);
153 typedef struct _objc_unresolved_category
155 struct _objc_unresolved_category *next;
156 struct old_category *cat; // may be NULL
158 } _objc_unresolved_category;
160 typedef struct _PendingSubclass
162 struct old_class *subclass; // subclass to finish connecting; may be NULL
163 struct _PendingSubclass *next;
166 typedef struct _PendingClassRef
168 struct old_class **ref; // class reference to fix up; may be NULL
169 // (ref & 1) is a metaclass reference
170 struct _PendingClassRef *next;
174 static uintptr_t classHash(void *info, Class data);
175 static int classIsEqual(void *info, Class name, Class cls);
176 static int _objc_defaultClassHandler(const char *clsName);
177 static BOOL class_is_connected(struct old_class *cls);
178 static inline NXMapTable *pendingClassRefsMapTable(void);
179 static inline NXMapTable *pendingSubclassesMapTable(void);
180 static void pendClassInstallation(struct old_class *cls, const char *superName);
181 static void pendClassReference(struct old_class **ref, const char *className, BOOL isMeta);
182 static void resolve_references_to_class(struct old_class *cls);
183 static void resolve_subclasses_of_class(struct old_class *cls);
184 static void really_connect_class(struct old_class *cls, struct old_class *supercls);
185 static BOOL connect_class(struct old_class *cls);
186 static void map_method_descs (struct objc_method_description_list * methods, BOOL copy);
187 static void _objcTweakMethodListPointerForClass(struct old_class *cls);
188 static inline void _objc_add_category(struct old_class *cls, struct old_category *category, int version);
189 static BOOL _objc_add_category_flush_caches(struct old_class *cls, struct old_category *category, int version);
190 static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat);
191 static void resolve_categories_for_class(struct old_class *cls);
192 static BOOL _objc_register_category(struct old_category *cat, int version);
195 // Function called when a class is loaded from an image
196 PRIVATE_EXTERN void (*callbackFunction)(Class, Category) = 0;
198 // Hash table of classes
199 PRIVATE_EXTERN NXHashTable * class_hash = 0;
200 static NXHashTablePrototype classHashPrototype =
202 (uintptr_t (*) (const void *, const void *)) classHash,
203 (int (*)(const void *, const void *, const void *)) classIsEqual,
207 // Hash table of unconnected classes
208 static NXHashTable *unconnected_class_hash = NULL;
210 // Exported copy of class_hash variable (hook for debugging tools)
211 NXHashTable *_objc_debug_class_hash = NULL;
213 // Category and class registries
214 // Keys are COPIES of strings, to prevent stale pointers with unloaded bundles
215 // Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove
216 static NXMapTable * category_hash = NULL;
218 // Keys are COPIES of strings, to prevent stale pointers with unloaded bundles
219 // Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove
220 static NXMapTable * pendingClassRefsMap = NULL;
221 static NXMapTable * pendingSubclassesMap = NULL;
224 static NXMapTable *protocol_map = NULL; // name -> protocol
225 static NXMapTable *protocol_ext_map = NULL; // protocol -> protocol ext
227 // Function pointer objc_getClass calls through when class is not found
228 static int (*objc_classHandler) (const char *) = _objc_defaultClassHandler;
230 // Function pointer called by objc_getClass and objc_lookupClass when
231 // class is not found. _objc_classLoader is called before objc_classHandler.
232 static BOOL (*_objc_classLoader)(const char *) = NULL;
235 /***********************************************************************
236 * objc_dump_class_hash. Log names of all known classes.
237 **********************************************************************/
238 PRIVATE_EXTERN void objc_dump_class_hash(void)
247 state = NXInitHashState (table);
248 while (NXNextHashState (table, &state, (void **) &data))
249 printf ("class %d: %s\n", ++count, _class_getName(data));
253 /***********************************************************************
254 * _objc_init_class_hash. Return the class lookup table, create it if
256 **********************************************************************/
257 PRIVATE_EXTERN void _objc_init_class_hash(void)
259 // Do nothing if class hash table already exists
263 // class_hash starts small, with only enough capacity for libobjc itself.
264 // If a second library is found by map_images(), class_hash is immediately
265 // resized to capacity 1024 to cut down on rehashes.
266 // Old numbers: A smallish Foundation+AppKit program will have
267 // about 520 classes. Larger apps (like IB or WOB) have more like
268 // 800 classes. Some customers have massive quantities of classes.
269 // Foundation-only programs aren't likely to notice the ~6K loss.
270 class_hash = NXCreateHashTableFromZone (classHashPrototype,
273 _objc_internal_zone ());
274 _objc_debug_class_hash = class_hash;
278 /***********************************************************************
279 * objc_getClassList. Return the known classes.
280 **********************************************************************/
281 int objc_getClassList(Class *buffer, int bufferLen)
287 mutex_lock(&classLock);
289 mutex_unlock(&classLock);
292 num = NXCountHashTable(class_hash);
293 if (NULL == buffer) {
294 mutex_unlock(&classLock);
298 state = NXInitHashState(class_hash);
299 while (cnt < bufferLen &&
300 NXNextHashState(class_hash, &state, (void **)&cls))
304 mutex_unlock(&classLock);
309 /***********************************************************************
311 * Returns pointers to all classes.
312 * This requires all classes be realized, which is regretfully non-lazy.
314 * outCount may be NULL. *outCount is the number of classes returned.
315 * If the returned array is not NULL, it is NULL-terminated and must be
317 * Locking: acquires classLock
318 **********************************************************************/
320 objc_copyClassList(unsigned int *outCount)
325 mutex_lock(&classLock);
327 count = class_hash ? NXCountHashTable(class_hash) : 0;
331 NXHashState state = NXInitHashState(class_hash);
332 result = malloc((1+count) * sizeof(Class));
334 while (NXNextHashState(class_hash, &state, (void **)&cls)) {
335 result[count++] = cls;
337 result[count] = NULL;
339 mutex_unlock(&classLock);
341 if (outCount) *outCount = count;
346 /***********************************************************************
347 * objc_copyProtocolList
348 * Returns pointers to all protocols.
349 * Locking: acquires classLock
350 **********************************************************************/
351 Protocol * __unsafe_unretained *
352 objc_copyProtocolList(unsigned int *outCount)
360 mutex_lock(&classLock);
362 count = NXCountMapTable(protocol_map);
364 mutex_unlock(&classLock);
365 if (outCount) *outCount = 0;
369 result = calloc(1 + count, sizeof(Protocol *));
372 state = NXInitMapState(protocol_map);
373 while (NXNextMapState(protocol_map, &state,
374 (const void **)&name, (const void **)&proto))
380 assert(i == count+1);
382 mutex_unlock(&classLock);
384 if (outCount) *outCount = count;
389 /***********************************************************************
390 * objc_getClasses. Return class lookup table.
392 * NOTE: This function is very dangerous, since you cannot safely use
393 * the hashtable without locking it, and the lock is private!
394 **********************************************************************/
395 void *objc_getClasses(void)
397 OBJC_WARN_DEPRECATED;
399 // Return the class lookup hash table
404 /***********************************************************************
406 **********************************************************************/
407 static uintptr_t classHash(void *info, Class data)
409 // Nil classes hash to zero
413 // Call through to real hash function
414 return _objc_strhash (_class_getName(data));
417 /***********************************************************************
418 * classIsEqual. Returns whether the class names match. If we ever
419 * check more than the name, routines like objc_lookUpClass have to
421 **********************************************************************/
422 static int classIsEqual(void *info, Class name, Class cls)
424 // Standard string comparison
425 return strcmp(_class_getName(name), _class_getName(cls)) == 0;
429 // Unresolved future classes
430 static NXHashTable *future_class_hash = NULL;
432 // Resolved future<->original classes
433 static NXMapTable *future_class_to_original_class_map = NULL;
434 static NXMapTable *original_class_to_future_class_map = NULL;
436 // CF requests about 20 future classes; HIToolbox requests one.
437 #define FUTURE_COUNT 32
440 /***********************************************************************
441 * setOriginalClassForFutureClass
442 * Record resolution of a future class.
443 **********************************************************************/
444 static void setOriginalClassForFutureClass(struct old_class *futureClass,
445 struct old_class *originalClass)
447 if (!future_class_to_original_class_map) {
448 future_class_to_original_class_map =
449 NXCreateMapTableFromZone (NXPtrValueMapPrototype, FUTURE_COUNT,
450 _objc_internal_zone ());
451 original_class_to_future_class_map =
452 NXCreateMapTableFromZone (NXPtrValueMapPrototype, FUTURE_COUNT,
453 _objc_internal_zone ());
456 NXMapInsert (future_class_to_original_class_map,
457 futureClass, originalClass);
458 NXMapInsert (original_class_to_future_class_map,
459 originalClass, futureClass);
462 _objc_inform("FUTURE: using %p instead of %p for %s", futureClass, originalClass, originalClass->name);
466 /***********************************************************************
467 * getOriginalClassForFutureClass
468 * getFutureClassForOriginalClass
469 * Switch between a future class and its corresponding original class.
470 * The future class is the one actually in use.
471 * The original class is the one from disk.
472 **********************************************************************/
474 static struct old_class *
475 getOriginalClassForFutureClass(struct old_class *futureClass)
477 if (!future_class_to_original_class_map) return Nil;
478 return NXMapGet (future_class_to_original_class_map, futureClass);
481 static struct old_class *
482 getFutureClassForOriginalClass(struct old_class *originalClass)
484 if (!original_class_to_future_class_map) return Nil;
485 return NXMapGet (original_class_to_future_class_map, originalClass);
489 /***********************************************************************
491 * Initialize the memory in *cls with an unresolved future class with the
492 * given name. The memory is recorded in future_class_hash.
493 **********************************************************************/
494 static void makeFutureClass(struct old_class *cls, const char *name)
496 // CF requests about 20 future classes, plus HIToolbox has one.
497 if (!future_class_hash) {
499 NXCreateHashTableFromZone(classHashPrototype, FUTURE_COUNT,
500 NULL, _objc_internal_zone());
503 cls->name = _strdup_internal(name);
504 NXHashInsert(future_class_hash, cls);
507 _objc_inform("FUTURE: reserving %p for %s", cls, name);
512 /***********************************************************************
513 * _objc_allocateFutureClass
514 * Allocate an unresolved future class for the given class name.
515 * Returns any existing allocation if one was already made.
516 * Assumes the named class doesn't exist yet.
518 **********************************************************************/
519 PRIVATE_EXTERN Class _objc_allocateFutureClass(const char *name)
521 struct old_class *cls;
523 if (future_class_hash) {
524 struct old_class query;
526 if ((cls = NXHashGet(future_class_hash, &query))) {
527 // Already have a future class for this name.
532 cls = (struct old_class *)_calloc_class(sizeof(*cls));
533 makeFutureClass(cls, name);
538 /***********************************************************************
539 * objc_setFutureClass.
540 * Like objc_getFutureClass, but uses the provided memory block.
541 * If the class already exists, a posing-like substitution is performed.
543 **********************************************************************/
544 void objc_setFutureClass(Class cls, const char *name)
546 struct old_class *oldcls;
547 struct old_class *newcls = (struct old_class *)cls; // Not a real class!
549 if ((oldcls = oldcls((Class)look_up_class(name, NO/*unconnected*/, NO/*classhandler*/)))) {
550 setOriginalClassForFutureClass(newcls, oldcls);
552 memcpy(newcls, oldcls, sizeof(struct objc_class));
553 newcls->info &= ~CLS_EXT;
555 mutex_lock(&classLock);
556 NXHashRemove(class_hash, oldcls);
557 objc_removeRegisteredClass((Class)oldcls);
558 change_class_references(newcls, oldcls, nil, YES);
559 NXHashInsert(class_hash, newcls);
560 objc_addRegisteredClass((Class)newcls);
561 mutex_unlock(&classLock);
563 makeFutureClass(newcls, name);
568 /***********************************************************************
569 * _objc_defaultClassHandler. Default objc_classHandler. Does nothing.
570 **********************************************************************/
571 static int _objc_defaultClassHandler(const char *clsName)
573 // Return zero so objc_getClass doesn't bother re-searching
577 /***********************************************************************
578 * objc_setClassHandler. Set objc_classHandler to the specified value.
580 * NOTE: This should probably deal with userSuppliedHandler being NULL,
581 * because the objc_classHandler caller does not check... it would bus
582 * error. It would make sense to handle NULL by restoring the default
583 * handler. Is anyone hacking with this, though?
584 **********************************************************************/
585 void objc_setClassHandler(int (*userSuppliedHandler)(const char *))
587 OBJC_WARN_DEPRECATED;
589 objc_classHandler = userSuppliedHandler;
593 /***********************************************************************
594 * _objc_setClassLoader
595 * Similar to objc_setClassHandler, but objc_classLoader is used for
596 * both objc_getClass() and objc_lookupClass(), and objc_classLoader
597 * pre-empts objc_classHandler.
598 **********************************************************************/
599 void _objc_setClassLoader(BOOL (*newClassLoader)(const char *))
601 _objc_classLoader = newClassLoader;
605 /***********************************************************************
607 * Get a protocol by name, or NULL.
608 **********************************************************************/
609 Protocol *objc_getProtocol(const char *name)
612 if (!protocol_map) return NULL;
613 mutex_lock(&classLock);
614 result = (Protocol *)NXMapGet(protocol_map, name);
615 mutex_unlock(&classLock);
620 /***********************************************************************
622 * Map a class name to a class using various methods.
623 * This is the common implementation of objc_lookUpClass and objc_getClass,
624 * and is also used internally to get additional search options.
627 * 2. unconnected_class_hash (optional)
628 * 3. classLoader callback
629 * 4. classHandler callback (optional)
630 **********************************************************************/
631 PRIVATE_EXTERN id look_up_class(const char *aClassName, BOOL includeUnconnected, BOOL includeClassHandler)
633 BOOL includeClassLoader = YES; // class loader cannot be skipped
635 struct old_class query;
637 query.name = aClassName;
641 if (!result && class_hash) {
642 // Check ordinary classes
643 mutex_lock (&classLock);
644 result = (id)NXHashGet(class_hash, &query);
645 mutex_unlock (&classLock);
648 if (!result && includeUnconnected && unconnected_class_hash) {
649 // Check not-yet-connected classes
650 mutex_lock(&classLock);
651 result = (id)NXHashGet(unconnected_class_hash, &query);
652 mutex_unlock(&classLock);
655 if (!result && includeClassLoader && _objc_classLoader) {
656 // Try class loader callback
657 if ((*_objc_classLoader)(aClassName)) {
658 // Re-try lookup without class loader
659 includeClassLoader = NO;
664 if (!result && includeClassHandler && objc_classHandler) {
665 // Try class handler callback
666 if ((*objc_classHandler)(aClassName)) {
667 // Re-try lookup without class handler or class loader
668 includeClassLoader = NO;
669 includeClassHandler = NO;
678 /***********************************************************************
679 * class_is_connected.
680 * Returns TRUE if class cls is connected.
681 * A connected class has either a connected superclass or a NULL superclass,
682 * and is present in class_hash.
683 **********************************************************************/
684 static BOOL class_is_connected(struct old_class *cls)
687 mutex_lock(&classLock);
688 result = NXHashMember(class_hash, cls);
689 mutex_unlock(&classLock);
694 /***********************************************************************
696 * Returns TRUE if class cls is ready for its +load method to be called.
697 * A class is ready for +load if it is connected.
698 **********************************************************************/
699 PRIVATE_EXTERN BOOL _class_isLoadable(Class cls)
701 return class_is_connected(oldcls(cls));
705 /***********************************************************************
706 * pendingClassRefsMapTable. Return a pointer to the lookup table for
707 * pending class refs.
708 **********************************************************************/
709 static inline NXMapTable *pendingClassRefsMapTable(void)
711 // Allocate table if needed
712 if (!pendingClassRefsMap) {
713 pendingClassRefsMap =
714 NXCreateMapTableFromZone(NXStrValueMapPrototype,
715 10, _objc_internal_zone ());
718 // Return table pointer
719 return pendingClassRefsMap;
723 /***********************************************************************
724 * pendingSubclassesMapTable. Return a pointer to the lookup table for
725 * pending subclasses.
726 **********************************************************************/
727 static inline NXMapTable *pendingSubclassesMapTable(void)
729 // Allocate table if needed
730 if (!pendingSubclassesMap) {
731 pendingSubclassesMap =
732 NXCreateMapTableFromZone(NXStrValueMapPrototype,
733 10, _objc_internal_zone ());
736 // Return table pointer
737 return pendingSubclassesMap;
741 /***********************************************************************
742 * pendClassInstallation
743 * Finish connecting class cls when its superclass becomes connected.
744 * Check for multiple pends of the same class because connect_class does not.
745 **********************************************************************/
746 static void pendClassInstallation(struct old_class *cls, const char *superName)
749 PendingSubclass *pending;
750 PendingSubclass *oldList;
753 // Create and/or locate pending class lookup table
754 table = pendingSubclassesMapTable ();
756 // Make sure this class isn't already in the pending list.
757 oldList = NXMapGet (table, superName);
758 for (l = oldList; l != NULL; l = l->next) {
759 if (l->subclass == cls) return; // already here, nothing to do
762 // Create entry referring to this class
763 pending = _malloc_internal(sizeof(PendingSubclass));
764 pending->subclass = cls;
766 // Link new entry into head of list of entries for this class
767 pending->next = oldList;
769 // (Re)place entry list in the table
770 NXMapKeyCopyingInsert (table, superName, pending);
774 /***********************************************************************
776 * Fix up a class ref when the class with the given name becomes connected.
777 **********************************************************************/
778 static void pendClassReference(struct old_class **ref, const char *className, BOOL isMeta)
781 PendingClassRef *pending;
783 // Create and/or locate pending class lookup table
784 table = pendingClassRefsMapTable ();
786 // Create entry containing the class reference
787 pending = _malloc_internal(sizeof(PendingClassRef));
790 pending->ref = (struct old_class **)((uintptr_t)pending->ref | 1);
793 // Link new entry into head of list of entries for this class
794 pending->next = NXMapGet (table, className);
796 // (Re)place entry list in the table
797 NXMapKeyCopyingInsert (table, className, pending);
799 if (PrintConnecting) {
800 _objc_inform("CONNECT: pended reference to class '%s%s' at %p",
801 className, isMeta ? " (meta)" : "", (void *)ref);
806 /***********************************************************************
807 * resolve_references_to_class
808 * Fix up any pending class refs to this class.
809 **********************************************************************/
810 static void resolve_references_to_class(struct old_class *cls)
812 PendingClassRef *pending;
814 if (!pendingClassRefsMap) return; // no unresolved refs for any class
816 pending = NXMapGet(pendingClassRefsMap, cls->name);
817 if (!pending) return; // no unresolved refs for this class
819 NXMapKeyFreeingRemove(pendingClassRefsMap, cls->name);
821 if (PrintConnecting) {
822 _objc_inform("CONNECT: resolving references to class '%s'", cls->name);
826 PendingClassRef *next = pending->next;
828 BOOL isMeta = ((uintptr_t)pending->ref & 1) ? YES : NO;
829 struct old_class **ref =
830 (struct old_class **)((uintptr_t)pending->ref & ~(uintptr_t)1);
831 *ref = isMeta ? cls->isa : cls;
833 _free_internal(pending);
837 if (NXCountMapTable(pendingClassRefsMap) == 0) {
838 NXFreeMapTable(pendingClassRefsMap);
839 pendingClassRefsMap = NULL;
844 /***********************************************************************
845 * resolve_subclasses_of_class
846 * Fix up any pending subclasses of this class.
847 **********************************************************************/
848 static void resolve_subclasses_of_class(struct old_class *cls)
850 PendingSubclass *pending;
852 if (!pendingSubclassesMap) return; // no unresolved subclasses
854 pending = NXMapGet(pendingSubclassesMap, cls->name);
855 if (!pending) return; // no unresolved subclasses for this class
857 NXMapKeyFreeingRemove(pendingSubclassesMap, cls->name);
859 // Destroy the pending table if it's now empty, to save memory.
860 if (NXCountMapTable(pendingSubclassesMap) == 0) {
861 NXFreeMapTable(pendingSubclassesMap);
862 pendingSubclassesMap = NULL;
865 if (PrintConnecting) {
866 _objc_inform("CONNECT: resolving subclasses of class '%s'", cls->name);
870 PendingSubclass *next = pending->next;
871 if (pending->subclass) connect_class(pending->subclass);
872 _free_internal(pending);
878 /***********************************************************************
879 * really_connect_class
880 * Connect cls to superclass supercls unconditionally.
881 * Also adjust the class hash tables and handle pended subclasses.
883 * This should be called from connect_class() ONLY.
884 **********************************************************************/
885 static void really_connect_class(struct old_class *cls,
886 struct old_class *supercls)
888 struct old_class *oldCls;
890 // Connect superclass pointers.
891 set_superclass(cls, supercls, YES);
894 // For paranoia, this is a conservative update:
895 // only non-strong -> strong and weak -> strong are corrected.
896 if (UseGC && supercls &&
897 (cls->info & CLS_EXT) && (supercls->info & CLS_EXT))
900 layout_bitmap ivarBitmap =
901 layout_bitmap_create(cls->ivar_layout,
903 cls->instance_size, NO);
905 layout_bitmap superBitmap =
906 layout_bitmap_create(supercls->ivar_layout,
907 supercls->instance_size,
908 supercls->instance_size, NO);
910 // non-strong -> strong: bits set in super should be set in sub
911 layoutChanged = layout_bitmap_or(ivarBitmap, superBitmap, cls->name);
912 layout_bitmap_free(superBitmap);
915 layout_bitmap weakBitmap = {0};
916 BOOL weakLayoutChanged = NO;
918 if (cls->ext && cls->ext->weak_ivar_layout) {
919 // weak -> strong: strong bits should be cleared in weak layout
920 // This is a subset of non-strong -> strong
922 layout_bitmap_create(cls->ext->weak_ivar_layout,
924 cls->instance_size, YES);
927 layout_bitmap_clear(weakBitmap, ivarBitmap, cls->name);
929 // no existing weak ivars, so no weak -> strong changes
932 // Rebuild layout strings.
934 _objc_inform("IVARS: gc layout changed "
935 "for class %s (super %s)",
936 cls->name, supercls->name);
937 if (weakLayoutChanged) {
938 _objc_inform("IVARS: gc weak layout changed "
939 "for class %s (super %s)",
940 cls->name, supercls->name);
943 cls->ivar_layout = layout_string_create(ivarBitmap);
944 if (weakLayoutChanged) {
945 cls->ext->weak_ivar_layout = layout_string_create(weakBitmap);
948 layout_bitmap_free(weakBitmap);
951 layout_bitmap_free(ivarBitmap);
955 cls->info |= CLS_CONNECTED;
957 mutex_lock(&classLock);
959 // Update hash tables.
960 NXHashRemove(unconnected_class_hash, cls);
961 oldCls = NXHashInsert(class_hash, cls);
962 objc_addRegisteredClass((Class)cls);
964 // Delete unconnected_class_hash if it is now empty.
965 if (NXCountHashTable(unconnected_class_hash) == 0) {
966 NXFreeHashTable(unconnected_class_hash);
967 unconnected_class_hash = NULL;
970 // No duplicate classes allowed.
971 // Duplicates should have been rejected by _objc_read_classes_from_image.
974 mutex_unlock(&classLock);
976 // Fix up pended class refs to this class, if any
977 resolve_references_to_class(cls);
979 // Connect newly-connectable subclasses
980 resolve_subclasses_of_class(cls);
982 // GC debugging: make sure all classes with -dealloc also have -finalize
983 if (DebugFinalizers) {
984 extern IMP findIMPInClass(struct old_class *cls, SEL sel);
985 if (findIMPInClass(cls, sel_getUid("dealloc")) &&
986 ! findIMPInClass(cls, sel_getUid("finalize")))
988 _objc_inform("GC: class '%s' implements -dealloc but not -finalize", cls->name);
992 // Debugging: if this class has ivars, make sure this class's ivars don't
993 // overlap with its super's. This catches some broken fragile base classes.
994 // Do not use super->instance_size vs. self->ivar[0] to check this.
995 // Ivars may be packed across instance_size boundaries.
996 if (DebugFragileSuperclasses && cls->ivars && cls->ivars->ivar_count) {
997 struct old_class *ivar_cls = supercls;
999 // Find closest superclass that has some ivars, if one exists.
1001 (!ivar_cls->ivars || ivar_cls->ivars->ivar_count == 0))
1003 ivar_cls = ivar_cls->super_class;
1007 // Compare superclass's last ivar to this class's first ivar
1008 struct old_ivar *super_ivar =
1009 &ivar_cls->ivars->ivar_list[ivar_cls->ivars->ivar_count - 1];
1010 struct old_ivar *self_ivar =
1011 &cls->ivars->ivar_list[0];
1013 // fixme could be smarter about super's ivar size
1014 if (self_ivar->ivar_offset <= super_ivar->ivar_offset) {
1015 _objc_inform("WARNING: ivars of superclass '%s' and "
1016 "subclass '%s' overlap; superclass may have "
1017 "changed since subclass was compiled",
1018 ivar_cls->name, cls->name);
1025 /***********************************************************************
1027 * Connect class cls to its superclasses, if possible.
1028 * If cls becomes connected, move it from unconnected_class_hash
1029 * to connected_class_hash.
1030 * Returns TRUE if cls is connected.
1031 * Returns FALSE if cls could not be connected for some reason
1032 * (missing superclass or still-unconnected superclass)
1033 **********************************************************************/
1034 static BOOL connect_class(struct old_class *cls)
1036 if (class_is_connected(cls)) {
1037 // This class is already connected to its superclass.
1041 else if (cls->super_class == NULL) {
1042 // This class is a root class.
1043 // Connect it to itself.
1045 if (PrintConnecting) {
1046 _objc_inform("CONNECT: class '%s' now connected (root class)",
1050 really_connect_class(cls, NULL);
1054 // This class is not a root class and is not yet connected.
1055 // Connect it if its superclass and root class are already connected.
1056 // Otherwise, add this class to the to-be-connected list,
1057 // pending the completion of its superclass and root class.
1059 // At this point, cls->super_class and cls->isa->isa are still STRINGS
1060 char *supercls_name = (char *)cls->super_class;
1061 struct old_class *supercls;
1063 // YES unconnected, YES class handler
1064 if (NULL == (supercls = oldcls((Class)look_up_class(supercls_name, YES, YES)))) {
1065 // Superclass does not exist yet.
1066 // pendClassInstallation will handle duplicate pends of this class
1067 pendClassInstallation(cls, supercls_name);
1069 if (PrintConnecting) {
1070 _objc_inform("CONNECT: class '%s' NOT connected (missing super)", cls->name);
1075 if (! connect_class(supercls)) {
1076 // Superclass exists but is not yet connected.
1077 // pendClassInstallation will handle duplicate pends of this class
1078 pendClassInstallation(cls, supercls_name);
1080 if (PrintConnecting) {
1081 _objc_inform("CONNECT: class '%s' NOT connected (unconnected super)", cls->name);
1086 // Superclass exists and is connected.
1087 // Connect this class to the superclass.
1089 if (PrintConnecting) {
1090 _objc_inform("CONNECT: class '%s' now connected", cls->name);
1093 really_connect_class(cls, supercls);
1099 /***********************************************************************
1100 * _objc_read_categories_from_image.
1101 * Read all categories from the given image.
1102 * Install them on their parent classes, or register them for later
1104 * Returns YES if some method caches now need to be flushed.
1105 **********************************************************************/
1106 static BOOL _objc_read_categories_from_image (header_info * hi)
1110 BOOL needFlush = NO;
1112 if (_objcHeaderIsReplacement(hi)) {
1113 // Ignore any categories in this image
1118 // Major loop - process all modules in the header
1121 // NOTE: The module and category lists are traversed backwards
1122 // to preserve the pre-10.4 processing order. Changing the order
1123 // would have a small chance of introducing binary compatibility bugs.
1124 midx = hi->mod_count;
1125 while (midx-- > 0) {
1129 // Nothing to do for a module without a symbol table
1130 if (mods[midx].symtab == NULL)
1133 // Total entries in symbol table (class entries followed
1134 // by category entries)
1135 total = mods[midx].symtab->cls_def_cnt +
1136 mods[midx].symtab->cat_def_cnt;
1138 // Minor loop - register all categories from given module
1140 while (index-- > mods[midx].symtab->cls_def_cnt) {
1141 struct old_category *cat = mods[midx].symtab->defs[index];
1142 needFlush |= _objc_register_category(cat, (int)mods[midx].version);
1150 /***********************************************************************
1151 * _objc_read_classes_from_image.
1152 * Read classes from the given image, perform assorted minor fixups,
1153 * scan for +load implementation.
1154 * Does not connect classes to superclasses.
1155 * Does attach pended categories to the classes.
1156 * Adds all classes to unconnected_class_hash. class_hash is unchanged.
1157 **********************************************************************/
1158 static void _objc_read_classes_from_image(header_info *hi)
1163 int isBundle = headerIsBundle(hi);
1165 if (_objcHeaderIsReplacement(hi)) {
1166 // Ignore any classes in this image
1170 // class_hash starts small, enough only for libobjc itself.
1171 // If other Objective-C libraries are found, immediately resize
1172 // class_hash, assuming that Foundation and AppKit are about
1173 // to add lots of classes.
1174 mutex_lock(&classLock);
1175 if (hi->mhdr != libobjc_header && _NXHashCapacity(class_hash) < 1024) {
1176 _NXHashRehashToCapacity(class_hash, 1024);
1178 mutex_unlock(&classLock);
1180 // Major loop - process all modules in the image
1182 for (midx = 0; midx < hi->mod_count; midx += 1)
1184 // Skip module containing no classes
1185 if (mods[midx].symtab == NULL)
1188 // Minor loop - process all the classes in given module
1189 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
1191 struct old_class *newCls, *oldCls;
1194 // Locate the class description pointer
1195 newCls = mods[midx].symtab->defs[index];
1197 // Classes loaded from Mach-O bundles can be unloaded later.
1198 // Nothing uses this class yet, so _class_setInfo is not needed.
1199 if (isBundle) newCls->info |= CLS_FROM_BUNDLE;
1200 if (isBundle) newCls->isa->info |= CLS_FROM_BUNDLE;
1202 // Use common static empty cache instead of NULL
1203 if (newCls->cache == NULL)
1204 newCls->cache = (Cache) &_objc_empty_cache;
1205 if (newCls->isa->cache == NULL)
1206 newCls->isa->cache = (Cache) &_objc_empty_cache;
1208 // Set metaclass version
1209 newCls->isa->version = mods[midx].version;
1211 // methodLists is NULL or a single list, not an array
1212 newCls->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY;
1213 newCls->isa->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY;
1215 // class has no subclasses for cache flushing
1216 newCls->info |= CLS_LEAF;
1217 newCls->isa->info |= CLS_LEAF;
1219 if (mods[midx].version >= 6) {
1220 // class structure has ivar_layout and ext fields
1221 newCls->info |= CLS_EXT;
1222 newCls->isa->info |= CLS_EXT;
1225 // Check for +load implementation before categories are attached
1226 if (_class_hasLoadMethod((Class)newCls)) {
1227 newCls->isa->info |= CLS_HAS_LOAD_METHOD;
1230 // Install into unconnected_class_hash.
1231 mutex_lock(&classLock);
1233 if (future_class_hash) {
1234 struct old_class *futureCls =
1235 NXHashRemove(future_class_hash, newCls);
1237 // Another class structure for this class was already
1238 // prepared by objc_getFutureClass(). Use it instead.
1239 _free_internal((char *)futureCls->name);
1240 memcpy(futureCls, newCls, sizeof(*newCls));
1241 setOriginalClassForFutureClass(futureCls, newCls);
1244 if (NXCountHashTable(future_class_hash) == 0) {
1245 NXFreeHashTable(future_class_hash);
1246 future_class_hash = NULL;
1251 if (!unconnected_class_hash) {
1252 unconnected_class_hash =
1253 NXCreateHashTableFromZone(classHashPrototype, 128,
1254 NULL, _objc_internal_zone());
1257 if ((oldCls = NXHashGet(class_hash, newCls)) ||
1258 (oldCls = NXHashGet(unconnected_class_hash, newCls)))
1260 // Another class with this name exists. Complain and reject.
1261 inform_duplicate(newCls->name, (Class)oldCls, (Class)newCls);
1265 NXHashInsert(unconnected_class_hash, newCls);
1269 mutex_unlock(&classLock);
1272 // Attach pended categories for this class, if any
1273 resolve_categories_for_class(newCls);
1280 /***********************************************************************
1281 * _objc_connect_classes_from_image.
1282 * Connect the classes in the given image to their superclasses,
1283 * or register them for later connection if any superclasses are missing.
1284 **********************************************************************/
1285 static void _objc_connect_classes_from_image(header_info *hi)
1290 BOOL replacement = _objcHeaderIsReplacement(hi);
1292 // Major loop - process all modules in the image
1294 for (midx = 0; midx < hi->mod_count; midx += 1)
1296 // Skip module containing no classes
1297 if (mods[midx].symtab == NULL)
1300 // Minor loop - process all the classes in given module
1301 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
1303 struct old_class *cls = mods[midx].symtab->defs[index];
1304 if (! replacement) {
1306 struct old_class *futureCls = getFutureClassForOriginalClass(cls);
1308 // objc_getFutureClass() requested a different class
1309 // struct. Fix up the original struct's super_class
1310 // field for [super ...] use, but otherwise perform
1311 // fixups on the new class struct only.
1312 const char *super_name = (const char *) cls->super_class;
1313 if (super_name) cls->super_class = oldcls((Class)objc_getClass(super_name));
1316 connected = connect_class(cls);
1317 if (connected && callbackFunction) {
1318 (*callbackFunction)((Class)cls, 0);
1321 // Replacement image - fix up super_class only (#3704817)
1322 // And metaclass's super_class (#5351107)
1323 const char *super_name = (const char *) cls->super_class;
1325 cls->super_class = oldcls((Class)objc_getClass(super_name));
1326 // metaclass's superclass is superclass's metaclass
1327 cls->isa->super_class = cls->super_class->isa;
1329 // Replacement for a root class
1330 // cls->super_class already NULL
1331 // root metaclass's superclass is root class
1332 cls->isa->super_class = cls;
1340 /***********************************************************************
1341 * _objc_map_class_refs_for_image. Convert the class ref entries from
1342 * a class name string pointer to a class pointer. If the class does
1343 * not yet exist, the reference is added to a list of pending references
1344 * to be fixed up at a later date.
1345 **********************************************************************/
1346 static void fix_class_ref(struct old_class **ref, const char *name, BOOL isMeta)
1348 struct old_class *cls;
1350 // Get pointer to class of this name
1351 // NO unconnected, YES class loader
1352 // (real class with weak-missing superclass is unconnected now)
1353 cls = oldcls((Class)look_up_class(name, NO, YES));
1355 // Referenced class exists. Fix up the reference.
1356 *ref = isMeta ? cls->isa : cls;
1358 // Referenced class does not exist yet. Insert NULL for now
1359 // (weak-linking) and fix up the reference if the class arrives later.
1360 pendClassReference (ref, name, isMeta);
1365 static void _objc_map_class_refs_for_image (header_info * hi)
1367 struct old_class **cls_refs;
1371 // Locate class refs in image
1372 cls_refs = _getObjcClassRefs (hi, &count);
1374 // Process each class ref
1375 for (index = 0; index < count; index += 1) {
1376 // Ref is initially class name char*
1377 const char *name = (const char *) cls_refs[index];
1378 if (!name) continue;
1379 fix_class_ref(&cls_refs[index], name, NO /*never meta*/);
1385 /***********************************************************************
1386 * _objc_remove_pending_class_refs_in_image
1387 * Delete any pending class ref fixups for class refs in the given image,
1388 * because the image is about to be unloaded.
1389 **********************************************************************/
1390 static void removePendingReferences(struct old_class **refs, size_t count)
1392 struct old_class **end = refs + count;
1395 if (!pendingClassRefsMap) return;
1397 // Search the pending class ref table for class refs in this range.
1398 // The class refs may have already been stomped with NULL,
1399 // so there's no way to recover the original class name.
1403 PendingClassRef *pending;
1404 NXMapState state = NXInitMapState(pendingClassRefsMap);
1405 while(NXNextMapState(pendingClassRefsMap, &state,
1406 (const void **)&key, (const void **)&pending))
1408 for ( ; pending != NULL; pending = pending->next) {
1409 if (pending->ref >= refs && pending->ref < end) {
1410 pending->ref = NULL;
1417 static void _objc_remove_pending_class_refs_in_image(header_info *hi)
1419 struct old_class **cls_refs;
1422 // Locate class refs in this image
1423 cls_refs = _getObjcClassRefs(hi, &count);
1424 removePendingReferences(cls_refs, count);
1428 /***********************************************************************
1429 * map_selrefs. For each selector in the specified array,
1430 * replace the name pointer with a uniqued selector.
1431 * If copy is TRUE, all selector data is always copied. This is used
1432 * for registering selectors from unloadable bundles, so the selector
1433 * can still be used after the bundle's data segment is unmapped.
1434 * Returns YES if dst was written to, NO if it was unchanged.
1435 **********************************************************************/
1436 static inline void map_selrefs(SEL *sels, size_t count, BOOL copy)
1444 // Process each selector
1445 for (index = 0; index < count; index += 1)
1449 // Lookup pointer to uniqued string
1450 sel = sel_registerNameNoLock((const char *) sels[index], copy);
1452 // Replace this selector with uniqued one (avoid
1453 // modifying the VM page if this would be a NOP)
1454 if (sels[index] != sel) {
1463 /***********************************************************************
1464 * map_method_descs. For each method in the specified method list,
1465 * replace the name pointer with a uniqued selector.
1466 * If copy is TRUE, all selector data is always copied. This is used
1467 * for registering selectors from unloadable bundles, so the selector
1468 * can still be used after the bundle's data segment is unmapped.
1469 **********************************************************************/
1470 static void map_method_descs (struct objc_method_description_list * methods, BOOL copy)
1474 if (!methods) return;
1478 // Process each method
1479 for (index = 0; index < methods->count; index += 1)
1481 struct objc_method_description * method;
1484 // Get method entry to fix up
1485 method = &methods->list[index];
1487 // Lookup pointer to uniqued string
1488 sel = sel_registerNameNoLock((const char *) method->name, copy);
1490 // Replace this selector with uniqued one (avoid
1491 // modifying the VM page if this would be a NOP)
1492 if (method->name != sel)
1500 /***********************************************************************
1502 * Returns the protocol extension for the given protocol.
1503 * Returns NULL if the protocol has no extension.
1504 **********************************************************************/
1505 static struct old_protocol_ext *ext_for_protocol(struct old_protocol *proto)
1507 if (!proto) return NULL;
1508 if (!protocol_ext_map) return NULL;
1509 else return (struct old_protocol_ext *)NXMapGet(protocol_ext_map, proto);
1513 /***********************************************************************
1515 * Search a protocol method list for a selector.
1516 **********************************************************************/
1517 static struct objc_method_description *
1518 lookup_method(struct objc_method_description_list *mlist, SEL aSel)
1522 for (i = 0; i < mlist->count; i++) {
1523 if (mlist->list[i].name == aSel) {
1524 return mlist->list+i;
1532 /***********************************************************************
1533 * lookup_protocol_method
1534 * Recursively search for a selector in a protocol
1535 * (and all incorporated protocols)
1536 **********************************************************************/
1537 PRIVATE_EXTERN struct objc_method_description *
1538 lookup_protocol_method(struct old_protocol *proto, SEL aSel,
1539 BOOL isRequiredMethod, BOOL isInstanceMethod)
1541 struct objc_method_description *m = NULL;
1542 struct old_protocol_ext *ext;
1544 if (isRequiredMethod) {
1545 if (isInstanceMethod) {
1546 m = lookup_method(proto->instance_methods, aSel);
1548 m = lookup_method(proto->class_methods, aSel);
1550 } else if ((ext = ext_for_protocol(proto))) {
1551 if (isInstanceMethod) {
1552 m = lookup_method(ext->optional_instance_methods, aSel);
1554 m = lookup_method(ext->optional_class_methods, aSel);
1558 if (!m && proto->protocol_list) {
1560 for (i = 0; !m && i < proto->protocol_list->count; i++) {
1561 m = lookup_protocol_method(proto->protocol_list->list[i], aSel,
1562 isRequiredMethod, isInstanceMethod);
1570 /***********************************************************************
1572 * Returns the name of the given protocol.
1573 **********************************************************************/
1574 const char *protocol_getName(Protocol *p)
1576 struct old_protocol *proto = oldprotocol(p);
1577 if (!proto) return "nil";
1578 return proto->protocol_name;
1582 /***********************************************************************
1583 * protocol_getMethodDescription
1584 * Returns the description of a named method.
1585 * Searches either required or optional methods.
1586 * Searches either instance or class methods.
1587 **********************************************************************/
1588 struct objc_method_description
1589 protocol_getMethodDescription(Protocol *p, SEL aSel,
1590 BOOL isRequiredMethod, BOOL isInstanceMethod)
1592 struct objc_method_description empty = {NULL, NULL};
1593 struct old_protocol *proto = oldprotocol(p);
1594 struct objc_method_description *desc;
1595 if (!proto) return empty;
1597 desc = lookup_protocol_method(proto, aSel,
1598 isRequiredMethod, isInstanceMethod);
1599 if (desc) return *desc;
1604 /***********************************************************************
1605 * protocol_copyMethodDescriptionList
1606 * Returns an array of method descriptions from a protocol.
1607 * Copies either required or optional methods.
1608 * Copies either instance or class methods.
1609 **********************************************************************/
1610 struct objc_method_description *
1611 protocol_copyMethodDescriptionList(Protocol *p,
1612 BOOL isRequiredMethod,
1613 BOOL isInstanceMethod,
1614 unsigned int *outCount)
1616 struct objc_method_description_list *mlist = NULL;
1617 struct old_protocol *proto = oldprotocol(p);
1618 struct old_protocol_ext *ext;
1619 unsigned int i, count;
1620 struct objc_method_description *result;
1623 if (outCount) *outCount = 0;
1627 if (isRequiredMethod) {
1628 if (isInstanceMethod) {
1629 mlist = proto->instance_methods;
1631 mlist = proto->class_methods;
1633 } else if ((ext = ext_for_protocol(proto))) {
1634 if (isInstanceMethod) {
1635 mlist = ext->optional_instance_methods;
1637 mlist = ext->optional_class_methods;
1642 if (outCount) *outCount = 0;
1646 count = mlist->count;
1648 calloc(count + 1, sizeof(struct objc_method_description));
1649 for (i = 0; i < count; i++) {
1650 result[i] = mlist->list[i];
1653 if (outCount) *outCount = count;
1658 objc_property_t protocol_getProperty(Protocol *p, const char *name,
1659 BOOL isRequiredProperty, BOOL isInstanceProperty)
1661 struct old_protocol *proto = oldprotocol(p);
1662 struct old_protocol_ext *ext;
1663 struct old_protocol_list *plist;
1665 if (!proto || !name) return NULL;
1667 if (!isRequiredProperty || !isInstanceProperty) {
1668 // Only required instance properties are currently supported
1672 if ((ext = ext_for_protocol(proto))) {
1673 struct old_property_list *plist;
1674 if ((plist = ext->instance_properties)) {
1676 for (i = 0; i < plist->count; i++) {
1677 struct old_property *prop = property_list_nth(plist, i);
1678 if (0 == strcmp(name, prop->name)) {
1679 return (objc_property_t)prop;
1685 if ((plist = proto->protocol_list)) {
1687 for (i = 0; i < plist->count; i++) {
1688 objc_property_t prop =
1689 protocol_getProperty((Protocol *)plist->list[i], name,
1690 isRequiredProperty, isInstanceProperty);
1691 if (prop) return prop;
1699 objc_property_t *protocol_copyPropertyList(Protocol *p, unsigned int *outCount)
1701 struct old_property **result = NULL;
1702 struct old_protocol_ext *ext;
1703 struct old_property_list *plist;
1705 struct old_protocol *proto = oldprotocol(p);
1706 if (! (ext = ext_for_protocol(proto))) {
1707 if (outCount) *outCount = 0;
1711 plist = ext->instance_properties;
1712 result = copyPropertyList(plist, outCount);
1714 return (objc_property_t *)result;
1718 /***********************************************************************
1719 * protocol_copyProtocolList
1720 * Copies this protocol's incorporated protocols.
1721 * Does not copy those protocol's incorporated protocols in turn.
1722 **********************************************************************/
1723 Protocol * __unsafe_unretained *
1724 protocol_copyProtocolList(Protocol *p, unsigned int *outCount)
1726 unsigned int count = 0;
1727 Protocol **result = NULL;
1728 struct old_protocol *proto = oldprotocol(p);
1731 if (outCount) *outCount = 0;
1735 if (proto->protocol_list) {
1736 count = (unsigned int)proto->protocol_list->count;
1740 result = malloc((count+1) * sizeof(Protocol *));
1742 for (i = 0; i < count; i++) {
1743 result[i] = (Protocol *)proto->protocol_list->list[i];
1748 if (outCount) *outCount = count;
1753 BOOL protocol_conformsToProtocol(Protocol *self_gen, Protocol *other_gen)
1755 struct old_protocol *self = oldprotocol(self_gen);
1756 struct old_protocol *other = oldprotocol(other_gen);
1758 if (!self || !other) {
1762 if (0 == strcmp(self->protocol_name, other->protocol_name)) {
1766 if (self->protocol_list) {
1768 for (i = 0; i < self->protocol_list->count; i++) {
1769 struct old_protocol *proto = self->protocol_list->list[i];
1770 if (0 == strcmp(other->protocol_name, proto->protocol_name)) {
1773 if (protocol_conformsToProtocol((Protocol *)proto, other_gen)) {
1783 BOOL protocol_isEqual(Protocol *self, Protocol *other)
1785 if (self == other) return YES;
1786 if (!self || !other) return NO;
1788 if (!protocol_conformsToProtocol(self, other)) return NO;
1789 if (!protocol_conformsToProtocol(other, self)) return NO;
1795 /***********************************************************************
1796 * objc_allocateProtocol
1797 * Creates a new protocol. The protocol may not be used until
1798 * objc_registerProtocol() is called.
1799 * Returns NULL if a protocol with the same name already exists.
1800 * Locking: acquires classLock
1801 **********************************************************************/
1803 objc_allocateProtocol(const char *name)
1805 Class cls = (Class)objc_getClass("__IncompleteProtocol");
1807 mutex_lock(&classLock);
1809 if (NXMapGet(protocol_map, name)) {
1810 mutex_unlock(&classLock);
1814 struct old_protocol *result = (struct old_protocol *)
1815 _calloc_internal(1, sizeof(struct old_protocol)
1816 + sizeof(struct old_protocol_ext));
1817 struct old_protocol_ext *ext = (struct old_protocol_ext *)(result+1);
1820 result->protocol_name = _strdup_internal(name);
1821 ext->size = sizeof(*ext);
1823 // fixme reserve name without installing
1825 NXMapInsert(protocol_ext_map, result, result+1);
1827 mutex_unlock(&classLock);
1829 return (Protocol *)result;
1833 /***********************************************************************
1834 * objc_registerProtocol
1835 * Registers a newly-constructed protocol. The protocol is now
1836 * ready for use and immutable.
1837 * Locking: acquires classLock
1838 **********************************************************************/
1839 void objc_registerProtocol(Protocol *proto_gen)
1841 struct old_protocol *proto = oldprotocol(proto_gen);
1843 Class oldcls = (Class)objc_getClass("__IncompleteProtocol");
1844 Class cls = (Class)objc_getClass("Protocol");
1846 mutex_lock(&classLock);
1848 if (proto->isa == cls) {
1849 _objc_inform("objc_registerProtocol: protocol '%s' was already "
1850 "registered!", proto->protocol_name);
1851 mutex_unlock(&classLock);
1854 if (proto->isa != oldcls) {
1855 _objc_inform("objc_registerProtocol: protocol '%s' was not allocated "
1856 "with objc_allocateProtocol!", proto->protocol_name);
1857 mutex_unlock(&classLock);
1863 NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto);
1865 mutex_unlock(&classLock);
1869 /***********************************************************************
1870 * protocol_addProtocol
1871 * Adds an incorporated protocol to another protocol.
1872 * No method enforcement is performed.
1873 * `proto` must be under construction. `addition` must not.
1874 * Locking: acquires classLock
1875 **********************************************************************/
1877 protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen)
1879 struct old_protocol *proto = oldprotocol(proto_gen);
1880 struct old_protocol *addition = oldprotocol(addition_gen);
1882 Class cls = (Class)objc_getClass("__IncompleteProtocol");
1884 if (!proto_gen) return;
1885 if (!addition_gen) return;
1887 mutex_lock(&classLock);
1889 if (proto->isa != cls) {
1890 _objc_inform("protocol_addProtocol: modified protocol '%s' is not "
1891 "under construction!", proto->protocol_name);
1892 mutex_unlock(&classLock);
1895 if (addition->isa == cls) {
1896 _objc_inform("protocol_addProtocol: added protocol '%s' is still "
1897 "under construction!", addition->protocol_name);
1898 mutex_unlock(&classLock);
1902 struct old_protocol_list *protolist = proto->protocol_list;
1904 size_t size = sizeof(*protolist)
1905 + protolist->count * sizeof(protolist->list[0]);
1906 protolist = (struct old_protocol_list *)
1907 _realloc_internal(protolist, size);
1909 protolist = (struct old_protocol_list *)
1910 _calloc_internal(1, sizeof(struct old_protocol_list));
1913 protolist->list[protolist->count++] = addition;
1914 proto->protocol_list = protolist;
1916 mutex_unlock(&classLock);
1920 /***********************************************************************
1921 * protocol_addMethodDescription
1922 * Adds a method to a protocol. The protocol must be under construction.
1923 * Locking: acquires classLock
1924 **********************************************************************/
1926 _protocol_addMethod(struct objc_method_description_list **list, SEL name, const char *types)
1929 *list = (struct objc_method_description_list *)
1930 _calloc_internal(sizeof(struct objc_method_description_list), 1);
1932 size_t size = sizeof(struct objc_method_description_list)
1933 + (*list)->count * sizeof(struct objc_method_description);
1934 *list = (struct objc_method_description_list *)
1935 _realloc_internal(*list, size);
1938 struct objc_method_description *desc = &(*list)->list[(*list)->count++];
1940 desc->types = _strdup_internal(types ?: "");
1944 protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types,
1945 BOOL isRequiredMethod, BOOL isInstanceMethod)
1947 struct old_protocol *proto = oldprotocol(proto_gen);
1949 Class cls = (Class)objc_getClass("__IncompleteProtocol");
1951 if (!proto_gen) return;
1953 mutex_lock(&classLock);
1955 if (proto->isa != cls) {
1956 _objc_inform("protocol_addMethodDescription: protocol '%s' is not "
1957 "under construction!", proto->protocol_name);
1958 mutex_unlock(&classLock);
1962 if (isRequiredMethod && isInstanceMethod) {
1963 _protocol_addMethod(&proto->instance_methods, name, types);
1964 } else if (isRequiredMethod && !isInstanceMethod) {
1965 _protocol_addMethod(&proto->class_methods, name, types);
1966 } else if (!isRequiredMethod && isInstanceMethod) {
1967 struct old_protocol_ext *ext = (struct old_protocol_ext *)(proto+1);
1968 _protocol_addMethod(&ext->optional_instance_methods, name, types);
1969 } else /* !isRequiredMethod && !isInstanceMethod) */ {
1970 struct old_protocol_ext *ext = (struct old_protocol_ext *)(proto+1);
1971 _protocol_addMethod(&ext->optional_class_methods, name, types);
1974 mutex_unlock(&classLock);
1978 /***********************************************************************
1979 * protocol_addProperty
1980 * Adds a property to a protocol. The protocol must be under construction.
1981 * Locking: acquires classLock
1982 **********************************************************************/
1984 _protocol_addProperty(struct old_property_list **plist, const char *name,
1985 const objc_property_attribute_t *attrs,
1989 *plist = (struct old_property_list *)
1990 _calloc_internal(sizeof(struct old_property_list), 1);
1991 (*plist)->entsize = sizeof(struct old_property);
1993 *plist = (struct old_property_list *)
1994 _realloc_internal(*plist, sizeof(struct old_property_list)
1995 + (*plist)->count * (*plist)->entsize);
1998 struct old_property *prop = property_list_nth(*plist, (*plist)->count++);
1999 prop->name = _strdup_internal(name);
2000 prop->attributes = copyPropertyAttributeString(attrs, count);
2004 protocol_addProperty(Protocol *proto_gen, const char *name,
2005 const objc_property_attribute_t *attrs,
2007 BOOL isRequiredProperty, BOOL isInstanceProperty)
2009 struct old_protocol *proto = oldprotocol(proto_gen);
2011 Class cls = (Class)objc_getClass("__IncompleteProtocol");
2016 mutex_lock(&classLock);
2018 if (proto->isa != cls) {
2019 _objc_inform("protocol_addProperty: protocol '%s' is not "
2020 "under construction!", proto->protocol_name);
2021 mutex_unlock(&classLock);
2025 struct old_protocol_ext *ext = ext_for_protocol(proto);
2027 if (isRequiredProperty && isInstanceProperty) {
2028 _protocol_addProperty(&ext->instance_properties, name, attrs, count);
2030 //else if (isRequiredProperty && !isInstanceProperty) {
2031 // _protocol_addProperty(&ext->class_properties, name, attrs, count);
2032 //} else if (!isRequiredProperty && isInstanceProperty) {
2033 // _protocol_addProperty(&ext->optional_instance_properties, name, attrs, count);
2034 //} else /* !isRequiredProperty && !isInstanceProperty) */ {
2035 // _protocol_addProperty(&ext->optional_class_properties, name, attrs, count);
2038 mutex_unlock(&classLock);
2042 /***********************************************************************
2043 * _objc_fixup_protocol_objects_for_image. For each protocol in the
2044 * specified image, selectorize the method names and add to the protocol hash.
2045 **********************************************************************/
2047 static BOOL versionIsExt(uintptr_t version, const char *names, size_t size)
2049 // CodeWarrior used isa field for string "Protocol"
2050 // from section __OBJC,__class_names. rdar://4951638
2051 // gcc (10.4 and earlier) used isa field for version number;
2052 // the only version number used on Mac OS X was 2.
2053 // gcc (10.5 and later) uses isa field for ext pointer
2055 if (version < 4096) {
2059 if (version >= (uintptr_t)names && version < (uintptr_t)(names + size)) {
2066 static void fix_protocol(struct old_protocol *proto, Class protocolClass,
2067 BOOL isBundle, const char *names, size_t names_size)
2072 version = (uintptr_t)proto->isa;
2074 // Set the protocol's isa
2075 proto->isa = protocolClass;
2077 // Fix up method lists
2078 // fixme share across duplicates
2079 map_method_descs (proto->instance_methods, isBundle);
2080 map_method_descs (proto->class_methods, isBundle);
2082 // Fix up ext, if any
2083 if (versionIsExt(version, names, names_size)) {
2084 struct old_protocol_ext *ext = (struct old_protocol_ext *)version;
2085 NXMapInsert(protocol_ext_map, proto, ext);
2086 map_method_descs (ext->optional_instance_methods, isBundle);
2087 map_method_descs (ext->optional_class_methods, isBundle);
2090 // Record the protocol it if we don't have one with this name yet
2091 // fixme bundles - copy protocol
2093 if (!NXMapGet(protocol_map, proto->protocol_name)) {
2094 NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto);
2095 if (PrintProtocols) {
2096 _objc_inform("PROTOCOLS: protocol at %p is %s",
2097 proto, proto->protocol_name);
2100 // duplicate - do nothing
2101 if (PrintProtocols) {
2102 _objc_inform("PROTOCOLS: protocol at %p is %s (duplicate)",
2103 proto, proto->protocol_name);
2108 static void _objc_fixup_protocol_objects_for_image (header_info * hi)
2110 Class protocolClass = (Class)objc_getClass("Protocol");
2112 struct old_protocol **protos;
2113 int isBundle = headerIsBundle(hi);
2117 mutex_lock(&classLock);
2119 // Allocate the protocol registry if necessary.
2120 if (!protocol_map) {
2122 NXCreateMapTableFromZone(NXStrValueMapPrototype, 32,
2123 _objc_internal_zone());
2125 if (!protocol_ext_map) {
2127 NXCreateMapTableFromZone(NXPtrValueMapPrototype, 32,
2128 _objc_internal_zone());
2131 protos = _getObjcProtocols(hi, &count);
2132 names = _getObjcClassNames(hi, &names_size);
2133 for (i = 0; i < count; i++) {
2134 fix_protocol(protos[i], protocolClass, isBundle, names, names_size);
2137 mutex_unlock(&classLock);
2141 /***********************************************************************
2142 * _objc_fixup_selector_refs. Register all of the selectors in each
2143 * image, and fix them all up.
2144 **********************************************************************/
2145 static void _objc_fixup_selector_refs (const header_info *hi)
2151 if (sel_preoptimizationValid(hi)) {
2152 _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors in %s",
2153 _nameForHeader(hi->mhdr));
2155 else if (_objcHeaderOptimizedByDyld(hi)) {
2156 _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors in %s",
2157 _nameForHeader(hi->mhdr));
2161 if (sel_preoptimizationValid(hi)) return;
2163 sels = _getObjcSelectorRefs (hi, &count);
2165 map_selrefs(sels, count, headerIsBundle(hi));
2168 static inline BOOL _is_threaded() {
2172 return pthread_is_threaded_np() != 0;
2176 #if !TARGET_OS_WIN32
2177 /***********************************************************************
2179 * Process the given image which is about to be unmapped by dyld.
2180 * mh is mach_header instead of headerType because that's what
2181 * dyld_priv.h says even for 64-bit.
2182 **********************************************************************/
2184 unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide)
2186 recursive_mutex_lock(&loadMethodLock);
2187 unmap_image_nolock(mh);
2188 recursive_mutex_unlock(&loadMethodLock);
2192 /***********************************************************************
2194 * Process the given images which are being mapped in by dyld.
2195 * Calls ABI-agnostic code after taking ABI-specific locks.
2196 **********************************************************************/
2197 PRIVATE_EXTERN const char *
2198 map_images(enum dyld_image_states state, uint32_t infoCount,
2199 const struct dyld_image_info infoList[])
2203 recursive_mutex_lock(&loadMethodLock);
2204 err = map_images_nolock(state, infoCount, infoList);
2205 recursive_mutex_unlock(&loadMethodLock);
2211 /***********************************************************************
2213 * Process +load in the given images which are being mapped in by dyld.
2214 * Calls ABI-agnostic code after taking ABI-specific locks.
2216 * Locking: acquires classLock and loadMethodLock
2217 **********************************************************************/
2218 PRIVATE_EXTERN const char *
2219 load_images(enum dyld_image_states state, uint32_t infoCount,
2220 const struct dyld_image_info infoList[])
2224 recursive_mutex_lock(&loadMethodLock);
2226 // Discover +load methods
2227 found = load_images_nolock(state, infoCount, infoList);
2229 // Call +load methods (without classLock - re-entrant)
2231 call_load_methods();
2234 recursive_mutex_unlock(&loadMethodLock);
2241 /***********************************************************************
2243 * Perform metadata processing for hCount images starting with firstNewHeader
2244 **********************************************************************/
2245 PRIVATE_EXTERN void _read_images(header_info **hList, uint32_t hCount)
2248 BOOL categoriesLoaded = NO;
2250 if (!class_hash) _objc_init_class_hash();
2252 // Parts of this order are important for correctness or performance.
2254 // Read classes from all images.
2255 for (i = 0; i < hCount; i++) {
2256 _objc_read_classes_from_image(hList[i]);
2259 // Read categories from all images.
2260 // But not if any other threads are running - they might
2261 // call a category method before the fixups below are complete.
2262 if (!_is_threaded()) {
2263 BOOL needFlush = NO;
2264 for (i = 0; i < hCount; i++) {
2265 needFlush |= _objc_read_categories_from_image(hList[i]);
2267 if (needFlush) flush_marked_caches();
2268 categoriesLoaded = YES;
2271 // Connect classes from all images.
2272 for (i = 0; i < hCount; i++) {
2273 _objc_connect_classes_from_image(hList[i]);
2276 // Fix up class refs, selector refs, and protocol objects from all images.
2277 for (i = 0; i < hCount; i++) {
2278 _objc_map_class_refs_for_image(hList[i]);
2279 _objc_fixup_selector_refs(hList[i]);
2280 _objc_fixup_protocol_objects_for_image(hList[i]);
2283 // Read categories from all images.
2284 // But not if this is the only thread - it's more
2285 // efficient to attach categories earlier if safe.
2286 if (!categoriesLoaded) {
2287 BOOL needFlush = NO;
2288 for (i = 0; i < hCount; i++) {
2289 needFlush |= _objc_read_categories_from_image(hList[i]);
2291 if (needFlush) flush_marked_caches();
2294 // Multi-threaded category load MUST BE LAST to avoid a race.
2298 /***********************************************************************
2299 * prepare_load_methods
2300 * Schedule +load for classes in this image, any un-+load-ed
2301 * superclasses in other images, and any categories in this image.
2302 **********************************************************************/
2303 // Recursively schedule +load for cls and any un-+load-ed superclasses.
2304 // cls must already be connected.
2305 static void schedule_class_load(struct old_class *cls)
2307 if (cls->info & CLS_LOADED) return;
2308 if (cls->super_class) schedule_class_load(cls->super_class);
2309 add_class_to_loadable_list((Class)cls);
2310 cls->info |= CLS_LOADED;
2313 PRIVATE_EXTERN void prepare_load_methods(header_info *hi)
2319 if (_objcHeaderIsReplacement(hi)) {
2320 // Ignore any classes in this image
2324 // Major loop - process all modules in the image
2326 for (midx = 0; midx < hi->mod_count; midx += 1)
2330 // Skip module containing no classes
2331 if (mods[midx].symtab == NULL)
2334 // Minor loop - process all the classes in given module
2335 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
2337 // Locate the class description pointer
2338 struct old_class *cls = mods[midx].symtab->defs[index];
2339 if (cls->info & CLS_CONNECTED) {
2340 schedule_class_load(cls);
2346 // Major loop - process all modules in the header
2349 // NOTE: The module and category lists are traversed backwards
2350 // to preserve the pre-10.4 processing order. Changing the order
2351 // would have a small chance of introducing binary compatibility bugs.
2352 midx = (unsigned int)hi->mod_count;
2353 while (midx-- > 0) {
2356 Symtab symtab = mods[midx].symtab;
2358 // Nothing to do for a module without a symbol table
2359 if (mods[midx].symtab == NULL)
2361 // Total entries in symbol table (class entries followed
2362 // by category entries)
2363 total = mods[midx].symtab->cls_def_cnt +
2364 mods[midx].symtab->cat_def_cnt;
2366 // Minor loop - register all categories from given module
2368 while (index-- > mods[midx].symtab->cls_def_cnt) {
2369 struct old_category *cat = symtab->defs[index];
2370 add_category_to_loadable_list((Category)cat);
2378 PRIVATE_EXTERN void unload_class(struct old_class *cls)
2384 /***********************************************************************
2385 * _objc_remove_classes_in_image
2386 * Remove all classes in the given image from the runtime, because
2387 * the image is about to be unloaded.
2388 * Things to clean up:
2390 * unconnected_class_hash
2391 * pending subclasses list (only if class is still unconnected)
2392 * loadable class list
2393 * class's method caches
2394 * class refs in all other images
2395 **********************************************************************/
2396 // Re-pend any class references in refs that point into [start..end)
2397 static void rependClassReferences(struct old_class **refs, size_t count,
2398 uintptr_t start, uintptr_t end)
2404 // Process each class ref
2405 for (i = 0; i < count; i++) {
2406 if ((uintptr_t)(refs[i]) >= start && (uintptr_t)(refs[i]) < end) {
2407 pendClassReference(&refs[i], refs[i]->name,
2408 (refs[i]->info & CLS_META) ? YES : NO);
2415 PRIVATE_EXTERN void try_free(const void *p)
2417 if (p && malloc_size(p)) free((void *)p);
2420 // Deallocate all memory in a method list
2421 static void unload_mlist(struct old_method_list *mlist)
2424 for (i = 0; i < mlist->method_count; i++) {
2425 try_free(mlist->method_list[i].method_types);
2430 static void unload_property_list(struct old_property_list *proplist)
2434 if (!proplist) return;
2436 for (i = 0; i < proplist->count; i++) {
2437 struct old_property *prop = property_list_nth(proplist, i);
2438 try_free(prop->name);
2439 try_free(prop->attributes);
2445 // Deallocate all memory in a class.
2446 PRIVATE_EXTERN void unload_class(struct old_class *cls)
2448 // Free method cache
2449 // This dereferences the cache contents; do this before freeing methods
2450 if (cls->cache && cls->cache != &_objc_empty_cache) {
2451 _cache_free(cls->cache);
2457 for (i = 0; i < cls->ivars->ivar_count; i++) {
2458 try_free(cls->ivars->ivar_list[i].ivar_name);
2459 try_free(cls->ivars->ivar_list[i].ivar_type);
2461 try_free(cls->ivars);
2464 // Free fixed-up method lists and method list array
2465 if (cls->methodLists) {
2466 // more than zero method lists
2467 if (cls->info & CLS_NO_METHOD_ARRAY) {
2469 unload_mlist((struct old_method_list *)cls->methodLists);
2472 // more than one method list
2473 struct old_method_list **mlistp;
2474 for (mlistp = cls->methodLists;
2475 *mlistp != NULL && *mlistp != END_OF_METHODS_LIST;
2478 unload_mlist(*mlistp);
2480 free(cls->methodLists);
2484 // Free protocol list
2485 struct old_protocol_list *protos = cls->protocols;
2487 struct old_protocol_list *dead = protos;
2488 protos = protos->next;
2492 if ((cls->info & CLS_EXT)) {
2494 // Free property lists and property list array
2495 if (cls->ext->propertyLists) {
2496 // more than zero property lists
2497 if (cls->info & CLS_NO_PROPERTY_ARRAY) {
2498 // one property list
2499 struct old_property_list *proplist =
2500 (struct old_property_list *)cls->ext->propertyLists;
2501 unload_property_list(proplist);
2503 // more than one property list
2504 struct old_property_list **plistp;
2505 for (plistp = cls->ext->propertyLists;
2509 unload_property_list(*plistp);
2511 try_free(cls->ext->propertyLists);
2515 // Free weak ivar layout
2516 try_free(cls->ext->weak_ivar_layout);
2522 // Free non-weak ivar layout
2523 try_free(cls->ivar_layout);
2527 try_free(cls->name);
2534 static void _objc_remove_classes_in_image(header_info *hi)
2540 mutex_lock(&classLock);
2542 // Major loop - process all modules in the image
2544 for (midx = 0; midx < hi->mod_count; midx += 1)
2546 // Skip module containing no classes
2547 if (mods[midx].symtab == NULL)
2550 // Minor loop - process all the classes in given module
2551 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
2553 struct old_class *cls;
2555 // Locate the class description pointer
2556 cls = mods[midx].symtab->defs[index];
2558 // Remove from loadable class list, if present
2559 remove_class_from_loadable_list((Class)cls);
2561 // Remove from unconnected_class_hash and pending subclasses
2562 if (unconnected_class_hash && NXHashMember(unconnected_class_hash, cls)) {
2563 NXHashRemove(unconnected_class_hash, cls);
2564 if (pendingSubclassesMap) {
2565 // Find this class in its superclass's pending list
2566 char *supercls_name = (char *)cls->super_class;
2567 PendingSubclass *pending =
2568 NXMapGet(pendingSubclassesMap, supercls_name);
2569 for ( ; pending != NULL; pending = pending->next) {
2570 if (pending->subclass == cls) {
2571 pending->subclass = Nil;
2578 // Remove from class_hash
2579 NXHashRemove(class_hash, cls);
2580 objc_removeRegisteredClass((Class)cls);
2582 // Free heap memory pointed to by the class
2583 unload_class(cls->isa);
2589 // Search all other images for class refs that point back to this range.
2590 // Un-fix and re-pend any such class refs.
2592 // Get the location of the dying image's __OBJC segment
2594 unsigned long seg_size;
2595 seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size);
2597 header_info *other_hi;
2598 for (other_hi = FirstHeader; other_hi != NULL; other_hi = other_hi->next) {
2599 struct old_class **other_refs;
2601 if (other_hi == hi) continue; // skip the image being unloaded
2603 // Fix class refs in the other image
2604 other_refs = _getObjcClassRefs(other_hi, &count);
2605 rependClassReferences(other_refs, count, seg, seg+seg_size);
2608 mutex_unlock(&classLock);
2612 /***********************************************************************
2613 * _objc_remove_categories_in_image
2614 * Remove all categories in the given image from the runtime, because
2615 * the image is about to be unloaded.
2616 * Things to clean up:
2617 * unresolved category list
2618 * loadable category list
2619 **********************************************************************/
2620 static void _objc_remove_categories_in_image(header_info *hi)
2625 // Major loop - process all modules in the header
2628 for (midx = 0; midx < hi->mod_count; midx++) {
2631 Symtab symtab = mods[midx].symtab;
2633 // Nothing to do for a module without a symbol table
2634 if (symtab == NULL) continue;
2636 // Total entries in symbol table (class entries followed
2637 // by category entries)
2638 total = symtab->cls_def_cnt + symtab->cat_def_cnt;
2640 // Minor loop - check all categories from given module
2641 for (index = symtab->cls_def_cnt; index < total; index++) {
2642 struct old_category *cat = symtab->defs[index];
2644 // Clean up loadable category list
2645 remove_category_from_loadable_list((Category)cat);
2647 // Clean up category_hash
2648 if (category_hash) {
2649 _objc_unresolved_category *cat_entry =
2650 NXMapGet(category_hash, cat->class_name);
2651 for ( ; cat_entry != NULL; cat_entry = cat_entry->next) {
2652 if (cat_entry->cat == cat) {
2653 cat_entry->cat = NULL;
2663 /***********************************************************************
2665 * Various paranoid debugging checks that look for poorly-behaving
2666 * unloadable bundles.
2667 * Called by _objc_unmap_image when OBJC_UNLOAD_DEBUG is set.
2668 **********************************************************************/
2669 static void unload_paranoia(header_info *hi)
2671 // Get the location of the dying image's __OBJC segment
2673 unsigned long seg_size;
2674 seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size);
2676 _objc_inform("UNLOAD DEBUG: unloading image '%s' [%p..%p]",
2677 _nameForHeader(hi->mhdr), (void *)seg, (void*)(seg+seg_size));
2679 mutex_lock(&classLock);
2681 // Make sure the image contains no categories on surviving classes.
2686 // Major loop - process all modules in the header
2689 for (midx = 0; midx < hi->mod_count; midx++) {
2692 Symtab symtab = mods[midx].symtab;
2694 // Nothing to do for a module without a symbol table
2695 if (symtab == NULL) continue;
2697 // Total entries in symbol table (class entries followed
2698 // by category entries)
2699 total = symtab->cls_def_cnt + symtab->cat_def_cnt;
2701 // Minor loop - check all categories from given module
2702 for (index = symtab->cls_def_cnt; index < total; index++) {
2703 struct old_category *cat = symtab->defs[index];
2704 struct old_class query;
2706 query.name = cat->class_name;
2707 if (NXHashMember(class_hash, &query)) {
2708 _objc_inform("UNLOAD DEBUG: dying image contains category '%s(%s)' on surviving class '%s'!", cat->class_name, cat->category_name, cat->class_name);
2714 // Make sure no surviving class is in the dying image.
2715 // Make sure no surviving class has a superclass in the dying image.
2716 // fixme check method implementations too
2718 struct old_class *cls;
2721 state = NXInitHashState(class_hash);
2722 while (NXNextHashState(class_hash, &state, (void **)&cls)) {
2723 if ((vm_address_t)cls >= seg &&
2724 (vm_address_t)cls < seg+seg_size)
2726 _objc_inform("UNLOAD DEBUG: dying image contains surviving class '%s'!", cls->name);
2729 if ((vm_address_t)cls->super_class >= seg &&
2730 (vm_address_t)cls->super_class < seg+seg_size)
2732 _objc_inform("UNLOAD DEBUG: dying image contains superclass '%s' of surviving class '%s'!", cls->super_class->name, cls->name);
2737 mutex_unlock(&classLock);
2741 /***********************************************************************
2743 * Only handles MH_BUNDLE for now.
2744 * Locking: loadMethodLock acquired by unmap_image
2745 **********************************************************************/
2746 PRIVATE_EXTERN void _unload_image(header_info *hi)
2748 recursive_mutex_assert_locked(&loadMethodLock);
2751 // Remove image's classes from the class list and free auxiliary data.
2752 // Remove image's unresolved or loadable categories and free auxiliary data
2753 // Remove image's unresolved class refs.
2754 _objc_remove_classes_in_image(hi);
2755 _objc_remove_categories_in_image(hi);
2756 _objc_remove_pending_class_refs_in_image(hi);
2758 // Perform various debugging checks if requested.
2759 if (DebugUnload) unload_paranoia(hi);
2765 /***********************************************************************
2766 * objc_addClass. Add the specified class to the table of known classes,
2767 * after doing a little verification and fixup.
2768 **********************************************************************/
2769 void objc_addClass (Class cls_gen)
2771 struct old_class *cls = oldcls(cls_gen);
2773 OBJC_WARN_DEPRECATED;
2775 // Synchronize access to hash table
2776 mutex_lock (&classLock);
2778 // Make sure both the class and the metaclass have caches!
2779 // Clear all bits of the info fields except CLS_CLASS and CLS_META.
2780 // Normally these bits are already clear but if someone tries to cons
2781 // up their own class on the fly they might need to be cleared.
2782 if (cls->cache == NULL) {
2783 cls->cache = (Cache) &_objc_empty_cache;
2784 cls->info = CLS_CLASS;
2787 if (cls->isa->cache == NULL) {
2788 cls->isa->cache = (Cache) &_objc_empty_cache;
2789 cls->isa->info = CLS_META;
2792 // methodLists should be:
2793 // 1. NULL (Tiger and later only)
2794 // 2. A -1 terminated method list array
2795 // In either case, CLS_NO_METHOD_ARRAY remains clear.
2796 // If the user manipulates the method list directly,
2797 // they must use the magic private format.
2799 // Add the class to the table
2800 (void) NXHashInsert (class_hash, cls);
2801 objc_addRegisteredClass((Class)cls);
2803 // Superclass is no longer a leaf for cache flushing
2804 if (cls->super_class && (cls->super_class->info & CLS_LEAF)) {
2805 _class_clearInfo((Class)cls->super_class, CLS_LEAF);
2806 _class_clearInfo((Class)cls->super_class->isa, CLS_LEAF);
2810 mutex_unlock (&classLock);
2813 /***********************************************************************
2814 * _objcTweakMethodListPointerForClass.
2815 * Change the class's method list pointer to a method list array.
2816 * Does nothing if the method list pointer is already a method list array.
2817 * If the class is currently in use, methodListLock must be held by the caller.
2818 **********************************************************************/
2819 static void _objcTweakMethodListPointerForClass(struct old_class *cls)
2821 struct old_method_list * originalList;
2822 const int initialEntries = 4;
2824 struct old_method_list ** ptr;
2826 // Do nothing if methodLists is already an array.
2827 if (cls->methodLists && !(cls->info & CLS_NO_METHOD_ARRAY)) return;
2829 // Remember existing list
2830 originalList = (struct old_method_list *) cls->methodLists;
2832 // Allocate and zero a method list array
2833 mallocSize = sizeof(struct old_method_list *) * initialEntries;
2834 ptr = (struct old_method_list **) _calloc_internal(1, mallocSize);
2836 // Insert the existing list into the array
2837 ptr[initialEntries - 1] = END_OF_METHODS_LIST;
2838 ptr[0] = originalList;
2840 // Replace existing list with array
2841 cls->methodLists = ptr;
2842 _class_clearInfo((Class)cls, CLS_NO_METHOD_ARRAY);
2846 /***********************************************************************
2847 * _objc_insertMethods.
2848 * Adds methods to a class.
2849 * Does not flush any method caches.
2850 * Does not take any locks.
2851 * If the class is already in use, use class_addMethods() instead.
2852 **********************************************************************/
2853 PRIVATE_EXTERN void _objc_insertMethods(struct old_class *cls,
2854 struct old_method_list *mlist,
2855 struct old_category *cat)
2857 struct old_method_list ***list;
2858 struct old_method_list **ptr;
2863 if (!cls->methodLists) {
2864 // cls has no methods - simply use this method list
2865 cls->methodLists = (struct old_method_list **)mlist;
2866 _class_setInfo((Class)cls, CLS_NO_METHOD_ARRAY);
2870 // Log any existing methods being replaced
2871 if (PrintReplacedMethods) {
2873 for (i = 0; i < mlist->method_count; i++) {
2874 extern IMP findIMPInClass(struct old_class *cls, SEL sel);
2875 SEL sel = sel_registerName((char *)mlist->method_list[i].method_name);
2876 IMP newImp = mlist->method_list[i].method_imp;
2879 if ((oldImp = findIMPInClass(cls, sel))) {
2880 logReplacedMethod(cls->name, sel, ISMETA(cls),
2881 cat ? cat->category_name : NULL,
2887 // Create method list array if necessary
2888 _objcTweakMethodListPointerForClass(cls);
2890 list = &cls->methodLists;
2892 // Locate unused entry for insertion point
2894 while ((*ptr != 0) && (*ptr != END_OF_METHODS_LIST))
2897 // If array is full, add to it
2898 if (*ptr == END_OF_METHODS_LIST)
2900 // Calculate old and new dimensions
2901 endIndex = ptr - *list;
2902 oldSize = (endIndex + 1) * sizeof(void *);
2903 newSize = oldSize + sizeof(struct old_method_list *); // only increase by 1
2905 // Grow the method list array by one.
2906 // This block may be from user code; don't use _realloc_internal
2907 *list = (struct old_method_list **)realloc(*list, newSize);
2909 // Zero out addition part of new array
2910 bzero (&((*list)[endIndex]), newSize - oldSize);
2912 // Place new end marker
2913 (*list)[(newSize/sizeof(void *)) - 1] = END_OF_METHODS_LIST;
2915 // Insertion point corresponds to old array end
2916 ptr = &((*list)[endIndex]);
2919 // Right shift existing entries by one
2920 bcopy (*list, (*list) + 1, (uint8_t *)ptr - (uint8_t *)*list);
2922 // Insert at method list at beginning of array
2926 /***********************************************************************
2927 * _objc_removeMethods.
2928 * Remove methods from a class.
2929 * Does not take any locks.
2930 * Does not flush any method caches.
2931 * If the class is currently in use, use class_removeMethods() instead.
2932 **********************************************************************/
2933 PRIVATE_EXTERN void _objc_removeMethods(struct old_class *cls,
2934 struct old_method_list *mlist)
2936 struct old_method_list ***list;
2937 struct old_method_list **ptr;
2939 if (cls->methodLists == NULL) {
2940 // cls has no methods
2943 if (cls->methodLists == (struct old_method_list **)mlist) {
2944 // mlist is the class's only method list - erase it
2945 cls->methodLists = NULL;
2948 if (cls->info & CLS_NO_METHOD_ARRAY) {
2949 // cls has only one method list, and this isn't it - do nothing
2953 // cls has a method list array - search it
2955 list = &cls->methodLists;
2957 // Locate list in the array
2959 while (*ptr != mlist) {
2960 // fix for radar # 2538790
2961 if ( *ptr == END_OF_METHODS_LIST ) return;
2965 // Remove this entry
2968 // Left shift the following entries
2969 while (*(++ptr) != END_OF_METHODS_LIST)
2974 /***********************************************************************
2975 * _objc_add_category. Install the specified category's methods and
2976 * protocols into the class it augments.
2977 * The class is assumed not to be in use yet: no locks are taken and
2978 * no method caches are flushed.
2979 **********************************************************************/
2980 static inline void _objc_add_category(struct old_class *cls, struct old_category *category, int version)
2982 if (PrintConnecting) {
2983 _objc_inform("CONNECT: attaching category '%s (%s)'", cls->name, category->category_name);
2986 // Augment instance methods
2987 if (category->instance_methods)
2988 _objc_insertMethods (cls, category->instance_methods, category);
2990 // Augment class methods
2991 if (category->class_methods)
2992 _objc_insertMethods (cls->isa, category->class_methods, category);
2994 // Augment protocols
2995 if ((version >= 5) && category->protocols)
2997 if (cls->isa->version >= 5)
2999 category->protocols->next = cls->protocols;
3000 cls->protocols = category->protocols;
3001 cls->isa->protocols = category->protocols;
3005 _objc_inform ("unable to add protocols from category %s...\n", category->category_name);
3006 _objc_inform ("class `%s' must be recompiled\n", category->class_name);
3010 // Augment properties
3011 if (version >= 7 && category->instance_properties) {
3012 if (cls->isa->version >= 6) {
3013 _class_addProperties(cls, category->instance_properties);
3015 _objc_inform ("unable to add properties from category %s...\n", category->category_name);
3016 _objc_inform ("class `%s' must be recompiled\n", category->class_name);
3021 /***********************************************************************
3022 * _objc_add_category_flush_caches. Install the specified category's
3023 * methods into the class it augments, and flush the class' method cache.
3024 * Return YES if some method caches now need to be flushed.
3025 **********************************************************************/
3026 static BOOL _objc_add_category_flush_caches(struct old_class *cls, struct old_category *category, int version)
3028 BOOL needFlush = NO;
3030 // Install the category's methods into its intended class
3031 mutex_lock(&methodListLock);
3032 _objc_add_category (cls, category, version);
3033 mutex_unlock(&methodListLock);
3035 // Queue for cache flushing so category's methods can get called
3036 if (category->instance_methods) {
3037 _class_setInfo((Class)cls, CLS_FLUSH_CACHE);
3040 if (category->class_methods) {
3041 _class_setInfo((Class)cls->isa, CLS_FLUSH_CACHE);
3049 /***********************************************************************
3051 * Reverse the given linked list of pending categories.
3052 * The pending category list is built backwards, and needs to be
3053 * reversed before actually attaching the categories to a class.
3054 * Returns the head of the new linked list.
3055 **********************************************************************/
3056 static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat)
3058 _objc_unresolved_category *prev;
3059 _objc_unresolved_category *cur;
3060 _objc_unresolved_category *ahead;
3062 if (!cat) return NULL;
3079 /***********************************************************************
3080 * resolve_categories_for_class.
3081 * Install all existing categories intended for the specified class.
3082 * cls must be a true class and not a metaclass.
3083 **********************************************************************/
3084 static void resolve_categories_for_class(struct old_class *cls)
3086 _objc_unresolved_category * pending;
3087 _objc_unresolved_category * next;
3089 // Nothing to do if there are no categories at all
3090 if (!category_hash) return;
3092 // Locate and remove first element in category list
3093 // associated with this class
3094 pending = NXMapKeyFreeingRemove (category_hash, cls->name);
3096 // Traverse the list of categories, if any, registered for this class
3098 // The pending list is built backwards. Reverse it and walk forwards.
3099 pending = reverse_cat(pending);
3103 // Install the category
3104 // use the non-flush-cache version since we are only
3105 // called from the class intialization code
3106 _objc_add_category(cls, pending->cat, (int)pending->version);
3109 // Delink and reclaim this registration
3110 next = pending->next;
3111 _free_internal(pending);
3117 /***********************************************************************
3118 * _objc_resolve_categories_for_class.
3119 * Public version of resolve_categories_for_class. This was
3120 * exported pre-10.4 for Omni et al. to workaround a problem
3121 * with too-lazy category attachment.
3122 * cls should be a class, but this function can also cope with metaclasses.
3123 **********************************************************************/
3124 void _objc_resolve_categories_for_class(Class cls_gen)
3126 struct old_class *cls = oldcls(cls_gen);
3128 // If cls is a metaclass, get the class.
3129 // resolve_categories_for_class() requires a real class to work correctly.
3131 if (strncmp(cls->name, "_%", 2) == 0) {
3132 // Posee's meta's name is smashed and isn't in the class_hash,
3133 // so objc_getClass doesn't work.
3134 const char *baseName = strchr(cls->name, '%'); // get posee's real name
3135 cls = oldcls((Class)objc_getClass(baseName));
3137 cls = oldcls((Class)objc_getClass(cls->name));
3141 resolve_categories_for_class(cls);
3145 /***********************************************************************
3146 * _objc_register_category.
3147 * Process a category read from an image.
3148 * If the category's class exists, attach the category immediately.
3149 * Classes that need cache flushing are marked but not flushed.
3150 * If the category's class does not exist yet, pend the category for
3151 * later attachment. Pending categories are attached in the order
3152 * they were discovered.
3153 * Returns YES if some method caches now need to be flushed.
3154 **********************************************************************/
3155 static BOOL _objc_register_category(struct old_category *cat, int version)
3157 _objc_unresolved_category * new_cat;
3158 _objc_unresolved_category * old;
3159 struct old_class *theClass;
3161 // If the category's class exists, attach the category.
3162 if ((theClass = oldcls((Class)objc_lookUpClass(cat->class_name)))) {
3163 return _objc_add_category_flush_caches(theClass, cat, version);
3166 // If the category's class exists but is unconnected,
3167 // then attach the category to the class but don't bother
3168 // flushing any method caches (because they must be empty).
3169 // YES unconnected, NO class_handler
3170 if ((theClass = oldcls((Class)look_up_class(cat->class_name, YES, NO)))) {
3171 _objc_add_category(theClass, cat, version);
3176 // Category's class does not exist yet.
3177 // Save the category for later attachment.
3179 if (PrintConnecting) {
3180 _objc_inform("CONNECT: pending category '%s (%s)'", cat->class_name, cat->category_name);
3183 // Create category lookup table if needed
3185 category_hash = NXCreateMapTableFromZone (NXStrValueMapPrototype,
3187 _objc_internal_zone ());
3189 // Locate an existing list of categories, if any, for the class.
3190 old = NXMapGet (category_hash, cat->class_name);
3192 // Register the category to be fixed up later.
3193 // The category list is built backwards, and is reversed again
3194 // by resolve_categories_for_class().
3195 new_cat = _malloc_internal(sizeof(_objc_unresolved_category));
3196 new_cat->next = old;
3198 new_cat->version = version;
3199 (void) NXMapKeyCopyingInsert (category_hash, cat->class_name, new_cat);
3205 PRIVATE_EXTERN const char **
3206 _objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount)
3219 for (m = 0; m < hi->mod_count; m++) {
3222 if (!mods[m].symtab) continue;
3224 for (d = 0; d < mods[m].symtab->cls_def_cnt; d++) {
3225 struct old_class *cls = mods[m].symtab->defs[d];
3226 // fixme what about future-ified classes?
3227 if (class_is_connected(cls)) {
3228 if (count == allocated) {
3229 allocated = allocated*2 + 16;
3230 list = (const char **)
3231 realloc((void *)list, allocated * sizeof(char *));
3233 list[count++] = cls->name;
3239 // NULL-terminate non-empty list
3240 if (count == allocated) {
3241 allocated = allocated+1;
3242 list = (const char **)
3243 realloc((void *)list, allocated * sizeof(char *));
3248 if (outCount) *outCount = count;
3252 Class gdb_class_getClass(Class cls)
3254 const char *className = cls->name;
3255 if(!className || !strlen(className)) return Nil;
3256 Class rCls = look_up_class(className, NO, NO);
3261 Class gdb_object_getClass(id obj)
3263 Class cls = _object_getClass(obj);
3264 return gdb_class_getClass(cls);
3267 BOOL gdb_objc_isRuntimeLocked()
3269 if (mutex_try_lock(&methodListLock)) {
3270 mutex_unlock(&methodListLock);
3274 if (mutex_try_lock(&classLock)) {
3275 mutex_unlock(&classLock);
3279 if (mutex_try_lock(&cacheUpdateLock)) {
3280 mutex_unlock(&cacheUpdateLock);
3288 /***********************************************************************
3290 * Every lock used anywhere must be managed here.
3291 * Locks not managed here may cause gdb deadlocks.
3292 **********************************************************************/
3293 PRIVATE_EXTERN rwlock_t selLock = {0};
3294 PRIVATE_EXTERN mutex_t classLock = MUTEX_INITIALIZER;
3295 PRIVATE_EXTERN mutex_t methodListLock = MUTEX_INITIALIZER;
3296 PRIVATE_EXTERN mutex_t cacheUpdateLock = MUTEX_INITIALIZER;
3297 PRIVATE_EXTERN recursive_mutex_t loadMethodLock = RECURSIVE_MUTEX_INITIALIZER;
3298 static int debugger_selLock;
3299 static int debugger_loadMethodLock;
3303 PRIVATE_EXTERN void lock_init(void)
3305 rwlock_init(&selLock);
3306 recursive_mutex_init(&loadMethodLock);
3310 #if SUPPORT_DEBUGGER_MODE
3312 /***********************************************************************
3314 * Attempt to acquire some locks for debugger mode.
3315 * Returns 0 if debugger mode failed because too many locks are unavailable.
3317 * Locks successfully acquired are held until endDebuggerMode().
3318 * Locks not acquired are off-limits until endDebuggerMode(); any
3319 * attempt to manipulate them will cause a trap.
3320 * Locks not handled here may cause deadlocks in gdb.
3321 **********************************************************************/
3322 PRIVATE_EXTERN int startDebuggerMode(void)
3324 int result = DEBUGGER_FULL;
3326 // classLock is required
3327 // methodListLock is required
3328 // cacheUpdateLock is required
3329 // fixme might be able to allow all-or-none
3330 if (! mutex_try_lock(&classLock)) {
3331 return DEBUGGER_OFF;
3333 if (! mutex_try_lock(&methodListLock)) {
3334 mutex_unlock(&classLock);
3335 return DEBUGGER_OFF;
3337 if (! mutex_try_lock(&cacheUpdateLock)) {
3338 mutex_unlock(&methodListLock);
3339 mutex_unlock(&classLock);
3340 return DEBUGGER_OFF;
3343 // selLock is optional
3344 if (rwlock_try_write(&selLock)) {
3345 debugger_selLock = RDWR;
3346 } else if (rwlock_try_read(&selLock)) {
3347 debugger_selLock = RDONLY;
3348 result = DEBUGGER_PARTIAL;
3350 debugger_selLock = 0;
3351 result = DEBUGGER_PARTIAL;
3354 // loadMethodLock is optional
3355 if (recursive_mutex_try_lock(&loadMethodLock)) {
3356 debugger_loadMethodLock = RDWR;
3358 debugger_loadMethodLock = 0;
3359 result = DEBUGGER_PARTIAL;
3365 /***********************************************************************
3367 * Relinquish locks acquired in startDebuggerMode().
3368 **********************************************************************/
3369 PRIVATE_EXTERN void endDebuggerMode(void)
3371 if (debugger_loadMethodLock) {
3372 recursive_mutex_unlock(&loadMethodLock);
3373 debugger_loadMethodLock = 0;
3375 rwlock_unlock(&selLock, debugger_selLock);
3376 debugger_selLock = 0;
3377 mutex_unlock(&classLock);
3378 mutex_unlock(&methodListLock);
3379 mutex_unlock(&cacheUpdateLock);
3382 /***********************************************************************
3383 * isManagedDuringDebugger
3384 * Returns YES if the given lock is handled specially during debugger
3385 * mode (i.e. debugger mode tries to acquire it).
3386 **********************************************************************/
3387 PRIVATE_EXTERN BOOL isManagedDuringDebugger(void *lock)
3389 if (lock == &selLock) return YES;
3390 if (lock == &classLock) return YES;
3391 if (lock == &methodListLock) return YES;
3392 if (lock == &cacheUpdateLock) return YES;
3393 if (lock == &loadMethodLock) return YES;
3397 /***********************************************************************
3398 * isLockedDuringDebugger
3399 * Returns YES if the given mutex was acquired by debugger mode.
3400 * Locking a managed mutex during debugger mode causes a trap unless
3402 **********************************************************************/
3403 PRIVATE_EXTERN BOOL isLockedDuringDebugger(mutex_t *lock)
3405 assert(DebuggerMode);
3407 if (lock == &classLock) return YES;
3408 if (lock == &methodListLock) return YES;
3409 if (lock == &cacheUpdateLock) return YES;
3410 if (lock == (mutex_t *)&loadMethodLock) return YES;
3415 /***********************************************************************
3416 * isReadingDuringDebugger
3417 * Returns YES if the given rwlock was read-locked by debugger mode.
3418 * Read-locking a managed rwlock during debugger mode causes a trap unless
3420 **********************************************************************/
3421 PRIVATE_EXTERN BOOL isReadingDuringDebugger(rwlock_t *lock)
3423 assert(DebuggerMode);
3425 // read-lock is allowed even if debugger mode actually write-locked it
3426 if (debugger_selLock && lock == &selLock) return YES;
3431 /***********************************************************************
3432 * isWritingDuringDebugger
3433 * Returns YES if the given rwlock was write-locked by debugger mode.
3434 * Write-locking a managed rwlock during debugger mode causes a trap unless
3436 **********************************************************************/
3437 PRIVATE_EXTERN BOOL isWritingDuringDebugger(rwlock_t *lock)
3439 assert(DebuggerMode);
3441 if (debugger_selLock == RDWR && lock == &selLock) return YES;
3446 // SUPPORT_DEBUGGER_MODE