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"
149 typedef struct _objc_unresolved_category
151 struct _objc_unresolved_category *next;
152 struct old_category *cat; // may be NULL
154 } _objc_unresolved_category;
156 typedef struct _PendingSubclass
158 struct old_class *subclass; // subclass to finish connecting; may be NULL
159 struct _PendingSubclass *next;
162 typedef struct _PendingClassRef
164 struct old_class **ref; // class reference to fix up; may be NULL
165 // (ref & 1) is a metaclass reference
166 struct _PendingClassRef *next;
170 static uintptr_t classHash(void *info, Class data);
171 static int classIsEqual(void *info, Class name, Class cls);
172 static int _objc_defaultClassHandler(const char *clsName);
173 static BOOL class_is_connected(struct old_class *cls);
174 static inline NXMapTable *pendingClassRefsMapTable(void);
175 static inline NXMapTable *pendingSubclassesMapTable(void);
176 static void pendClassInstallation(struct old_class *cls, const char *superName);
177 static void pendClassReference(struct old_class **ref, const char *className, BOOL isMeta);
178 static void resolve_references_to_class(struct old_class *cls);
179 static void resolve_subclasses_of_class(struct old_class *cls);
180 static void really_connect_class(struct old_class *cls, struct old_class *supercls);
181 static BOOL connect_class(struct old_class *cls);
182 static void map_method_descs (struct objc_method_description_list * methods, BOOL copy);
183 static void _objcTweakMethodListPointerForClass(struct old_class *cls);
184 static inline void _objc_add_category(struct old_class *cls, struct old_category *category, int version);
185 static BOOL _objc_add_category_flush_caches(struct old_class *cls, struct old_category *category, int version);
186 static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat);
187 static void resolve_categories_for_class(struct old_class *cls);
188 static BOOL _objc_register_category(struct old_category *cat, int version);
191 // Function called when a class is loaded from an image
192 void (*callbackFunction)(Class, Category) = 0;
194 // Hash table of classes
195 NXHashTable * class_hash = 0;
196 static NXHashTablePrototype classHashPrototype =
198 (uintptr_t (*) (const void *, const void *)) classHash,
199 (int (*)(const void *, const void *, const void *)) classIsEqual,
203 // Hash table of unconnected classes
204 static NXHashTable *unconnected_class_hash = NULL;
206 // Exported copy of class_hash variable (hook for debugging tools)
207 NXHashTable *_objc_debug_class_hash = NULL;
209 // Category and class registries
210 // Keys are COPIES of strings, to prevent stale pointers with unloaded bundles
211 // Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove
212 static NXMapTable * category_hash = NULL;
214 // Keys are COPIES of strings, to prevent stale pointers with unloaded bundles
215 // Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove
216 static NXMapTable * pendingClassRefsMap = NULL;
217 static NXMapTable * pendingSubclassesMap = NULL;
220 static NXMapTable *protocol_map = NULL; // name -> protocol
221 static NXMapTable *protocol_ext_map = NULL; // protocol -> protocol ext
223 // Function pointer objc_getClass calls through when class is not found
224 static int (*objc_classHandler) (const char *) = _objc_defaultClassHandler;
226 // Function pointer called by objc_getClass and objc_lookupClass when
227 // class is not found. _objc_classLoader is called before objc_classHandler.
228 static BOOL (*_objc_classLoader)(const char *) = NULL;
231 /***********************************************************************
232 * objc_dump_class_hash. Log names of all known classes.
233 **********************************************************************/
234 void objc_dump_class_hash(void)
243 state = NXInitHashState (table);
244 while (NXNextHashState (table, &state, (void **) &data))
245 printf ("class %d: %s\n", ++count, _class_getName(data));
249 /***********************************************************************
250 * _objc_init_class_hash. Return the class lookup table, create it if
252 **********************************************************************/
253 void _objc_init_class_hash(void)
255 // Do nothing if class hash table already exists
259 // class_hash starts small, with only enough capacity for libobjc itself.
260 // If a second library is found by map_images(), class_hash is immediately
261 // resized to capacity 1024 to cut down on rehashes.
262 // Old numbers: A smallish Foundation+AppKit program will have
263 // about 520 classes. Larger apps (like IB or WOB) have more like
264 // 800 classes. Some customers have massive quantities of classes.
265 // Foundation-only programs aren't likely to notice the ~6K loss.
266 class_hash = NXCreateHashTableFromZone (classHashPrototype,
269 _objc_internal_zone ());
270 _objc_debug_class_hash = class_hash;
274 /***********************************************************************
275 * objc_getClassList. Return the known classes.
276 **********************************************************************/
277 int objc_getClassList(Class *buffer, int bufferLen)
283 mutex_lock(&classLock);
285 mutex_unlock(&classLock);
288 num = NXCountHashTable(class_hash);
289 if (NULL == buffer) {
290 mutex_unlock(&classLock);
294 state = NXInitHashState(class_hash);
295 while (cnt < bufferLen &&
296 NXNextHashState(class_hash, &state, (void **)&cls))
300 mutex_unlock(&classLock);
305 /***********************************************************************
307 * Returns pointers to all classes.
308 * This requires all classes be realized, which is regretfully non-lazy.
310 * outCount may be NULL. *outCount is the number of classes returned.
311 * If the returned array is not NULL, it is NULL-terminated and must be
313 * Locking: acquires classLock
314 **********************************************************************/
316 objc_copyClassList(unsigned int *outCount)
321 mutex_lock(&classLock);
323 count = class_hash ? NXCountHashTable(class_hash) : 0;
327 NXHashState state = NXInitHashState(class_hash);
328 result = malloc((1+count) * sizeof(Class));
330 while (NXNextHashState(class_hash, &state, (void **)&cls)) {
331 result[count++] = cls;
333 result[count] = NULL;
335 mutex_unlock(&classLock);
337 if (outCount) *outCount = count;
342 /***********************************************************************
343 * objc_copyProtocolList
344 * Returns pointers to all protocols.
345 * Locking: acquires classLock
346 **********************************************************************/
347 Protocol * __unsafe_unretained *
348 objc_copyProtocolList(unsigned int *outCount)
356 mutex_lock(&classLock);
358 count = NXCountMapTable(protocol_map);
360 mutex_unlock(&classLock);
361 if (outCount) *outCount = 0;
365 result = calloc(1 + count, sizeof(Protocol *));
368 state = NXInitMapState(protocol_map);
369 while (NXNextMapState(protocol_map, &state,
370 (const void **)&name, (const void **)&proto))
376 assert(i == count+1);
378 mutex_unlock(&classLock);
380 if (outCount) *outCount = count;
385 /***********************************************************************
386 * objc_getClasses. Return class lookup table.
388 * NOTE: This function is very dangerous, since you cannot safely use
389 * the hashtable without locking it, and the lock is private!
390 **********************************************************************/
391 void *objc_getClasses(void)
393 OBJC_WARN_DEPRECATED;
395 // Return the class lookup hash table
400 /***********************************************************************
402 **********************************************************************/
403 static uintptr_t classHash(void *info, Class data)
405 // Nil classes hash to zero
409 // Call through to real hash function
410 return _objc_strhash (_class_getName(data));
413 /***********************************************************************
414 * classIsEqual. Returns whether the class names match. If we ever
415 * check more than the name, routines like objc_lookUpClass have to
417 **********************************************************************/
418 static int classIsEqual(void *info, Class name, Class cls)
420 // Standard string comparison
421 return strcmp(_class_getName(name), _class_getName(cls)) == 0;
425 // Unresolved future classes
426 static NXHashTable *future_class_hash = NULL;
428 // Resolved future<->original classes
429 static NXMapTable *future_class_to_original_class_map = NULL;
430 static NXMapTable *original_class_to_future_class_map = NULL;
432 // CF requests about 20 future classes; HIToolbox requests one.
433 #define FUTURE_COUNT 32
436 /***********************************************************************
437 * setOriginalClassForFutureClass
438 * Record resolution of a future class.
439 **********************************************************************/
440 static void setOriginalClassForFutureClass(struct old_class *futureClass,
441 struct old_class *originalClass)
443 if (!future_class_to_original_class_map) {
444 future_class_to_original_class_map =
445 NXCreateMapTableFromZone (NXPtrValueMapPrototype, FUTURE_COUNT,
446 _objc_internal_zone ());
447 original_class_to_future_class_map =
448 NXCreateMapTableFromZone (NXPtrValueMapPrototype, FUTURE_COUNT,
449 _objc_internal_zone ());
452 NXMapInsert (future_class_to_original_class_map,
453 futureClass, originalClass);
454 NXMapInsert (original_class_to_future_class_map,
455 originalClass, futureClass);
458 _objc_inform("FUTURE: using %p instead of %p for %s", futureClass, originalClass, originalClass->name);
462 /***********************************************************************
463 * getOriginalClassForFutureClass
464 * getFutureClassForOriginalClass
465 * Switch between a future class and its corresponding original class.
466 * The future class is the one actually in use.
467 * The original class is the one from disk.
468 **********************************************************************/
470 static struct old_class *
471 getOriginalClassForFutureClass(struct old_class *futureClass)
473 if (!future_class_to_original_class_map) return Nil;
474 return NXMapGet (future_class_to_original_class_map, futureClass);
477 static struct old_class *
478 getFutureClassForOriginalClass(struct old_class *originalClass)
480 if (!original_class_to_future_class_map) return Nil;
481 return NXMapGet (original_class_to_future_class_map, originalClass);
485 /***********************************************************************
487 * Initialize the memory in *cls with an unresolved future class with the
488 * given name. The memory is recorded in future_class_hash.
489 **********************************************************************/
490 static void makeFutureClass(struct old_class *cls, const char *name)
492 // CF requests about 20 future classes, plus HIToolbox has one.
493 if (!future_class_hash) {
495 NXCreateHashTableFromZone(classHashPrototype, FUTURE_COUNT,
496 NULL, _objc_internal_zone());
499 cls->name = _strdup_internal(name);
500 NXHashInsert(future_class_hash, cls);
503 _objc_inform("FUTURE: reserving %p for %s", cls, name);
508 /***********************************************************************
509 * _objc_allocateFutureClass
510 * Allocate an unresolved future class for the given class name.
511 * Returns any existing allocation if one was already made.
512 * Assumes the named class doesn't exist yet.
514 **********************************************************************/
515 Class _objc_allocateFutureClass(const char *name)
517 struct old_class *cls;
519 if (future_class_hash) {
520 struct old_class query;
522 if ((cls = NXHashGet(future_class_hash, &query))) {
523 // Already have a future class for this name.
528 cls = (struct old_class *)_calloc_class(sizeof(*cls));
529 makeFutureClass(cls, name);
534 /***********************************************************************
535 * objc_setFutureClass.
536 * Like objc_getFutureClass, but uses the provided memory block.
537 * If the class already exists, a posing-like substitution is performed.
539 **********************************************************************/
540 void objc_setFutureClass(Class cls, const char *name)
542 struct old_class *oldcls;
543 struct old_class *newcls = (struct old_class *)cls; // Not a real class!
545 if ((oldcls = oldcls((Class)look_up_class(name, NO/*unconnected*/, NO/*classhandler*/)))) {
546 setOriginalClassForFutureClass(newcls, oldcls);
548 memcpy(newcls, oldcls, sizeof(struct objc_class));
549 newcls->info &= ~CLS_EXT;
551 mutex_lock(&classLock);
552 NXHashRemove(class_hash, oldcls);
553 objc_removeRegisteredClass((Class)oldcls);
554 change_class_references(newcls, oldcls, nil, YES);
555 NXHashInsert(class_hash, newcls);
556 objc_addRegisteredClass((Class)newcls);
557 mutex_unlock(&classLock);
559 makeFutureClass(newcls, name);
564 /***********************************************************************
565 * _objc_defaultClassHandler. Default objc_classHandler. Does nothing.
566 **********************************************************************/
567 static int _objc_defaultClassHandler(const char *clsName)
569 // Return zero so objc_getClass doesn't bother re-searching
573 /***********************************************************************
574 * objc_setClassHandler. Set objc_classHandler to the specified value.
576 * NOTE: This should probably deal with userSuppliedHandler being NULL,
577 * because the objc_classHandler caller does not check... it would bus
578 * error. It would make sense to handle NULL by restoring the default
579 * handler. Is anyone hacking with this, though?
580 **********************************************************************/
581 void objc_setClassHandler(int (*userSuppliedHandler)(const char *))
583 OBJC_WARN_DEPRECATED;
585 objc_classHandler = userSuppliedHandler;
589 /***********************************************************************
590 * _objc_setClassLoader
591 * Similar to objc_setClassHandler, but objc_classLoader is used for
592 * both objc_getClass() and objc_lookupClass(), and objc_classLoader
593 * pre-empts objc_classHandler.
594 **********************************************************************/
595 void _objc_setClassLoader(BOOL (*newClassLoader)(const char *))
597 _objc_classLoader = newClassLoader;
601 /***********************************************************************
603 * Get a protocol by name, or NULL.
604 **********************************************************************/
605 Protocol *objc_getProtocol(const char *name)
608 if (!protocol_map) return NULL;
609 mutex_lock(&classLock);
610 result = (Protocol *)NXMapGet(protocol_map, name);
611 mutex_unlock(&classLock);
616 /***********************************************************************
618 * Map a class name to a class using various methods.
619 * This is the common implementation of objc_lookUpClass and objc_getClass,
620 * and is also used internally to get additional search options.
623 * 2. unconnected_class_hash (optional)
624 * 3. classLoader callback
625 * 4. classHandler callback (optional)
626 **********************************************************************/
627 id look_up_class(const char *aClassName, BOOL includeUnconnected, BOOL includeClassHandler)
629 BOOL includeClassLoader = YES; // class loader cannot be skipped
631 struct old_class query;
633 query.name = aClassName;
637 if (!result && class_hash) {
638 // Check ordinary classes
639 mutex_lock (&classLock);
640 result = (id)NXHashGet(class_hash, &query);
641 mutex_unlock (&classLock);
644 if (!result && includeUnconnected && unconnected_class_hash) {
645 // Check not-yet-connected classes
646 mutex_lock(&classLock);
647 result = (id)NXHashGet(unconnected_class_hash, &query);
648 mutex_unlock(&classLock);
651 if (!result && includeClassLoader && _objc_classLoader) {
652 // Try class loader callback
653 if ((*_objc_classLoader)(aClassName)) {
654 // Re-try lookup without class loader
655 includeClassLoader = NO;
660 if (!result && includeClassHandler && objc_classHandler) {
661 // Try class handler callback
662 if ((*objc_classHandler)(aClassName)) {
663 // Re-try lookup without class handler or class loader
664 includeClassLoader = NO;
665 includeClassHandler = NO;
674 /***********************************************************************
675 * class_is_connected.
676 * Returns TRUE if class cls is connected.
677 * A connected class has either a connected superclass or a NULL superclass,
678 * and is present in class_hash.
679 **********************************************************************/
680 static BOOL class_is_connected(struct old_class *cls)
683 mutex_lock(&classLock);
684 result = NXHashMember(class_hash, cls);
685 mutex_unlock(&classLock);
690 /***********************************************************************
692 * Returns TRUE if class cls is ready for its +load method to be called.
693 * A class is ready for +load if it is connected.
694 **********************************************************************/
695 BOOL _class_isLoadable(Class cls)
697 return class_is_connected(oldcls(cls));
701 /***********************************************************************
702 * pendingClassRefsMapTable. Return a pointer to the lookup table for
703 * pending class refs.
704 **********************************************************************/
705 static inline NXMapTable *pendingClassRefsMapTable(void)
707 // Allocate table if needed
708 if (!pendingClassRefsMap) {
709 pendingClassRefsMap =
710 NXCreateMapTableFromZone(NXStrValueMapPrototype,
711 10, _objc_internal_zone ());
714 // Return table pointer
715 return pendingClassRefsMap;
719 /***********************************************************************
720 * pendingSubclassesMapTable. Return a pointer to the lookup table for
721 * pending subclasses.
722 **********************************************************************/
723 static inline NXMapTable *pendingSubclassesMapTable(void)
725 // Allocate table if needed
726 if (!pendingSubclassesMap) {
727 pendingSubclassesMap =
728 NXCreateMapTableFromZone(NXStrValueMapPrototype,
729 10, _objc_internal_zone ());
732 // Return table pointer
733 return pendingSubclassesMap;
737 /***********************************************************************
738 * pendClassInstallation
739 * Finish connecting class cls when its superclass becomes connected.
740 * Check for multiple pends of the same class because connect_class does not.
741 **********************************************************************/
742 static void pendClassInstallation(struct old_class *cls, const char *superName)
745 PendingSubclass *pending;
746 PendingSubclass *oldList;
749 // Create and/or locate pending class lookup table
750 table = pendingSubclassesMapTable ();
752 // Make sure this class isn't already in the pending list.
753 oldList = NXMapGet (table, superName);
754 for (l = oldList; l != NULL; l = l->next) {
755 if (l->subclass == cls) return; // already here, nothing to do
758 // Create entry referring to this class
759 pending = _malloc_internal(sizeof(PendingSubclass));
760 pending->subclass = cls;
762 // Link new entry into head of list of entries for this class
763 pending->next = oldList;
765 // (Re)place entry list in the table
766 NXMapKeyCopyingInsert (table, superName, pending);
770 /***********************************************************************
772 * Fix up a class ref when the class with the given name becomes connected.
773 **********************************************************************/
774 static void pendClassReference(struct old_class **ref, const char *className, BOOL isMeta)
777 PendingClassRef *pending;
779 // Create and/or locate pending class lookup table
780 table = pendingClassRefsMapTable ();
782 // Create entry containing the class reference
783 pending = _malloc_internal(sizeof(PendingClassRef));
786 pending->ref = (struct old_class **)((uintptr_t)pending->ref | 1);
789 // Link new entry into head of list of entries for this class
790 pending->next = NXMapGet (table, className);
792 // (Re)place entry list in the table
793 NXMapKeyCopyingInsert (table, className, pending);
795 if (PrintConnecting) {
796 _objc_inform("CONNECT: pended reference to class '%s%s' at %p",
797 className, isMeta ? " (meta)" : "", (void *)ref);
802 /***********************************************************************
803 * resolve_references_to_class
804 * Fix up any pending class refs to this class.
805 **********************************************************************/
806 static void resolve_references_to_class(struct old_class *cls)
808 PendingClassRef *pending;
810 if (!pendingClassRefsMap) return; // no unresolved refs for any class
812 pending = NXMapGet(pendingClassRefsMap, cls->name);
813 if (!pending) return; // no unresolved refs for this class
815 NXMapKeyFreeingRemove(pendingClassRefsMap, cls->name);
817 if (PrintConnecting) {
818 _objc_inform("CONNECT: resolving references to class '%s'", cls->name);
822 PendingClassRef *next = pending->next;
824 BOOL isMeta = ((uintptr_t)pending->ref & 1) ? YES : NO;
825 struct old_class **ref =
826 (struct old_class **)((uintptr_t)pending->ref & ~(uintptr_t)1);
827 *ref = isMeta ? cls->isa : cls;
829 _free_internal(pending);
833 if (NXCountMapTable(pendingClassRefsMap) == 0) {
834 NXFreeMapTable(pendingClassRefsMap);
835 pendingClassRefsMap = NULL;
840 /***********************************************************************
841 * resolve_subclasses_of_class
842 * Fix up any pending subclasses of this class.
843 **********************************************************************/
844 static void resolve_subclasses_of_class(struct old_class *cls)
846 PendingSubclass *pending;
848 if (!pendingSubclassesMap) return; // no unresolved subclasses
850 pending = NXMapGet(pendingSubclassesMap, cls->name);
851 if (!pending) return; // no unresolved subclasses for this class
853 NXMapKeyFreeingRemove(pendingSubclassesMap, cls->name);
855 // Destroy the pending table if it's now empty, to save memory.
856 if (NXCountMapTable(pendingSubclassesMap) == 0) {
857 NXFreeMapTable(pendingSubclassesMap);
858 pendingSubclassesMap = NULL;
861 if (PrintConnecting) {
862 _objc_inform("CONNECT: resolving subclasses of class '%s'", cls->name);
866 PendingSubclass *next = pending->next;
867 if (pending->subclass) connect_class(pending->subclass);
868 _free_internal(pending);
874 /***********************************************************************
875 * really_connect_class
876 * Connect cls to superclass supercls unconditionally.
877 * Also adjust the class hash tables and handle pended subclasses.
879 * This should be called from connect_class() ONLY.
880 **********************************************************************/
881 static void really_connect_class(struct old_class *cls,
882 struct old_class *supercls)
884 struct old_class *oldCls;
886 // Connect superclass pointers.
887 set_superclass(cls, supercls, YES);
890 // For paranoia, this is a conservative update:
891 // only non-strong -> strong and weak -> strong are corrected.
892 if (UseGC && supercls &&
893 (cls->info & CLS_EXT) && (supercls->info & CLS_EXT))
896 layout_bitmap ivarBitmap =
897 layout_bitmap_create(cls->ivar_layout,
899 cls->instance_size, NO);
901 layout_bitmap superBitmap =
902 layout_bitmap_create(supercls->ivar_layout,
903 supercls->instance_size,
904 supercls->instance_size, NO);
906 // non-strong -> strong: bits set in super should be set in sub
907 layoutChanged = layout_bitmap_or(ivarBitmap, superBitmap, cls->name);
908 layout_bitmap_free(superBitmap);
911 layout_bitmap weakBitmap = {};
912 BOOL weakLayoutChanged = NO;
914 if (cls->ext && cls->ext->weak_ivar_layout) {
915 // weak -> strong: strong bits should be cleared in weak layout
916 // This is a subset of non-strong -> strong
918 layout_bitmap_create(cls->ext->weak_ivar_layout,
920 cls->instance_size, YES);
923 layout_bitmap_clear(weakBitmap, ivarBitmap, cls->name);
925 // no existing weak ivars, so no weak -> strong changes
928 // Rebuild layout strings.
930 _objc_inform("IVARS: gc layout changed "
931 "for class %s (super %s)",
932 cls->name, supercls->name);
933 if (weakLayoutChanged) {
934 _objc_inform("IVARS: gc weak layout changed "
935 "for class %s (super %s)",
936 cls->name, supercls->name);
939 cls->ivar_layout = layout_string_create(ivarBitmap);
940 if (weakLayoutChanged) {
941 cls->ext->weak_ivar_layout = layout_string_create(weakBitmap);
944 layout_bitmap_free(weakBitmap);
947 layout_bitmap_free(ivarBitmap);
951 cls->info |= CLS_CONNECTED;
953 mutex_lock(&classLock);
955 // Update hash tables.
956 NXHashRemove(unconnected_class_hash, cls);
957 oldCls = NXHashInsert(class_hash, cls);
958 objc_addRegisteredClass((Class)cls);
960 // Delete unconnected_class_hash if it is now empty.
961 if (NXCountHashTable(unconnected_class_hash) == 0) {
962 NXFreeHashTable(unconnected_class_hash);
963 unconnected_class_hash = NULL;
966 // No duplicate classes allowed.
967 // Duplicates should have been rejected by _objc_read_classes_from_image.
970 mutex_unlock(&classLock);
972 // Fix up pended class refs to this class, if any
973 resolve_references_to_class(cls);
975 // Connect newly-connectable subclasses
976 resolve_subclasses_of_class(cls);
978 // GC debugging: make sure all classes with -dealloc also have -finalize
979 if (DebugFinalizers) {
980 extern IMP findIMPInClass(struct old_class *cls, SEL sel);
981 if (findIMPInClass(cls, sel_getUid("dealloc")) &&
982 ! findIMPInClass(cls, sel_getUid("finalize")))
984 _objc_inform("GC: class '%s' implements -dealloc but not -finalize", cls->name);
988 // Debugging: if this class has ivars, make sure this class's ivars don't
989 // overlap with its super's. This catches some broken fragile base classes.
990 // Do not use super->instance_size vs. self->ivar[0] to check this.
991 // Ivars may be packed across instance_size boundaries.
992 if (DebugFragileSuperclasses && cls->ivars && cls->ivars->ivar_count) {
993 struct old_class *ivar_cls = supercls;
995 // Find closest superclass that has some ivars, if one exists.
997 (!ivar_cls->ivars || ivar_cls->ivars->ivar_count == 0))
999 ivar_cls = ivar_cls->super_class;
1003 // Compare superclass's last ivar to this class's first ivar
1004 struct old_ivar *super_ivar =
1005 &ivar_cls->ivars->ivar_list[ivar_cls->ivars->ivar_count - 1];
1006 struct old_ivar *self_ivar =
1007 &cls->ivars->ivar_list[0];
1009 // fixme could be smarter about super's ivar size
1010 if (self_ivar->ivar_offset <= super_ivar->ivar_offset) {
1011 _objc_inform("WARNING: ivars of superclass '%s' and "
1012 "subclass '%s' overlap; superclass may have "
1013 "changed since subclass was compiled",
1014 ivar_cls->name, cls->name);
1021 /***********************************************************************
1023 * Connect class cls to its superclasses, if possible.
1024 * If cls becomes connected, move it from unconnected_class_hash
1025 * to connected_class_hash.
1026 * Returns TRUE if cls is connected.
1027 * Returns FALSE if cls could not be connected for some reason
1028 * (missing superclass or still-unconnected superclass)
1029 **********************************************************************/
1030 static BOOL connect_class(struct old_class *cls)
1032 if (class_is_connected(cls)) {
1033 // This class is already connected to its superclass.
1037 else if (cls->super_class == NULL) {
1038 // This class is a root class.
1039 // Connect it to itself.
1041 if (PrintConnecting) {
1042 _objc_inform("CONNECT: class '%s' now connected (root class)",
1046 really_connect_class(cls, NULL);
1050 // This class is not a root class and is not yet connected.
1051 // Connect it if its superclass and root class are already connected.
1052 // Otherwise, add this class to the to-be-connected list,
1053 // pending the completion of its superclass and root class.
1055 // At this point, cls->super_class and cls->isa->isa are still STRINGS
1056 char *supercls_name = (char *)cls->super_class;
1057 struct old_class *supercls;
1059 // YES unconnected, YES class handler
1060 if (NULL == (supercls = oldcls((Class)look_up_class(supercls_name, YES, YES)))) {
1061 // Superclass does not exist yet.
1062 // pendClassInstallation will handle duplicate pends of this class
1063 pendClassInstallation(cls, supercls_name);
1065 if (PrintConnecting) {
1066 _objc_inform("CONNECT: class '%s' NOT connected (missing super)", cls->name);
1071 if (! connect_class(supercls)) {
1072 // Superclass exists but is not yet connected.
1073 // pendClassInstallation will handle duplicate pends of this class
1074 pendClassInstallation(cls, supercls_name);
1076 if (PrintConnecting) {
1077 _objc_inform("CONNECT: class '%s' NOT connected (unconnected super)", cls->name);
1082 // Superclass exists and is connected.
1083 // Connect this class to the superclass.
1085 if (PrintConnecting) {
1086 _objc_inform("CONNECT: class '%s' now connected", cls->name);
1089 really_connect_class(cls, supercls);
1095 /***********************************************************************
1096 * _objc_read_categories_from_image.
1097 * Read all categories from the given image.
1098 * Install them on their parent classes, or register them for later
1100 * Returns YES if some method caches now need to be flushed.
1101 **********************************************************************/
1102 static BOOL _objc_read_categories_from_image (header_info * hi)
1106 BOOL needFlush = NO;
1108 if (_objcHeaderIsReplacement(hi)) {
1109 // Ignore any categories in this image
1114 // Major loop - process all modules in the header
1117 // NOTE: The module and category lists are traversed backwards
1118 // to preserve the pre-10.4 processing order. Changing the order
1119 // would have a small chance of introducing binary compatibility bugs.
1120 midx = hi->mod_count;
1121 while (midx-- > 0) {
1125 // Nothing to do for a module without a symbol table
1126 if (mods[midx].symtab == NULL)
1129 // Total entries in symbol table (class entries followed
1130 // by category entries)
1131 total = mods[midx].symtab->cls_def_cnt +
1132 mods[midx].symtab->cat_def_cnt;
1134 // Minor loop - register all categories from given module
1136 while (index-- > mods[midx].symtab->cls_def_cnt) {
1137 struct old_category *cat = mods[midx].symtab->defs[index];
1138 needFlush |= _objc_register_category(cat, (int)mods[midx].version);
1146 /***********************************************************************
1147 * _objc_read_classes_from_image.
1148 * Read classes from the given image, perform assorted minor fixups,
1149 * scan for +load implementation.
1150 * Does not connect classes to superclasses.
1151 * Does attach pended categories to the classes.
1152 * Adds all classes to unconnected_class_hash. class_hash is unchanged.
1153 **********************************************************************/
1154 static void _objc_read_classes_from_image(header_info *hi)
1159 int isBundle = headerIsBundle(hi);
1161 if (_objcHeaderIsReplacement(hi)) {
1162 // Ignore any classes in this image
1166 // class_hash starts small, enough only for libobjc itself.
1167 // If other Objective-C libraries are found, immediately resize
1168 // class_hash, assuming that Foundation and AppKit are about
1169 // to add lots of classes.
1170 mutex_lock(&classLock);
1171 if (hi->mhdr != libobjc_header && _NXHashCapacity(class_hash) < 1024) {
1172 _NXHashRehashToCapacity(class_hash, 1024);
1174 mutex_unlock(&classLock);
1176 // Major loop - process all modules in the image
1178 for (midx = 0; midx < hi->mod_count; midx += 1)
1180 // Skip module containing no classes
1181 if (mods[midx].symtab == NULL)
1184 // Minor loop - process all the classes in given module
1185 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
1187 struct old_class *newCls, *oldCls;
1190 // Locate the class description pointer
1191 newCls = mods[midx].symtab->defs[index];
1193 // Classes loaded from Mach-O bundles can be unloaded later.
1194 // Nothing uses this class yet, so _class_setInfo is not needed.
1195 if (isBundle) newCls->info |= CLS_FROM_BUNDLE;
1196 if (isBundle) newCls->isa->info |= CLS_FROM_BUNDLE;
1198 // Use common static empty cache instead of NULL
1199 if (newCls->cache == NULL)
1200 newCls->cache = (Cache) &_objc_empty_cache;
1201 if (newCls->isa->cache == NULL)
1202 newCls->isa->cache = (Cache) &_objc_empty_cache;
1204 // Set metaclass version
1205 newCls->isa->version = mods[midx].version;
1207 // methodLists is NULL or a single list, not an array
1208 newCls->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY;
1209 newCls->isa->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY;
1211 // class has no subclasses for cache flushing
1212 newCls->info |= CLS_LEAF;
1213 newCls->isa->info |= CLS_LEAF;
1215 if (mods[midx].version >= 6) {
1216 // class structure has ivar_layout and ext fields
1217 newCls->info |= CLS_EXT;
1218 newCls->isa->info |= CLS_EXT;
1221 // Check for +load implementation before categories are attached
1222 if (_class_hasLoadMethod((Class)newCls)) {
1223 newCls->isa->info |= CLS_HAS_LOAD_METHOD;
1226 // Install into unconnected_class_hash.
1227 mutex_lock(&classLock);
1229 if (future_class_hash) {
1230 struct old_class *futureCls =
1231 NXHashRemove(future_class_hash, newCls);
1233 // Another class structure for this class was already
1234 // prepared by objc_getFutureClass(). Use it instead.
1235 _free_internal((char *)futureCls->name);
1236 memcpy(futureCls, newCls, sizeof(*newCls));
1237 setOriginalClassForFutureClass(futureCls, newCls);
1240 if (NXCountHashTable(future_class_hash) == 0) {
1241 NXFreeHashTable(future_class_hash);
1242 future_class_hash = NULL;
1247 if (!unconnected_class_hash) {
1248 unconnected_class_hash =
1249 NXCreateHashTableFromZone(classHashPrototype, 128,
1250 NULL, _objc_internal_zone());
1253 if ((oldCls = NXHashGet(class_hash, newCls)) ||
1254 (oldCls = NXHashGet(unconnected_class_hash, newCls)))
1256 // Another class with this name exists. Complain and reject.
1257 inform_duplicate(newCls->name, (Class)oldCls, (Class)newCls);
1261 NXHashInsert(unconnected_class_hash, newCls);
1265 mutex_unlock(&classLock);
1268 // Attach pended categories for this class, if any
1269 resolve_categories_for_class(newCls);
1276 /***********************************************************************
1277 * _objc_connect_classes_from_image.
1278 * Connect the classes in the given image to their superclasses,
1279 * or register them for later connection if any superclasses are missing.
1280 **********************************************************************/
1281 static void _objc_connect_classes_from_image(header_info *hi)
1286 BOOL replacement = _objcHeaderIsReplacement(hi);
1288 // Major loop - process all modules in the image
1290 for (midx = 0; midx < hi->mod_count; midx += 1)
1292 // Skip module containing no classes
1293 if (mods[midx].symtab == NULL)
1296 // Minor loop - process all the classes in given module
1297 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
1299 struct old_class *cls = mods[midx].symtab->defs[index];
1300 if (! replacement) {
1302 struct old_class *futureCls = getFutureClassForOriginalClass(cls);
1304 // objc_getFutureClass() requested a different class
1305 // struct. Fix up the original struct's super_class
1306 // field for [super ...] use, but otherwise perform
1307 // fixups on the new class struct only.
1308 const char *super_name = (const char *) cls->super_class;
1309 if (super_name) cls->super_class = oldcls((Class)objc_getClass(super_name));
1312 connected = connect_class(cls);
1313 if (connected && callbackFunction) {
1314 (*callbackFunction)((Class)cls, 0);
1317 // Replacement image - fix up super_class only (#3704817)
1318 // And metaclass's super_class (#5351107)
1319 const char *super_name = (const char *) cls->super_class;
1321 cls->super_class = oldcls((Class)objc_getClass(super_name));
1322 // metaclass's superclass is superclass's metaclass
1323 cls->isa->super_class = cls->super_class->isa;
1325 // Replacement for a root class
1326 // cls->super_class already NULL
1327 // root metaclass's superclass is root class
1328 cls->isa->super_class = cls;
1336 /***********************************************************************
1337 * _objc_map_class_refs_for_image. Convert the class ref entries from
1338 * a class name string pointer to a class pointer. If the class does
1339 * not yet exist, the reference is added to a list of pending references
1340 * to be fixed up at a later date.
1341 **********************************************************************/
1342 static void fix_class_ref(struct old_class **ref, const char *name, BOOL isMeta)
1344 struct old_class *cls;
1346 // Get pointer to class of this name
1347 // NO unconnected, YES class loader
1348 // (real class with weak-missing superclass is unconnected now)
1349 cls = oldcls((Class)look_up_class(name, NO, YES));
1351 // Referenced class exists. Fix up the reference.
1352 *ref = isMeta ? cls->isa : cls;
1354 // Referenced class does not exist yet. Insert NULL for now
1355 // (weak-linking) and fix up the reference if the class arrives later.
1356 pendClassReference (ref, name, isMeta);
1361 static void _objc_map_class_refs_for_image (header_info * hi)
1363 struct old_class **cls_refs;
1367 // Locate class refs in image
1368 cls_refs = _getObjcClassRefs (hi, &count);
1370 // Process each class ref
1371 for (index = 0; index < count; index += 1) {
1372 // Ref is initially class name char*
1373 const char *name = (const char *) cls_refs[index];
1374 if (!name) continue;
1375 fix_class_ref(&cls_refs[index], name, NO /*never meta*/);
1381 /***********************************************************************
1382 * _objc_remove_pending_class_refs_in_image
1383 * Delete any pending class ref fixups for class refs in the given image,
1384 * because the image is about to be unloaded.
1385 **********************************************************************/
1386 static void removePendingReferences(struct old_class **refs, size_t count)
1388 struct old_class **end = refs + count;
1391 if (!pendingClassRefsMap) return;
1393 // Search the pending class ref table for class refs in this range.
1394 // The class refs may have already been stomped with NULL,
1395 // so there's no way to recover the original class name.
1399 PendingClassRef *pending;
1400 NXMapState state = NXInitMapState(pendingClassRefsMap);
1401 while(NXNextMapState(pendingClassRefsMap, &state,
1402 (const void **)&key, (const void **)&pending))
1404 for ( ; pending != NULL; pending = pending->next) {
1405 if (pending->ref >= refs && pending->ref < end) {
1406 pending->ref = NULL;
1413 static void _objc_remove_pending_class_refs_in_image(header_info *hi)
1415 struct old_class **cls_refs;
1418 // Locate class refs in this image
1419 cls_refs = _getObjcClassRefs(hi, &count);
1420 removePendingReferences(cls_refs, count);
1424 /***********************************************************************
1425 * map_selrefs. For each selector in the specified array,
1426 * replace the name pointer with a uniqued selector.
1427 * If copy is TRUE, all selector data is always copied. This is used
1428 * for registering selectors from unloadable bundles, so the selector
1429 * can still be used after the bundle's data segment is unmapped.
1430 * Returns YES if dst was written to, NO if it was unchanged.
1431 **********************************************************************/
1432 static inline void map_selrefs(SEL *sels, size_t count, BOOL copy)
1440 // Process each selector
1441 for (index = 0; index < count; index += 1)
1445 // Lookup pointer to uniqued string
1446 sel = sel_registerNameNoLock((const char *) sels[index], copy);
1448 // Replace this selector with uniqued one (avoid
1449 // modifying the VM page if this would be a NOP)
1450 if (sels[index] != sel) {
1459 /***********************************************************************
1460 * map_method_descs. For each method in the specified method list,
1461 * replace the name pointer with a uniqued selector.
1462 * If copy is TRUE, all selector data is always copied. This is used
1463 * for registering selectors from unloadable bundles, so the selector
1464 * can still be used after the bundle's data segment is unmapped.
1465 **********************************************************************/
1466 static void map_method_descs (struct objc_method_description_list * methods, BOOL copy)
1470 if (!methods) return;
1474 // Process each method
1475 for (index = 0; index < methods->count; index += 1)
1477 struct objc_method_description * method;
1480 // Get method entry to fix up
1481 method = &methods->list[index];
1483 // Lookup pointer to uniqued string
1484 sel = sel_registerNameNoLock((const char *) method->name, copy);
1486 // Replace this selector with uniqued one (avoid
1487 // modifying the VM page if this would be a NOP)
1488 if (method->name != sel)
1496 /***********************************************************************
1498 * Returns the protocol extension for the given protocol.
1499 * Returns NULL if the protocol has no extension.
1500 **********************************************************************/
1501 static struct old_protocol_ext *ext_for_protocol(struct old_protocol *proto)
1503 if (!proto) return NULL;
1504 if (!protocol_ext_map) return NULL;
1505 else return (struct old_protocol_ext *)NXMapGet(protocol_ext_map, proto);
1509 /***********************************************************************
1511 * Search a protocol method list for a selector.
1512 **********************************************************************/
1513 static struct objc_method_description *
1514 lookup_method(struct objc_method_description_list *mlist, SEL aSel)
1518 for (i = 0; i < mlist->count; i++) {
1519 if (mlist->list[i].name == aSel) {
1520 return mlist->list+i;
1528 /***********************************************************************
1529 * lookup_protocol_method
1530 * Search for a selector in a protocol
1531 * (and optionally recursively all incorporated protocols)
1532 **********************************************************************/
1533 struct objc_method_description *
1534 lookup_protocol_method(struct old_protocol *proto, SEL aSel,
1535 BOOL isRequiredMethod, BOOL isInstanceMethod,
1538 struct objc_method_description *m = NULL;
1539 struct old_protocol_ext *ext;
1541 if (isRequiredMethod) {
1542 if (isInstanceMethod) {
1543 m = lookup_method(proto->instance_methods, aSel);
1545 m = lookup_method(proto->class_methods, aSel);
1547 } else if ((ext = ext_for_protocol(proto))) {
1548 if (isInstanceMethod) {
1549 m = lookup_method(ext->optional_instance_methods, aSel);
1551 m = lookup_method(ext->optional_class_methods, aSel);
1555 if (!m && recursive && proto->protocol_list) {
1557 for (i = 0; !m && i < proto->protocol_list->count; i++) {
1558 m = lookup_protocol_method(proto->protocol_list->list[i], aSel,
1559 isRequiredMethod,isInstanceMethod,true);
1567 /***********************************************************************
1569 * Returns the name of the given protocol.
1570 **********************************************************************/
1571 const char *protocol_getName(Protocol *p)
1573 struct old_protocol *proto = oldprotocol(p);
1574 if (!proto) return "nil";
1575 return proto->protocol_name;
1579 /***********************************************************************
1580 * protocol_getMethodDescription
1581 * Returns the description of a named method.
1582 * Searches either required or optional methods.
1583 * Searches either instance or class methods.
1584 **********************************************************************/
1585 struct objc_method_description
1586 protocol_getMethodDescription(Protocol *p, SEL aSel,
1587 BOOL isRequiredMethod, BOOL isInstanceMethod)
1589 struct objc_method_description empty = {NULL, NULL};
1590 struct old_protocol *proto = oldprotocol(p);
1591 struct objc_method_description *desc;
1592 if (!proto) return empty;
1594 desc = lookup_protocol_method(proto, aSel,
1595 isRequiredMethod, isInstanceMethod, true);
1596 if (desc) return *desc;
1601 /***********************************************************************
1602 * protocol_copyMethodDescriptionList
1603 * Returns an array of method descriptions from a protocol.
1604 * Copies either required or optional methods.
1605 * Copies either instance or class methods.
1606 **********************************************************************/
1607 struct objc_method_description *
1608 protocol_copyMethodDescriptionList(Protocol *p,
1609 BOOL isRequiredMethod,
1610 BOOL isInstanceMethod,
1611 unsigned int *outCount)
1613 struct objc_method_description_list *mlist = NULL;
1614 struct old_protocol *proto = oldprotocol(p);
1615 struct old_protocol_ext *ext;
1616 unsigned int i, count;
1617 struct objc_method_description *result;
1620 if (outCount) *outCount = 0;
1624 if (isRequiredMethod) {
1625 if (isInstanceMethod) {
1626 mlist = proto->instance_methods;
1628 mlist = proto->class_methods;
1630 } else if ((ext = ext_for_protocol(proto))) {
1631 if (isInstanceMethod) {
1632 mlist = ext->optional_instance_methods;
1634 mlist = ext->optional_class_methods;
1639 if (outCount) *outCount = 0;
1643 count = mlist->count;
1645 calloc(count + 1, sizeof(struct objc_method_description));
1646 for (i = 0; i < count; i++) {
1647 result[i] = mlist->list[i];
1650 if (outCount) *outCount = count;
1655 objc_property_t protocol_getProperty(Protocol *p, const char *name,
1656 BOOL isRequiredProperty, BOOL isInstanceProperty)
1658 struct old_protocol *proto = oldprotocol(p);
1659 struct old_protocol_ext *ext;
1660 struct old_protocol_list *proto_list;
1662 if (!proto || !name) return NULL;
1664 if (!isRequiredProperty || !isInstanceProperty) {
1665 // Only required instance properties are currently supported
1669 if ((ext = ext_for_protocol(proto))) {
1670 struct old_property_list *plist;
1671 if ((plist = ext->instance_properties)) {
1673 for (i = 0; i < plist->count; i++) {
1674 struct old_property *prop = property_list_nth(plist, i);
1675 if (0 == strcmp(name, prop->name)) {
1676 return (objc_property_t)prop;
1682 if ((proto_list = proto->protocol_list)) {
1684 for (i = 0; i < proto_list->count; i++) {
1685 objc_property_t prop =
1686 protocol_getProperty((Protocol *)proto_list->list[i], name,
1687 isRequiredProperty, isInstanceProperty);
1688 if (prop) return prop;
1696 objc_property_t *protocol_copyPropertyList(Protocol *p, unsigned int *outCount)
1698 struct old_property **result = NULL;
1699 struct old_protocol_ext *ext;
1700 struct old_property_list *plist;
1702 struct old_protocol *proto = oldprotocol(p);
1703 if (! (ext = ext_for_protocol(proto))) {
1704 if (outCount) *outCount = 0;
1708 plist = ext->instance_properties;
1709 result = copyPropertyList(plist, outCount);
1711 return (objc_property_t *)result;
1715 /***********************************************************************
1716 * protocol_copyProtocolList
1717 * Copies this protocol's incorporated protocols.
1718 * Does not copy those protocol's incorporated protocols in turn.
1719 **********************************************************************/
1720 Protocol * __unsafe_unretained *
1721 protocol_copyProtocolList(Protocol *p, unsigned int *outCount)
1723 unsigned int count = 0;
1724 Protocol **result = NULL;
1725 struct old_protocol *proto = oldprotocol(p);
1728 if (outCount) *outCount = 0;
1732 if (proto->protocol_list) {
1733 count = (unsigned int)proto->protocol_list->count;
1737 result = malloc((count+1) * sizeof(Protocol *));
1739 for (i = 0; i < count; i++) {
1740 result[i] = (Protocol *)proto->protocol_list->list[i];
1745 if (outCount) *outCount = count;
1750 BOOL protocol_conformsToProtocol(Protocol *self_gen, Protocol *other_gen)
1752 struct old_protocol *self = oldprotocol(self_gen);
1753 struct old_protocol *other = oldprotocol(other_gen);
1755 if (!self || !other) {
1759 if (0 == strcmp(self->protocol_name, other->protocol_name)) {
1763 if (self->protocol_list) {
1765 for (i = 0; i < self->protocol_list->count; i++) {
1766 struct old_protocol *proto = self->protocol_list->list[i];
1767 if (0 == strcmp(other->protocol_name, proto->protocol_name)) {
1770 if (protocol_conformsToProtocol((Protocol *)proto, other_gen)) {
1780 BOOL protocol_isEqual(Protocol *self, Protocol *other)
1782 if (self == other) return YES;
1783 if (!self || !other) return NO;
1785 if (!protocol_conformsToProtocol(self, other)) return NO;
1786 if (!protocol_conformsToProtocol(other, self)) return NO;
1792 /***********************************************************************
1793 * _protocol_getMethodTypeEncoding
1794 * Return the @encode string for the requested protocol method.
1795 * Returns NULL if the compiler did not emit any extended @encode data.
1796 * Locking: runtimeLock must not be held by the caller
1797 **********************************************************************/
1799 _protocol_getMethodTypeEncoding(Protocol *proto_gen, SEL sel,
1800 BOOL isRequiredMethod, BOOL isInstanceMethod)
1802 struct old_protocol *proto = oldprotocol(proto_gen);
1803 if (!proto) return NULL;
1804 struct old_protocol_ext *ext = ext_for_protocol(proto);
1805 if (!ext) return NULL;
1806 if (ext->size < offsetof(struct old_protocol_ext, extendedMethodTypes) + sizeof(ext->extendedMethodTypes)) return NULL;
1807 if (! ext->extendedMethodTypes) return NULL;
1809 struct objc_method_description *m =
1810 lookup_protocol_method(proto, sel,
1811 isRequiredMethod, isInstanceMethod, false);
1813 // No method with that name. Search incorporated protocols.
1814 if (proto->protocol_list) {
1815 for (int i = 0; i < proto->protocol_list->count; i++) {
1817 _protocol_getMethodTypeEncoding((Protocol *)proto->protocol_list->list[i], sel, isRequiredMethod, isInstanceMethod);
1818 if (enc) return enc;
1825 if (isRequiredMethod && isInstanceMethod) {
1826 i += ((uintptr_t)m - (uintptr_t)proto->instance_methods) / sizeof(proto->instance_methods->list[0]);
1828 } else if (proto->instance_methods) {
1829 i += proto->instance_methods->count;
1832 if (isRequiredMethod && !isInstanceMethod) {
1833 i += ((uintptr_t)m - (uintptr_t)proto->class_methods) / sizeof(proto->class_methods->list[0]);
1835 } else if (proto->class_methods) {
1836 i += proto->class_methods->count;
1839 if (!isRequiredMethod && isInstanceMethod) {
1840 i += ((uintptr_t)m - (uintptr_t)ext->optional_instance_methods) / sizeof(ext->optional_instance_methods->list[0]);
1842 } else if (ext->optional_instance_methods) {
1843 i += ext->optional_instance_methods->count;
1846 if (!isRequiredMethod && !isInstanceMethod) {
1847 i += ((uintptr_t)m - (uintptr_t)ext->optional_class_methods) / sizeof(ext->optional_class_methods->list[0]);
1849 } else if (ext->optional_class_methods) {
1850 i += ext->optional_class_methods->count;
1854 return ext->extendedMethodTypes[i];
1858 /***********************************************************************
1859 * objc_allocateProtocol
1860 * Creates a new protocol. The protocol may not be used until
1861 * objc_registerProtocol() is called.
1862 * Returns NULL if a protocol with the same name already exists.
1863 * Locking: acquires classLock
1864 **********************************************************************/
1866 objc_allocateProtocol(const char *name)
1868 Class cls = (Class)objc_getClass("__IncompleteProtocol");
1870 mutex_lock(&classLock);
1872 if (NXMapGet(protocol_map, name)) {
1873 mutex_unlock(&classLock);
1877 struct old_protocol *result = (struct old_protocol *)
1878 _calloc_internal(1, sizeof(struct old_protocol)
1879 + sizeof(struct old_protocol_ext));
1880 struct old_protocol_ext *ext = (struct old_protocol_ext *)(result+1);
1883 result->protocol_name = _strdup_internal(name);
1884 ext->size = sizeof(*ext);
1886 // fixme reserve name without installing
1888 NXMapInsert(protocol_ext_map, result, result+1);
1890 mutex_unlock(&classLock);
1892 return (Protocol *)result;
1896 /***********************************************************************
1897 * objc_registerProtocol
1898 * Registers a newly-constructed protocol. The protocol is now
1899 * ready for use and immutable.
1900 * Locking: acquires classLock
1901 **********************************************************************/
1902 void objc_registerProtocol(Protocol *proto_gen)
1904 struct old_protocol *proto = oldprotocol(proto_gen);
1906 Class oldcls = (Class)objc_getClass("__IncompleteProtocol");
1907 Class cls = (Class)objc_getClass("Protocol");
1909 mutex_lock(&classLock);
1911 if (proto->isa == cls) {
1912 _objc_inform("objc_registerProtocol: protocol '%s' was already "
1913 "registered!", proto->protocol_name);
1914 mutex_unlock(&classLock);
1917 if (proto->isa != oldcls) {
1918 _objc_inform("objc_registerProtocol: protocol '%s' was not allocated "
1919 "with objc_allocateProtocol!", proto->protocol_name);
1920 mutex_unlock(&classLock);
1926 NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto);
1928 mutex_unlock(&classLock);
1932 /***********************************************************************
1933 * protocol_addProtocol
1934 * Adds an incorporated protocol to another protocol.
1935 * No method enforcement is performed.
1936 * `proto` must be under construction. `addition` must not.
1937 * Locking: acquires classLock
1938 **********************************************************************/
1940 protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen)
1942 struct old_protocol *proto = oldprotocol(proto_gen);
1943 struct old_protocol *addition = oldprotocol(addition_gen);
1945 Class cls = (Class)objc_getClass("__IncompleteProtocol");
1947 if (!proto_gen) return;
1948 if (!addition_gen) return;
1950 mutex_lock(&classLock);
1952 if (proto->isa != cls) {
1953 _objc_inform("protocol_addProtocol: modified protocol '%s' is not "
1954 "under construction!", proto->protocol_name);
1955 mutex_unlock(&classLock);
1958 if (addition->isa == cls) {
1959 _objc_inform("protocol_addProtocol: added protocol '%s' is still "
1960 "under construction!", addition->protocol_name);
1961 mutex_unlock(&classLock);
1965 struct old_protocol_list *protolist = proto->protocol_list;
1967 size_t size = sizeof(*protolist)
1968 + protolist->count * sizeof(protolist->list[0]);
1969 protolist = (struct old_protocol_list *)
1970 _realloc_internal(protolist, size);
1972 protolist = (struct old_protocol_list *)
1973 _calloc_internal(1, sizeof(struct old_protocol_list));
1976 protolist->list[protolist->count++] = addition;
1977 proto->protocol_list = protolist;
1979 mutex_unlock(&classLock);
1983 /***********************************************************************
1984 * protocol_addMethodDescription
1985 * Adds a method to a protocol. The protocol must be under construction.
1986 * Locking: acquires classLock
1987 **********************************************************************/
1989 _protocol_addMethod(struct objc_method_description_list **list, SEL name, const char *types)
1992 *list = (struct objc_method_description_list *)
1993 _calloc_internal(sizeof(struct objc_method_description_list), 1);
1995 size_t size = sizeof(struct objc_method_description_list)
1996 + (*list)->count * sizeof(struct objc_method_description);
1997 *list = (struct objc_method_description_list *)
1998 _realloc_internal(*list, size);
2001 struct objc_method_description *desc = &(*list)->list[(*list)->count++];
2003 desc->types = _strdup_internal(types ?: "");
2007 protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types,
2008 BOOL isRequiredMethod, BOOL isInstanceMethod)
2010 struct old_protocol *proto = oldprotocol(proto_gen);
2012 Class cls = (Class)objc_getClass("__IncompleteProtocol");
2014 if (!proto_gen) return;
2016 mutex_lock(&classLock);
2018 if (proto->isa != cls) {
2019 _objc_inform("protocol_addMethodDescription: protocol '%s' is not "
2020 "under construction!", proto->protocol_name);
2021 mutex_unlock(&classLock);
2025 if (isRequiredMethod && isInstanceMethod) {
2026 _protocol_addMethod(&proto->instance_methods, name, types);
2027 } else if (isRequiredMethod && !isInstanceMethod) {
2028 _protocol_addMethod(&proto->class_methods, name, types);
2029 } else if (!isRequiredMethod && isInstanceMethod) {
2030 struct old_protocol_ext *ext = (struct old_protocol_ext *)(proto+1);
2031 _protocol_addMethod(&ext->optional_instance_methods, name, types);
2032 } else /* !isRequiredMethod && !isInstanceMethod) */ {
2033 struct old_protocol_ext *ext = (struct old_protocol_ext *)(proto+1);
2034 _protocol_addMethod(&ext->optional_class_methods, name, types);
2037 mutex_unlock(&classLock);
2041 /***********************************************************************
2042 * protocol_addProperty
2043 * Adds a property to a protocol. The protocol must be under construction.
2044 * Locking: acquires classLock
2045 **********************************************************************/
2047 _protocol_addProperty(struct old_property_list **plist, const char *name,
2048 const objc_property_attribute_t *attrs,
2052 *plist = (struct old_property_list *)
2053 _calloc_internal(sizeof(struct old_property_list), 1);
2054 (*plist)->entsize = sizeof(struct old_property);
2056 *plist = (struct old_property_list *)
2057 _realloc_internal(*plist, sizeof(struct old_property_list)
2058 + (*plist)->count * (*plist)->entsize);
2061 struct old_property *prop = property_list_nth(*plist, (*plist)->count++);
2062 prop->name = _strdup_internal(name);
2063 prop->attributes = copyPropertyAttributeString(attrs, count);
2067 protocol_addProperty(Protocol *proto_gen, const char *name,
2068 const objc_property_attribute_t *attrs,
2070 BOOL isRequiredProperty, BOOL isInstanceProperty)
2072 struct old_protocol *proto = oldprotocol(proto_gen);
2074 Class cls = (Class)objc_getClass("__IncompleteProtocol");
2079 mutex_lock(&classLock);
2081 if (proto->isa != cls) {
2082 _objc_inform("protocol_addProperty: protocol '%s' is not "
2083 "under construction!", proto->protocol_name);
2084 mutex_unlock(&classLock);
2088 struct old_protocol_ext *ext = ext_for_protocol(proto);
2090 if (isRequiredProperty && isInstanceProperty) {
2091 _protocol_addProperty(&ext->instance_properties, name, attrs, count);
2093 //else if (isRequiredProperty && !isInstanceProperty) {
2094 // _protocol_addProperty(&ext->class_properties, name, attrs, count);
2095 //} else if (!isRequiredProperty && isInstanceProperty) {
2096 // _protocol_addProperty(&ext->optional_instance_properties, name, attrs, count);
2097 //} else /* !isRequiredProperty && !isInstanceProperty) */ {
2098 // _protocol_addProperty(&ext->optional_class_properties, name, attrs, count);
2101 mutex_unlock(&classLock);
2105 /***********************************************************************
2106 * _objc_fixup_protocol_objects_for_image. For each protocol in the
2107 * specified image, selectorize the method names and add to the protocol hash.
2108 **********************************************************************/
2110 static BOOL versionIsExt(uintptr_t version, const char *names, size_t size)
2112 // CodeWarrior used isa field for string "Protocol"
2113 // from section __OBJC,__class_names. rdar://4951638
2114 // gcc (10.4 and earlier) used isa field for version number;
2115 // the only version number used on Mac OS X was 2.
2116 // gcc (10.5 and later) uses isa field for ext pointer
2118 if (version < 4096) {
2122 if (version >= (uintptr_t)names && version < (uintptr_t)(names + size)) {
2129 static void fix_protocol(struct old_protocol *proto, Class protocolClass,
2130 BOOL isBundle, const char *names, size_t names_size)
2135 version = (uintptr_t)proto->isa;
2137 // Set the protocol's isa
2138 proto->isa = protocolClass;
2140 // Fix up method lists
2141 // fixme share across duplicates
2142 map_method_descs (proto->instance_methods, isBundle);
2143 map_method_descs (proto->class_methods, isBundle);
2145 // Fix up ext, if any
2146 if (versionIsExt(version, names, names_size)) {
2147 struct old_protocol_ext *ext = (struct old_protocol_ext *)version;
2148 NXMapInsert(protocol_ext_map, proto, ext);
2149 map_method_descs (ext->optional_instance_methods, isBundle);
2150 map_method_descs (ext->optional_class_methods, isBundle);
2153 // Record the protocol it if we don't have one with this name yet
2154 // fixme bundles - copy protocol
2156 if (!NXMapGet(protocol_map, proto->protocol_name)) {
2157 NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto);
2158 if (PrintProtocols) {
2159 _objc_inform("PROTOCOLS: protocol at %p is %s",
2160 proto, proto->protocol_name);
2163 // duplicate - do nothing
2164 if (PrintProtocols) {
2165 _objc_inform("PROTOCOLS: protocol at %p is %s (duplicate)",
2166 proto, proto->protocol_name);
2171 static void _objc_fixup_protocol_objects_for_image (header_info * hi)
2173 Class protocolClass = (Class)objc_getClass("Protocol");
2175 struct old_protocol **protos;
2176 int isBundle = headerIsBundle(hi);
2180 mutex_lock(&classLock);
2182 // Allocate the protocol registry if necessary.
2183 if (!protocol_map) {
2185 NXCreateMapTableFromZone(NXStrValueMapPrototype, 32,
2186 _objc_internal_zone());
2188 if (!protocol_ext_map) {
2190 NXCreateMapTableFromZone(NXPtrValueMapPrototype, 32,
2191 _objc_internal_zone());
2194 protos = _getObjcProtocols(hi, &count);
2195 names = _getObjcClassNames(hi, &names_size);
2196 for (i = 0; i < count; i++) {
2197 fix_protocol(protos[i], protocolClass, isBundle, names, names_size);
2200 mutex_unlock(&classLock);
2204 /***********************************************************************
2205 * _objc_fixup_selector_refs. Register all of the selectors in each
2206 * image, and fix them all up.
2207 **********************************************************************/
2208 static void _objc_fixup_selector_refs (const header_info *hi)
2214 if (sel_preoptimizationValid(hi)) {
2215 _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors in %s",
2218 else if (_objcHeaderOptimizedByDyld(hi)) {
2219 _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors in %s",
2224 if (sel_preoptimizationValid(hi)) return;
2226 sels = _getObjcSelectorRefs (hi, &count);
2228 map_selrefs(sels, count, headerIsBundle(hi));
2231 static inline BOOL _is_threaded() {
2235 return pthread_is_threaded_np() != 0;
2239 #if !TARGET_OS_WIN32
2240 /***********************************************************************
2242 * Process the given image which is about to be unmapped by dyld.
2243 * mh is mach_header instead of headerType because that's what
2244 * dyld_priv.h says even for 64-bit.
2245 **********************************************************************/
2247 unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide)
2249 recursive_mutex_lock(&loadMethodLock);
2250 unmap_image_nolock(mh);
2251 recursive_mutex_unlock(&loadMethodLock);
2255 /***********************************************************************
2257 * Process the given images which are being mapped in by dyld.
2258 * Calls ABI-agnostic code after taking ABI-specific locks.
2259 **********************************************************************/
2261 map_images(enum dyld_image_states state, uint32_t infoCount,
2262 const struct dyld_image_info infoList[])
2266 recursive_mutex_lock(&loadMethodLock);
2267 err = map_images_nolock(state, infoCount, infoList);
2268 recursive_mutex_unlock(&loadMethodLock);
2274 /***********************************************************************
2276 * Process +load in the given images which are being mapped in by dyld.
2277 * Calls ABI-agnostic code after taking ABI-specific locks.
2279 * Locking: acquires classLock and loadMethodLock
2280 **********************************************************************/
2282 load_images(enum dyld_image_states state, uint32_t infoCount,
2283 const struct dyld_image_info infoList[])
2287 recursive_mutex_lock(&loadMethodLock);
2289 // Discover +load methods
2290 found = load_images_nolock(state, infoCount, infoList);
2292 // Call +load methods (without classLock - re-entrant)
2294 call_load_methods();
2297 recursive_mutex_unlock(&loadMethodLock);
2304 /***********************************************************************
2306 * Perform metadata processing for hCount images starting with firstNewHeader
2307 **********************************************************************/
2308 void _read_images(header_info **hList, uint32_t hCount)
2311 BOOL categoriesLoaded = NO;
2313 if (!class_hash) _objc_init_class_hash();
2315 // Parts of this order are important for correctness or performance.
2317 // Read classes from all images.
2318 for (i = 0; i < hCount; i++) {
2319 _objc_read_classes_from_image(hList[i]);
2322 // Read categories from all images.
2323 // But not if any other threads are running - they might
2324 // call a category method before the fixups below are complete.
2325 if (!_is_threaded()) {
2326 BOOL needFlush = NO;
2327 for (i = 0; i < hCount; i++) {
2328 needFlush |= _objc_read_categories_from_image(hList[i]);
2330 if (needFlush) flush_marked_caches();
2331 categoriesLoaded = YES;
2334 // Connect classes from all images.
2335 for (i = 0; i < hCount; i++) {
2336 _objc_connect_classes_from_image(hList[i]);
2339 // Fix up class refs, selector refs, and protocol objects from all images.
2340 for (i = 0; i < hCount; i++) {
2341 _objc_map_class_refs_for_image(hList[i]);
2342 _objc_fixup_selector_refs(hList[i]);
2343 _objc_fixup_protocol_objects_for_image(hList[i]);
2346 // Read categories from all images.
2347 // But not if this is the only thread - it's more
2348 // efficient to attach categories earlier if safe.
2349 if (!categoriesLoaded) {
2350 BOOL needFlush = NO;
2351 for (i = 0; i < hCount; i++) {
2352 needFlush |= _objc_read_categories_from_image(hList[i]);
2354 if (needFlush) flush_marked_caches();
2357 // Multi-threaded category load MUST BE LAST to avoid a race.
2361 /***********************************************************************
2362 * prepare_load_methods
2363 * Schedule +load for classes in this image, any un-+load-ed
2364 * superclasses in other images, and any categories in this image.
2365 **********************************************************************/
2366 // Recursively schedule +load for cls and any un-+load-ed superclasses.
2367 // cls must already be connected.
2368 static void schedule_class_load(struct old_class *cls)
2370 if (cls->info & CLS_LOADED) return;
2371 if (cls->super_class) schedule_class_load(cls->super_class);
2372 add_class_to_loadable_list((Class)cls);
2373 cls->info |= CLS_LOADED;
2376 void prepare_load_methods(header_info *hi)
2382 if (_objcHeaderIsReplacement(hi)) {
2383 // Ignore any classes in this image
2387 // Major loop - process all modules in the image
2389 for (midx = 0; midx < hi->mod_count; midx += 1)
2393 // Skip module containing no classes
2394 if (mods[midx].symtab == NULL)
2397 // Minor loop - process all the classes in given module
2398 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
2400 // Locate the class description pointer
2401 struct old_class *cls = mods[midx].symtab->defs[index];
2402 if (cls->info & CLS_CONNECTED) {
2403 schedule_class_load(cls);
2409 // Major loop - process all modules in the header
2412 // NOTE: The module and category lists are traversed backwards
2413 // to preserve the pre-10.4 processing order. Changing the order
2414 // would have a small chance of introducing binary compatibility bugs.
2415 midx = (unsigned int)hi->mod_count;
2416 while (midx-- > 0) {
2419 Symtab symtab = mods[midx].symtab;
2421 // Nothing to do for a module without a symbol table
2422 if (mods[midx].symtab == NULL)
2424 // Total entries in symbol table (class entries followed
2425 // by category entries)
2426 total = mods[midx].symtab->cls_def_cnt +
2427 mods[midx].symtab->cat_def_cnt;
2429 // Minor loop - register all categories from given module
2431 while (index-- > mods[midx].symtab->cls_def_cnt) {
2432 struct old_category *cat = symtab->defs[index];
2433 add_category_to_loadable_list((Category)cat);
2441 void unload_class(struct old_class *cls)
2447 /***********************************************************************
2448 * _objc_remove_classes_in_image
2449 * Remove all classes in the given image from the runtime, because
2450 * the image is about to be unloaded.
2451 * Things to clean up:
2453 * unconnected_class_hash
2454 * pending subclasses list (only if class is still unconnected)
2455 * loadable class list
2456 * class's method caches
2457 * class refs in all other images
2458 **********************************************************************/
2459 // Re-pend any class references in refs that point into [start..end)
2460 static void rependClassReferences(struct old_class **refs, size_t count,
2461 uintptr_t start, uintptr_t end)
2467 // Process each class ref
2468 for (i = 0; i < count; i++) {
2469 if ((uintptr_t)(refs[i]) >= start && (uintptr_t)(refs[i]) < end) {
2470 pendClassReference(&refs[i], refs[i]->name,
2471 (refs[i]->info & CLS_META) ? YES : NO);
2478 void try_free(const void *p)
2480 if (p && malloc_size(p)) free((void *)p);
2483 // Deallocate all memory in a method list
2484 static void unload_mlist(struct old_method_list *mlist)
2487 for (i = 0; i < mlist->method_count; i++) {
2488 try_free(mlist->method_list[i].method_types);
2493 static void unload_property_list(struct old_property_list *proplist)
2497 if (!proplist) return;
2499 for (i = 0; i < proplist->count; i++) {
2500 struct old_property *prop = property_list_nth(proplist, i);
2501 try_free(prop->name);
2502 try_free(prop->attributes);
2508 // Deallocate all memory in a class.
2509 void unload_class(struct old_class *cls)
2511 // Free method cache
2512 // This dereferences the cache contents; do this before freeing methods
2513 if (cls->cache && cls->cache != &_objc_empty_cache) {
2514 _cache_free(cls->cache);
2520 for (i = 0; i < cls->ivars->ivar_count; i++) {
2521 try_free(cls->ivars->ivar_list[i].ivar_name);
2522 try_free(cls->ivars->ivar_list[i].ivar_type);
2524 try_free(cls->ivars);
2527 // Free fixed-up method lists and method list array
2528 if (cls->methodLists) {
2529 // more than zero method lists
2530 if (cls->info & CLS_NO_METHOD_ARRAY) {
2532 unload_mlist((struct old_method_list *)cls->methodLists);
2535 // more than one method list
2536 struct old_method_list **mlistp;
2537 for (mlistp = cls->methodLists;
2538 *mlistp != NULL && *mlistp != END_OF_METHODS_LIST;
2541 unload_mlist(*mlistp);
2543 free(cls->methodLists);
2547 // Free protocol list
2548 struct old_protocol_list *protos = cls->protocols;
2550 struct old_protocol_list *dead = protos;
2551 protos = protos->next;
2555 if ((cls->info & CLS_EXT)) {
2557 // Free property lists and property list array
2558 if (cls->ext->propertyLists) {
2559 // more than zero property lists
2560 if (cls->info & CLS_NO_PROPERTY_ARRAY) {
2561 // one property list
2562 struct old_property_list *proplist =
2563 (struct old_property_list *)cls->ext->propertyLists;
2564 unload_property_list(proplist);
2566 // more than one property list
2567 struct old_property_list **plistp;
2568 for (plistp = cls->ext->propertyLists;
2572 unload_property_list(*plistp);
2574 try_free(cls->ext->propertyLists);
2578 // Free weak ivar layout
2579 try_free(cls->ext->weak_ivar_layout);
2585 // Free non-weak ivar layout
2586 try_free(cls->ivar_layout);
2590 try_free(cls->name);
2597 static void _objc_remove_classes_in_image(header_info *hi)
2603 mutex_lock(&classLock);
2605 // Major loop - process all modules in the image
2607 for (midx = 0; midx < hi->mod_count; midx += 1)
2609 // Skip module containing no classes
2610 if (mods[midx].symtab == NULL)
2613 // Minor loop - process all the classes in given module
2614 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
2616 struct old_class *cls;
2618 // Locate the class description pointer
2619 cls = mods[midx].symtab->defs[index];
2621 // Remove from loadable class list, if present
2622 remove_class_from_loadable_list((Class)cls);
2624 // Remove from unconnected_class_hash and pending subclasses
2625 if (unconnected_class_hash && NXHashMember(unconnected_class_hash, cls)) {
2626 NXHashRemove(unconnected_class_hash, cls);
2627 if (pendingSubclassesMap) {
2628 // Find this class in its superclass's pending list
2629 char *supercls_name = (char *)cls->super_class;
2630 PendingSubclass *pending =
2631 NXMapGet(pendingSubclassesMap, supercls_name);
2632 for ( ; pending != NULL; pending = pending->next) {
2633 if (pending->subclass == cls) {
2634 pending->subclass = Nil;
2641 // Remove from class_hash
2642 NXHashRemove(class_hash, cls);
2643 objc_removeRegisteredClass((Class)cls);
2645 // Free heap memory pointed to by the class
2646 unload_class(cls->isa);
2652 // Search all other images for class refs that point back to this range.
2653 // Un-fix and re-pend any such class refs.
2655 // Get the location of the dying image's __OBJC segment
2657 unsigned long seg_size;
2658 seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size);
2660 header_info *other_hi;
2661 for (other_hi = FirstHeader; other_hi != NULL; other_hi = other_hi->next) {
2662 struct old_class **other_refs;
2664 if (other_hi == hi) continue; // skip the image being unloaded
2666 // Fix class refs in the other image
2667 other_refs = _getObjcClassRefs(other_hi, &count);
2668 rependClassReferences(other_refs, count, seg, seg+seg_size);
2671 mutex_unlock(&classLock);
2675 /***********************************************************************
2676 * _objc_remove_categories_in_image
2677 * Remove all categories in the given image from the runtime, because
2678 * the image is about to be unloaded.
2679 * Things to clean up:
2680 * unresolved category list
2681 * loadable category list
2682 **********************************************************************/
2683 static void _objc_remove_categories_in_image(header_info *hi)
2688 // Major loop - process all modules in the header
2691 for (midx = 0; midx < hi->mod_count; midx++) {
2694 Symtab symtab = mods[midx].symtab;
2696 // Nothing to do for a module without a symbol table
2697 if (symtab == NULL) continue;
2699 // Total entries in symbol table (class entries followed
2700 // by category entries)
2701 total = symtab->cls_def_cnt + symtab->cat_def_cnt;
2703 // Minor loop - check all categories from given module
2704 for (index = symtab->cls_def_cnt; index < total; index++) {
2705 struct old_category *cat = symtab->defs[index];
2707 // Clean up loadable category list
2708 remove_category_from_loadable_list((Category)cat);
2710 // Clean up category_hash
2711 if (category_hash) {
2712 _objc_unresolved_category *cat_entry =
2713 NXMapGet(category_hash, cat->class_name);
2714 for ( ; cat_entry != NULL; cat_entry = cat_entry->next) {
2715 if (cat_entry->cat == cat) {
2716 cat_entry->cat = NULL;
2726 /***********************************************************************
2728 * Various paranoid debugging checks that look for poorly-behaving
2729 * unloadable bundles.
2730 * Called by _objc_unmap_image when OBJC_UNLOAD_DEBUG is set.
2731 **********************************************************************/
2732 static void unload_paranoia(header_info *hi)
2734 // Get the location of the dying image's __OBJC segment
2736 unsigned long seg_size;
2737 seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size);
2739 _objc_inform("UNLOAD DEBUG: unloading image '%s' [%p..%p]",
2740 hi->fname, (void *)seg, (void*)(seg+seg_size));
2742 mutex_lock(&classLock);
2744 // Make sure the image contains no categories on surviving classes.
2749 // Major loop - process all modules in the header
2752 for (midx = 0; midx < hi->mod_count; midx++) {
2755 Symtab symtab = mods[midx].symtab;
2757 // Nothing to do for a module without a symbol table
2758 if (symtab == NULL) continue;
2760 // Total entries in symbol table (class entries followed
2761 // by category entries)
2762 total = symtab->cls_def_cnt + symtab->cat_def_cnt;
2764 // Minor loop - check all categories from given module
2765 for (index = symtab->cls_def_cnt; index < total; index++) {
2766 struct old_category *cat = symtab->defs[index];
2767 struct old_class query;
2769 query.name = cat->class_name;
2770 if (NXHashMember(class_hash, &query)) {
2771 _objc_inform("UNLOAD DEBUG: dying image contains category '%s(%s)' on surviving class '%s'!", cat->class_name, cat->category_name, cat->class_name);
2777 // Make sure no surviving class is in the dying image.
2778 // Make sure no surviving class has a superclass in the dying image.
2779 // fixme check method implementations too
2781 struct old_class *cls;
2784 state = NXInitHashState(class_hash);
2785 while (NXNextHashState(class_hash, &state, (void **)&cls)) {
2786 if ((vm_address_t)cls >= seg &&
2787 (vm_address_t)cls < seg+seg_size)
2789 _objc_inform("UNLOAD DEBUG: dying image contains surviving class '%s'!", cls->name);
2792 if ((vm_address_t)cls->super_class >= seg &&
2793 (vm_address_t)cls->super_class < seg+seg_size)
2795 _objc_inform("UNLOAD DEBUG: dying image contains superclass '%s' of surviving class '%s'!", cls->super_class->name, cls->name);
2800 mutex_unlock(&classLock);
2804 /***********************************************************************
2806 * Only handles MH_BUNDLE for now.
2807 * Locking: loadMethodLock acquired by unmap_image
2808 **********************************************************************/
2809 void _unload_image(header_info *hi)
2811 recursive_mutex_assert_locked(&loadMethodLock);
2814 // Remove image's classes from the class list and free auxiliary data.
2815 // Remove image's unresolved or loadable categories and free auxiliary data
2816 // Remove image's unresolved class refs.
2817 _objc_remove_classes_in_image(hi);
2818 _objc_remove_categories_in_image(hi);
2819 _objc_remove_pending_class_refs_in_image(hi);
2821 // Perform various debugging checks if requested.
2822 if (DebugUnload) unload_paranoia(hi);
2828 /***********************************************************************
2829 * objc_addClass. Add the specified class to the table of known classes,
2830 * after doing a little verification and fixup.
2831 **********************************************************************/
2832 void objc_addClass (Class cls_gen)
2834 struct old_class *cls = oldcls(cls_gen);
2836 OBJC_WARN_DEPRECATED;
2838 // Synchronize access to hash table
2839 mutex_lock (&classLock);
2841 // Make sure both the class and the metaclass have caches!
2842 // Clear all bits of the info fields except CLS_CLASS and CLS_META.
2843 // Normally these bits are already clear but if someone tries to cons
2844 // up their own class on the fly they might need to be cleared.
2845 if (cls->cache == NULL) {
2846 cls->cache = (Cache) &_objc_empty_cache;
2847 cls->info = CLS_CLASS;
2850 if (cls->isa->cache == NULL) {
2851 cls->isa->cache = (Cache) &_objc_empty_cache;
2852 cls->isa->info = CLS_META;
2855 // methodLists should be:
2856 // 1. NULL (Tiger and later only)
2857 // 2. A -1 terminated method list array
2858 // In either case, CLS_NO_METHOD_ARRAY remains clear.
2859 // If the user manipulates the method list directly,
2860 // they must use the magic private format.
2862 // Add the class to the table
2863 (void) NXHashInsert (class_hash, cls);
2864 objc_addRegisteredClass((Class)cls);
2866 // Superclass is no longer a leaf for cache flushing
2867 if (cls->super_class && (cls->super_class->info & CLS_LEAF)) {
2868 _class_clearInfo((Class)cls->super_class, CLS_LEAF);
2869 _class_clearInfo((Class)cls->super_class->isa, CLS_LEAF);
2873 mutex_unlock (&classLock);
2876 /***********************************************************************
2877 * _objcTweakMethodListPointerForClass.
2878 * Change the class's method list pointer to a method list array.
2879 * Does nothing if the method list pointer is already a method list array.
2880 * If the class is currently in use, methodListLock must be held by the caller.
2881 **********************************************************************/
2882 static void _objcTweakMethodListPointerForClass(struct old_class *cls)
2884 struct old_method_list * originalList;
2885 const int initialEntries = 4;
2887 struct old_method_list ** ptr;
2889 // Do nothing if methodLists is already an array.
2890 if (cls->methodLists && !(cls->info & CLS_NO_METHOD_ARRAY)) return;
2892 // Remember existing list
2893 originalList = (struct old_method_list *) cls->methodLists;
2895 // Allocate and zero a method list array
2896 mallocSize = sizeof(struct old_method_list *) * initialEntries;
2897 ptr = (struct old_method_list **) _calloc_internal(1, mallocSize);
2899 // Insert the existing list into the array
2900 ptr[initialEntries - 1] = END_OF_METHODS_LIST;
2901 ptr[0] = originalList;
2903 // Replace existing list with array
2904 cls->methodLists = ptr;
2905 _class_clearInfo((Class)cls, CLS_NO_METHOD_ARRAY);
2909 /***********************************************************************
2910 * _objc_insertMethods.
2911 * Adds methods to a class.
2912 * Does not flush any method caches.
2913 * Does not take any locks.
2914 * If the class is already in use, use class_addMethods() instead.
2915 **********************************************************************/
2916 void _objc_insertMethods(struct old_class *cls,
2917 struct old_method_list *mlist,
2918 struct old_category *cat)
2920 struct old_method_list ***list;
2921 struct old_method_list **ptr;
2926 if (!cls->methodLists) {
2927 // cls has no methods - simply use this method list
2928 cls->methodLists = (struct old_method_list **)mlist;
2929 _class_setInfo((Class)cls, CLS_NO_METHOD_ARRAY);
2933 // Log any existing methods being replaced
2934 if (PrintReplacedMethods) {
2936 for (i = 0; i < mlist->method_count; i++) {
2937 extern IMP findIMPInClass(struct old_class *cls, SEL sel);
2938 SEL sel = sel_registerName((char *)mlist->method_list[i].method_name);
2939 IMP newImp = mlist->method_list[i].method_imp;
2942 if ((oldImp = findIMPInClass(cls, sel))) {
2943 logReplacedMethod(cls->name, sel, ISMETA(cls),
2944 cat ? cat->category_name : NULL,
2950 // Create method list array if necessary
2951 _objcTweakMethodListPointerForClass(cls);
2953 list = &cls->methodLists;
2955 // Locate unused entry for insertion point
2957 while ((*ptr != 0) && (*ptr != END_OF_METHODS_LIST))
2960 // If array is full, add to it
2961 if (*ptr == END_OF_METHODS_LIST)
2963 // Calculate old and new dimensions
2964 endIndex = ptr - *list;
2965 oldSize = (endIndex + 1) * sizeof(void *);
2966 newSize = oldSize + sizeof(struct old_method_list *); // only increase by 1
2968 // Grow the method list array by one.
2969 // This block may be from user code; don't use _realloc_internal
2970 *list = (struct old_method_list **)realloc(*list, newSize);
2972 // Zero out addition part of new array
2973 bzero (&((*list)[endIndex]), newSize - oldSize);
2975 // Place new end marker
2976 (*list)[(newSize/sizeof(void *)) - 1] = END_OF_METHODS_LIST;
2978 // Insertion point corresponds to old array end
2979 ptr = &((*list)[endIndex]);
2982 // Right shift existing entries by one
2983 bcopy (*list, (*list) + 1, (uint8_t *)ptr - (uint8_t *)*list);
2985 // Insert at method list at beginning of array
2989 /***********************************************************************
2990 * _objc_removeMethods.
2991 * Remove methods from a class.
2992 * Does not take any locks.
2993 * Does not flush any method caches.
2994 * If the class is currently in use, use class_removeMethods() instead.
2995 **********************************************************************/
2996 void _objc_removeMethods(struct old_class *cls,
2997 struct old_method_list *mlist)
2999 struct old_method_list ***list;
3000 struct old_method_list **ptr;
3002 if (cls->methodLists == NULL) {
3003 // cls has no methods
3006 if (cls->methodLists == (struct old_method_list **)mlist) {
3007 // mlist is the class's only method list - erase it
3008 cls->methodLists = NULL;
3011 if (cls->info & CLS_NO_METHOD_ARRAY) {
3012 // cls has only one method list, and this isn't it - do nothing
3016 // cls has a method list array - search it
3018 list = &cls->methodLists;
3020 // Locate list in the array
3022 while (*ptr != mlist) {
3023 // fix for radar # 2538790
3024 if ( *ptr == END_OF_METHODS_LIST ) return;
3028 // Remove this entry
3031 // Left shift the following entries
3032 while (*(++ptr) != END_OF_METHODS_LIST)
3037 /***********************************************************************
3038 * _objc_add_category. Install the specified category's methods and
3039 * protocols into the class it augments.
3040 * The class is assumed not to be in use yet: no locks are taken and
3041 * no method caches are flushed.
3042 **********************************************************************/
3043 static inline void _objc_add_category(struct old_class *cls, struct old_category *category, int version)
3045 if (PrintConnecting) {
3046 _objc_inform("CONNECT: attaching category '%s (%s)'", cls->name, category->category_name);
3049 // Augment instance methods
3050 if (category->instance_methods)
3051 _objc_insertMethods (cls, category->instance_methods, category);
3053 // Augment class methods
3054 if (category->class_methods)
3055 _objc_insertMethods (cls->isa, category->class_methods, category);
3057 // Augment protocols
3058 if ((version >= 5) && category->protocols)
3060 if (cls->isa->version >= 5)
3062 category->protocols->next = cls->protocols;
3063 cls->protocols = category->protocols;
3064 cls->isa->protocols = category->protocols;
3068 _objc_inform ("unable to add protocols from category %s...\n", category->category_name);
3069 _objc_inform ("class `%s' must be recompiled\n", category->class_name);
3073 // Augment properties
3074 if (version >= 7 && category->instance_properties) {
3075 if (cls->isa->version >= 6) {
3076 _class_addProperties(cls, category->instance_properties);
3078 _objc_inform ("unable to add properties from category %s...\n", category->category_name);
3079 _objc_inform ("class `%s' must be recompiled\n", category->class_name);
3084 /***********************************************************************
3085 * _objc_add_category_flush_caches. Install the specified category's
3086 * methods into the class it augments, and flush the class' method cache.
3087 * Return YES if some method caches now need to be flushed.
3088 **********************************************************************/
3089 static BOOL _objc_add_category_flush_caches(struct old_class *cls, struct old_category *category, int version)
3091 BOOL needFlush = NO;
3093 // Install the category's methods into its intended class
3094 mutex_lock(&methodListLock);
3095 _objc_add_category (cls, category, version);
3096 mutex_unlock(&methodListLock);
3098 // Queue for cache flushing so category's methods can get called
3099 if (category->instance_methods) {
3100 _class_setInfo((Class)cls, CLS_FLUSH_CACHE);
3103 if (category->class_methods) {
3104 _class_setInfo((Class)cls->isa, CLS_FLUSH_CACHE);
3112 /***********************************************************************
3114 * Reverse the given linked list of pending categories.
3115 * The pending category list is built backwards, and needs to be
3116 * reversed before actually attaching the categories to a class.
3117 * Returns the head of the new linked list.
3118 **********************************************************************/
3119 static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat)
3121 _objc_unresolved_category *prev;
3122 _objc_unresolved_category *cur;
3123 _objc_unresolved_category *ahead;
3125 if (!cat) return NULL;
3142 /***********************************************************************
3143 * resolve_categories_for_class.
3144 * Install all existing categories intended for the specified class.
3145 * cls must be a true class and not a metaclass.
3146 **********************************************************************/
3147 static void resolve_categories_for_class(struct old_class *cls)
3149 _objc_unresolved_category * pending;
3150 _objc_unresolved_category * next;
3152 // Nothing to do if there are no categories at all
3153 if (!category_hash) return;
3155 // Locate and remove first element in category list
3156 // associated with this class
3157 pending = NXMapKeyFreeingRemove (category_hash, cls->name);
3159 // Traverse the list of categories, if any, registered for this class
3161 // The pending list is built backwards. Reverse it and walk forwards.
3162 pending = reverse_cat(pending);
3166 // Install the category
3167 // use the non-flush-cache version since we are only
3168 // called from the class intialization code
3169 _objc_add_category(cls, pending->cat, (int)pending->version);
3172 // Delink and reclaim this registration
3173 next = pending->next;
3174 _free_internal(pending);
3180 /***********************************************************************
3181 * _objc_resolve_categories_for_class.
3182 * Public version of resolve_categories_for_class. This was
3183 * exported pre-10.4 for Omni et al. to workaround a problem
3184 * with too-lazy category attachment.
3185 * cls should be a class, but this function can also cope with metaclasses.
3186 **********************************************************************/
3187 void _objc_resolve_categories_for_class(Class cls_gen)
3189 struct old_class *cls = oldcls(cls_gen);
3191 // If cls is a metaclass, get the class.
3192 // resolve_categories_for_class() requires a real class to work correctly.
3194 if (strncmp(cls->name, "_%", 2) == 0) {
3195 // Posee's meta's name is smashed and isn't in the class_hash,
3196 // so objc_getClass doesn't work.
3197 const char *baseName = strchr(cls->name, '%'); // get posee's real name
3198 cls = oldcls((Class)objc_getClass(baseName));
3200 cls = oldcls((Class)objc_getClass(cls->name));
3204 resolve_categories_for_class(cls);
3208 /***********************************************************************
3209 * _objc_register_category.
3210 * Process a category read from an image.
3211 * If the category's class exists, attach the category immediately.
3212 * Classes that need cache flushing are marked but not flushed.
3213 * If the category's class does not exist yet, pend the category for
3214 * later attachment. Pending categories are attached in the order
3215 * they were discovered.
3216 * Returns YES if some method caches now need to be flushed.
3217 **********************************************************************/
3218 static BOOL _objc_register_category(struct old_category *cat, int version)
3220 _objc_unresolved_category * new_cat;
3221 _objc_unresolved_category * old;
3222 struct old_class *theClass;
3224 // If the category's class exists, attach the category.
3225 if ((theClass = oldcls((Class)objc_lookUpClass(cat->class_name)))) {
3226 return _objc_add_category_flush_caches(theClass, cat, version);
3229 // If the category's class exists but is unconnected,
3230 // then attach the category to the class but don't bother
3231 // flushing any method caches (because they must be empty).
3232 // YES unconnected, NO class_handler
3233 if ((theClass = oldcls((Class)look_up_class(cat->class_name, YES, NO)))) {
3234 _objc_add_category(theClass, cat, version);
3239 // Category's class does not exist yet.
3240 // Save the category for later attachment.
3242 if (PrintConnecting) {
3243 _objc_inform("CONNECT: pending category '%s (%s)'", cat->class_name, cat->category_name);
3246 // Create category lookup table if needed
3248 category_hash = NXCreateMapTableFromZone (NXStrValueMapPrototype,
3250 _objc_internal_zone ());
3252 // Locate an existing list of categories, if any, for the class.
3253 old = NXMapGet (category_hash, cat->class_name);
3255 // Register the category to be fixed up later.
3256 // The category list is built backwards, and is reversed again
3257 // by resolve_categories_for_class().
3258 new_cat = _malloc_internal(sizeof(_objc_unresolved_category));
3259 new_cat->next = old;
3261 new_cat->version = version;
3262 (void) NXMapKeyCopyingInsert (category_hash, cat->class_name, new_cat);
3269 _objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount)
3282 for (m = 0; m < hi->mod_count; m++) {
3285 if (!mods[m].symtab) continue;
3287 for (d = 0; d < mods[m].symtab->cls_def_cnt; d++) {
3288 struct old_class *cls = mods[m].symtab->defs[d];
3289 // fixme what about future-ified classes?
3290 if (class_is_connected(cls)) {
3291 if (count == allocated) {
3292 allocated = allocated*2 + 16;
3293 list = (const char **)
3294 realloc((void *)list, allocated * sizeof(char *));
3296 list[count++] = cls->name;
3302 // NULL-terminate non-empty list
3303 if (count == allocated) {
3304 allocated = allocated+1;
3305 list = (const char **)
3306 realloc((void *)list, allocated * sizeof(char *));
3311 if (outCount) *outCount = count;
3315 Class gdb_class_getClass(Class cls)
3317 const char *className = cls->name;
3318 if(!className || !strlen(className)) return Nil;
3319 Class rCls = look_up_class(className, NO, NO);
3324 Class gdb_object_getClass(id obj)
3326 Class cls = _object_getClass(obj);
3327 return gdb_class_getClass(cls);
3330 BOOL gdb_objc_isRuntimeLocked()
3332 if (mutex_try_lock(&methodListLock)) {
3333 mutex_unlock(&methodListLock);
3337 if (mutex_try_lock(&classLock)) {
3338 mutex_unlock(&classLock);
3342 if (mutex_try_lock(&cacheUpdateLock)) {
3343 mutex_unlock(&cacheUpdateLock);
3351 /***********************************************************************
3353 * Every lock used anywhere must be managed here.
3354 * Locks not managed here may cause gdb deadlocks.
3355 **********************************************************************/
3356 rwlock_t selLock = {};
3357 mutex_t classLock = MUTEX_INITIALIZER;
3358 mutex_t methodListLock = MUTEX_INITIALIZER;
3359 mutex_t cacheUpdateLock = MUTEX_INITIALIZER;
3360 recursive_mutex_t loadMethodLock = RECURSIVE_MUTEX_INITIALIZER;
3361 static int debugger_selLock;
3362 static int debugger_loadMethodLock;
3366 void lock_init(void)
3368 rwlock_init(&selLock);
3369 recursive_mutex_init(&loadMethodLock);
3373 #if SUPPORT_DEBUGGER_MODE
3375 /***********************************************************************
3377 * Attempt to acquire some locks for debugger mode.
3378 * Returns 0 if debugger mode failed because too many locks are unavailable.
3380 * Locks successfully acquired are held until endDebuggerMode().
3381 * Locks not acquired are off-limits until endDebuggerMode(); any
3382 * attempt to manipulate them will cause a trap.
3383 * Locks not handled here may cause deadlocks in gdb.
3384 **********************************************************************/
3385 int startDebuggerMode(void)
3387 int result = DEBUGGER_FULL;
3389 // classLock is required
3390 // methodListLock is required
3391 // cacheUpdateLock is required
3392 // fixme might be able to allow all-or-none
3393 if (! mutex_try_lock(&classLock)) {
3394 return DEBUGGER_OFF;
3396 if (! mutex_try_lock(&methodListLock)) {
3397 mutex_unlock(&classLock);
3398 return DEBUGGER_OFF;
3400 if (! mutex_try_lock(&cacheUpdateLock)) {
3401 mutex_unlock(&methodListLock);
3402 mutex_unlock(&classLock);
3403 return DEBUGGER_OFF;
3406 // side table locks are not optional because we're being conservative
3407 if (!noSideTableLocksHeld()) {
3408 mutex_unlock(&cacheUpdateLock);
3409 mutex_unlock(&methodListLock);
3410 mutex_unlock(&classLock);
3411 return DEBUGGER_OFF;
3414 // selLock is optional
3415 if (rwlock_try_write(&selLock)) {
3416 debugger_selLock = RDWR;
3417 } else if (rwlock_try_read(&selLock)) {
3418 debugger_selLock = RDONLY;
3419 result = DEBUGGER_PARTIAL;
3421 debugger_selLock = 0;
3422 result = DEBUGGER_PARTIAL;
3425 // loadMethodLock is optional
3426 if (recursive_mutex_try_lock(&loadMethodLock)) {
3427 debugger_loadMethodLock = RDWR;
3429 debugger_loadMethodLock = 0;
3430 result = DEBUGGER_PARTIAL;
3436 /***********************************************************************
3438 * Relinquish locks acquired in startDebuggerMode().
3439 **********************************************************************/
3440 void endDebuggerMode(void)
3442 if (debugger_loadMethodLock) {
3443 recursive_mutex_unlock(&loadMethodLock);
3444 debugger_loadMethodLock = 0;
3446 rwlock_unlock(&selLock, debugger_selLock);
3447 debugger_selLock = 0;
3448 mutex_unlock(&classLock);
3449 mutex_unlock(&methodListLock);
3450 mutex_unlock(&cacheUpdateLock);
3453 /***********************************************************************
3454 * isManagedDuringDebugger
3455 * Returns YES if the given lock is handled specially during debugger
3456 * mode (i.e. debugger mode tries to acquire it).
3457 **********************************************************************/
3458 BOOL isManagedDuringDebugger(void *lock)
3460 if (lock == &selLock) return YES;
3461 if (lock == &classLock) return YES;
3462 if (lock == &methodListLock) return YES;
3463 if (lock == &cacheUpdateLock) return YES;
3464 if (lock == &loadMethodLock) return YES;
3468 /***********************************************************************
3469 * isLockedDuringDebugger
3470 * Returns YES if the given mutex was acquired by debugger mode.
3471 * Locking a managed mutex during debugger mode causes a trap unless
3473 **********************************************************************/
3474 BOOL isLockedDuringDebugger(void *lock)
3476 assert(DebuggerMode);
3478 if (lock == &classLock) return YES;
3479 if (lock == &methodListLock) return YES;
3480 if (lock == &cacheUpdateLock) return YES;
3481 if (lock == (mutex_t *)&loadMethodLock) return YES;
3485 /***********************************************************************
3486 * isReadingDuringDebugger
3487 * Returns YES if the given rwlock was read-locked by debugger mode.
3488 * Read-locking a managed rwlock during debugger mode causes a trap unless
3490 **********************************************************************/
3491 BOOL isReadingDuringDebugger(rwlock_t *lock)
3493 assert(DebuggerMode);
3495 // read-lock is allowed even if debugger mode actually write-locked it
3496 if (debugger_selLock && lock == &selLock) return YES;
3501 /***********************************************************************
3502 * isWritingDuringDebugger
3503 * Returns YES if the given rwlock was write-locked by debugger mode.
3504 * Write-locking a managed rwlock during debugger mode causes a trap unless
3506 **********************************************************************/
3507 BOOL isWritingDuringDebugger(rwlock_t *lock)
3509 assert(DebuggerMode);
3511 if (debugger_selLock == RDWR && lock == &selLock) return YES;
3516 // SUPPORT_DEBUGGER_MODE