]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-runtime-old.mm
045db633d2c228a4202c9778b46fe5e8a708008e
[apple/objc4.git] / runtime / objc-runtime-old.mm
1 /*
2 * Copyright (c) 1999-2007 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /***********************************************************************
25 * objc-runtime-old.m
26 * Support for old-ABI classes and images.
27 **********************************************************************/
28
29 /***********************************************************************
30 * Class loading and connecting (GrP 2004-2-11)
31 *
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
35 * +load methods.
36 *
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.
41 *
42 * (Historical note)
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)
53 *
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.
60 *
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.
67 *
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.
74 *
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.
79 *
80 * Image mapping sequence:
81 *
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),
88 * and pend the rest.
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:
95 * connect the class
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.
109 *
110 * Performance: all classes are read before any categories are read.
111 * Fewer categories need be pended for lack of a parent class.
112 *
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.)
117 *
118 * Performance: all classes are read before any classes are connected.
119 * Fewer classes need be pended for lack of a superclass.
120 *
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.
124 *
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.
129 *
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.
134 *
135 * Correctness: pended class refs are not fixed up until the class is
136 * connected. Classes with missing weak superclasses remain unconnected.
137 * Class refs to classes with missing weak superclasses must be nil.
138 * Therefore class refs to unconnected classes must remain un-fixed.
139 *
140 **********************************************************************/
141
142 #if !__OBJC2__
143
144 #include "objc-private.h"
145 #include "objc-runtime-old.h"
146 #include "objc-file-old.h"
147 #include "objc-cache-old.h"
148 #include "objc-loadmethod.h"
149
150
151 typedef struct _objc_unresolved_category
152 {
153 struct _objc_unresolved_category *next;
154 old_category *cat; // may be nil
155 long version;
156 } _objc_unresolved_category;
157
158 typedef struct _PendingSubclass
159 {
160 Class subclass; // subclass to finish connecting; may be nil
161 struct _PendingSubclass *next;
162 } PendingSubclass;
163
164 typedef struct _PendingClassRef
165 {
166 Class *ref; // class reference to fix up; may be nil
167 // (ref & 1) is a metaclass reference
168 struct _PendingClassRef *next;
169 } PendingClassRef;
170
171
172 static uintptr_t classHash(void *info, Class data);
173 static int classIsEqual(void *info, Class name, Class cls);
174 static int _objc_defaultClassHandler(const char *clsName);
175 static inline NXMapTable *pendingClassRefsMapTable(void);
176 static inline NXMapTable *pendingSubclassesMapTable(void);
177 static void pendClassInstallation(Class cls, const char *superName);
178 static void pendClassReference(Class *ref, const char *className, bool isMeta);
179 static void resolve_references_to_class(Class cls);
180 static void resolve_subclasses_of_class(Class cls);
181 static void really_connect_class(Class cls, Class supercls);
182 static bool connect_class(Class cls);
183 static void map_method_descs (struct objc_method_description_list * methods, bool copy);
184 static void _objcTweakMethodListPointerForClass(Class cls);
185 static inline void _objc_add_category(Class cls, old_category *category, int version);
186 static bool _objc_add_category_flush_caches(Class cls, old_category *category, int version);
187 static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat);
188 static void resolve_categories_for_class(Class cls);
189 static bool _objc_register_category(old_category *cat, int version);
190
191
192 // Function called when a class is loaded from an image
193 void (*callbackFunction)(Class, Category) = 0;
194
195 // Hash table of classes
196 NXHashTable * class_hash = 0;
197 static NXHashTablePrototype classHashPrototype =
198 {
199 (uintptr_t (*) (const void *, const void *)) classHash,
200 (int (*)(const void *, const void *, const void *)) classIsEqual,
201 NXNoEffectFree, 0
202 };
203
204 // Hash table of unconnected classes
205 static NXHashTable *unconnected_class_hash = nil;
206
207 // Exported copy of class_hash variable (hook for debugging tools)
208 NXHashTable *_objc_debug_class_hash = nil;
209
210 // Category and class registries
211 // Keys are COPIES of strings, to prevent stale pointers with unloaded bundles
212 // Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove
213 static NXMapTable * category_hash = nil;
214
215 // Keys are COPIES of strings, to prevent stale pointers with unloaded bundles
216 // Use NXMapKeyCopyingInsert and NXMapKeyFreeingRemove
217 static NXMapTable * pendingClassRefsMap = nil;
218 static NXMapTable * pendingSubclassesMap = nil;
219
220 // Protocols
221 static NXMapTable *protocol_map = nil; // name -> protocol
222 static NXMapTable *protocol_ext_map = nil; // protocol -> protocol ext
223
224 // Function pointer objc_getClass calls through when class is not found
225 static int (*objc_classHandler) (const char *) = _objc_defaultClassHandler;
226
227 // Function pointer called by objc_getClass and objc_lookupClass when
228 // class is not found. _objc_classLoader is called before objc_classHandler.
229 static BOOL (*_objc_classLoader)(const char *) = nil;
230
231
232 /***********************************************************************
233 * objc_dump_class_hash. Log names of all known classes.
234 **********************************************************************/
235 void objc_dump_class_hash(void)
236 {
237 NXHashTable *table;
238 unsigned count;
239 Class data;
240 NXHashState state;
241
242 table = class_hash;
243 count = 0;
244 state = NXInitHashState (table);
245 while (NXNextHashState (table, &state, (void **) &data))
246 printf ("class %d: %s\n", ++count, data->nameForLogging());
247 }
248
249
250 /***********************************************************************
251 * _objc_init_class_hash. Return the class lookup table, create it if
252 * necessary.
253 **********************************************************************/
254 void _objc_init_class_hash(void)
255 {
256 // Do nothing if class hash table already exists
257 if (class_hash)
258 return;
259
260 // class_hash starts small, with only enough capacity for libobjc itself.
261 // If a second library is found by map_images(), class_hash is immediately
262 // resized to capacity 1024 to cut down on rehashes.
263 // Old numbers: A smallish Foundation+AppKit program will have
264 // about 520 classes. Larger apps (like IB or WOB) have more like
265 // 800 classes. Some customers have massive quantities of classes.
266 // Foundation-only programs aren't likely to notice the ~6K loss.
267 class_hash = NXCreateHashTable(classHashPrototype, 16, nil);
268 _objc_debug_class_hash = class_hash;
269 }
270
271
272 /***********************************************************************
273 * objc_getClassList. Return the known classes.
274 **********************************************************************/
275 int objc_getClassList(Class *buffer, int bufferLen)
276 {
277 NXHashState state;
278 Class cls;
279 int cnt, num;
280
281 mutex_locker_t lock(classLock);
282 if (!class_hash) return 0;
283
284 num = NXCountHashTable(class_hash);
285 if (nil == buffer) return num;
286
287 cnt = 0;
288 state = NXInitHashState(class_hash);
289 while (cnt < bufferLen &&
290 NXNextHashState(class_hash, &state, (void **)&cls))
291 {
292 buffer[cnt++] = cls;
293 }
294
295 return num;
296 }
297
298
299 /***********************************************************************
300 * objc_copyClassList
301 * Returns pointers to all classes.
302 * This requires all classes be realized, which is regretfully non-lazy.
303 *
304 * outCount may be nil. *outCount is the number of classes returned.
305 * If the returned array is not nil, it is nil-terminated and must be
306 * freed with free().
307 * Locking: acquires classLock
308 **********************************************************************/
309 Class *
310 objc_copyClassList(unsigned int *outCount)
311 {
312 Class *result;
313 unsigned int count;
314
315 mutex_locker_t lock(classLock);
316 result = nil;
317 count = class_hash ? NXCountHashTable(class_hash) : 0;
318
319 if (count > 0) {
320 Class cls;
321 NXHashState state = NXInitHashState(class_hash);
322 result = (Class *)malloc((1+count) * sizeof(Class));
323 count = 0;
324 while (NXNextHashState(class_hash, &state, (void **)&cls)) {
325 result[count++] = cls;
326 }
327 result[count] = nil;
328 }
329
330 if (outCount) *outCount = count;
331 return result;
332 }
333
334
335 /***********************************************************************
336 * objc_copyProtocolList
337 * Returns pointers to all protocols.
338 * Locking: acquires classLock
339 **********************************************************************/
340 Protocol * __unsafe_unretained *
341 objc_copyProtocolList(unsigned int *outCount)
342 {
343 int count, i;
344 Protocol *proto;
345 const char *name;
346 NXMapState state;
347 Protocol **result;
348
349 mutex_locker_t lock(classLock);
350
351 count = NXCountMapTable(protocol_map);
352 if (count == 0) {
353 if (outCount) *outCount = 0;
354 return nil;
355 }
356
357 result = (Protocol **)calloc(1 + count, sizeof(Protocol *));
358
359 i = 0;
360 state = NXInitMapState(protocol_map);
361 while (NXNextMapState(protocol_map, &state,
362 (const void **)&name, (const void **)&proto))
363 {
364 result[i++] = proto;
365 }
366
367 result[i++] = nil;
368 assert(i == count+1);
369
370 if (outCount) *outCount = count;
371 return result;
372 }
373
374
375 /***********************************************************************
376 * objc_getClasses. Return class lookup table.
377 *
378 * NOTE: This function is very dangerous, since you cannot safely use
379 * the hashtable without locking it, and the lock is private!
380 **********************************************************************/
381 void *objc_getClasses(void)
382 {
383 OBJC_WARN_DEPRECATED;
384
385 // Return the class lookup hash table
386 return class_hash;
387 }
388
389
390 /***********************************************************************
391 * classHash.
392 **********************************************************************/
393 static uintptr_t classHash(void *info, Class data)
394 {
395 // Nil classes hash to zero
396 if (!data)
397 return 0;
398
399 // Call through to real hash function
400 return _objc_strhash (data->mangledName());
401 }
402
403 /***********************************************************************
404 * classIsEqual. Returns whether the class names match. If we ever
405 * check more than the name, routines like objc_lookUpClass have to
406 * change as well.
407 **********************************************************************/
408 static int classIsEqual(void *info, Class name, Class cls)
409 {
410 // Standard string comparison
411 return strcmp(name->mangledName(), cls->mangledName()) == 0;
412 }
413
414
415 // Unresolved future classes
416 static NXHashTable *future_class_hash = nil;
417
418 // Resolved future<->original classes
419 static NXMapTable *future_class_to_original_class_map = nil;
420 static NXMapTable *original_class_to_future_class_map = nil;
421
422 // CF requests about 20 future classes; HIToolbox requests one.
423 #define FUTURE_COUNT 32
424
425
426 /***********************************************************************
427 * setOriginalClassForFutureClass
428 * Record resolution of a future class.
429 **********************************************************************/
430 static void setOriginalClassForFutureClass(Class futureClass,
431 Class originalClass)
432 {
433 if (!future_class_to_original_class_map) {
434 future_class_to_original_class_map =
435 NXCreateMapTable(NXPtrValueMapPrototype, FUTURE_COUNT);
436 original_class_to_future_class_map =
437 NXCreateMapTable(NXPtrValueMapPrototype, FUTURE_COUNT);
438 }
439
440 NXMapInsert (future_class_to_original_class_map,
441 futureClass, originalClass);
442 NXMapInsert (original_class_to_future_class_map,
443 originalClass, futureClass);
444
445 if (PrintFuture) {
446 _objc_inform("FUTURE: using %p instead of %p for %s", (void*)futureClass, (void*)originalClass, originalClass->name);
447 }
448 }
449
450 /***********************************************************************
451 * getOriginalClassForFutureClass
452 * getFutureClassForOriginalClass
453 * Switch between a future class and its corresponding original class.
454 * The future class is the one actually in use.
455 * The original class is the one from disk.
456 **********************************************************************/
457 /*
458 static Class
459 getOriginalClassForFutureClass(Class futureClass)
460 {
461 if (!future_class_to_original_class_map) return Nil;
462 return NXMapGet (future_class_to_original_class_map, futureClass);
463 }
464 */
465 static Class
466 getFutureClassForOriginalClass(Class originalClass)
467 {
468 if (!original_class_to_future_class_map) return Nil;
469 return (Class)NXMapGet(original_class_to_future_class_map, originalClass);
470 }
471
472
473 /***********************************************************************
474 * makeFutureClass
475 * Initialize the memory in *cls with an unresolved future class with the
476 * given name. The memory is recorded in future_class_hash.
477 **********************************************************************/
478 static void makeFutureClass(Class cls, const char *name)
479 {
480 // CF requests about 20 future classes, plus HIToolbox has one.
481 if (!future_class_hash) {
482 future_class_hash =
483 NXCreateHashTable(classHashPrototype, FUTURE_COUNT, nil);
484 }
485
486 cls->name = strdup(name);
487 NXHashInsert(future_class_hash, cls);
488
489 if (PrintFuture) {
490 _objc_inform("FUTURE: reserving %p for %s", (void*)cls, name);
491 }
492 }
493
494
495 /***********************************************************************
496 * _objc_allocateFutureClass
497 * Allocate an unresolved future class for the given class name.
498 * Returns any existing allocation if one was already made.
499 * Assumes the named class doesn't exist yet.
500 * Not thread safe.
501 **********************************************************************/
502 Class _objc_allocateFutureClass(const char *name)
503 {
504 Class cls;
505
506 if (future_class_hash) {
507 objc_class query;
508 query.name = name;
509 if ((cls = (Class)NXHashGet(future_class_hash, &query))) {
510 // Already have a future class for this name.
511 return cls;
512 }
513 }
514
515 cls = _calloc_class(sizeof(objc_class));
516 makeFutureClass(cls, name);
517 return cls;
518 }
519
520
521 /***********************************************************************
522 * objc_getFutureClass. Return the id of the named class.
523 * If the class does not exist, return an uninitialized class
524 * structure that will be used for the class when and if it
525 * does get loaded.
526 * Not thread safe.
527 **********************************************************************/
528 Class objc_getFutureClass(const char *name)
529 {
530 Class cls;
531
532 // YES unconnected, NO class handler
533 // (unconnected is OK because it will someday be the real class)
534 cls = look_up_class(name, YES, NO);
535 if (cls) {
536 if (PrintFuture) {
537 _objc_inform("FUTURE: found %p already in use for %s",
538 (void*)cls, name);
539 }
540 return cls;
541 }
542
543 // No class or future class with that name yet. Make one.
544 // fixme not thread-safe with respect to
545 // simultaneous library load or getFutureClass.
546 return _objc_allocateFutureClass(name);
547 }
548
549
550 BOOL _class_isFutureClass(Class cls)
551 {
552 return cls && cls->isFuture();
553 }
554
555 bool objc_class::isFuture()
556 {
557 return future_class_hash && NXHashGet(future_class_hash, this);
558 }
559
560
561 /***********************************************************************
562 * _objc_defaultClassHandler. Default objc_classHandler. Does nothing.
563 **********************************************************************/
564 static int _objc_defaultClassHandler(const char *clsName)
565 {
566 // Return zero so objc_getClass doesn't bother re-searching
567 return 0;
568 }
569
570 /***********************************************************************
571 * objc_setClassHandler. Set objc_classHandler to the specified value.
572 *
573 * NOTE: This should probably deal with userSuppliedHandler being nil,
574 * because the objc_classHandler caller does not check... it would bus
575 * error. It would make sense to handle nil by restoring the default
576 * handler. Is anyone hacking with this, though?
577 **********************************************************************/
578 void objc_setClassHandler(int (*userSuppliedHandler)(const char *))
579 {
580 OBJC_WARN_DEPRECATED;
581
582 objc_classHandler = userSuppliedHandler;
583 }
584
585
586 /***********************************************************************
587 * _objc_setClassLoader
588 * Similar to objc_setClassHandler, but objc_classLoader is used for
589 * both objc_getClass() and objc_lookupClass(), and objc_classLoader
590 * pre-empts objc_classHandler.
591 **********************************************************************/
592 void _objc_setClassLoader(BOOL (*newClassLoader)(const char *))
593 {
594 _objc_classLoader = newClassLoader;
595 }
596
597
598 /***********************************************************************
599 * objc_getProtocol
600 * Get a protocol by name, or nil.
601 **********************************************************************/
602 Protocol *objc_getProtocol(const char *name)
603 {
604 mutex_locker_t lock(classLock);
605 if (!protocol_map) return nil;
606 return (Protocol *)NXMapGet(protocol_map, name);
607 }
608
609
610 /***********************************************************************
611 * look_up_class
612 * Map a class name to a class using various methods.
613 * This is the common implementation of objc_lookUpClass and objc_getClass,
614 * and is also used internally to get additional search options.
615 * Sequence:
616 * 1. class_hash
617 * 2. unconnected_class_hash (optional)
618 * 3. classLoader callback
619 * 4. classHandler callback (optional)
620 **********************************************************************/
621 Class look_up_class(const char *aClassName, bool includeUnconnected,
622 bool includeClassHandler)
623 {
624 bool includeClassLoader = YES; // class loader cannot be skipped
625 Class result = nil;
626 struct objc_class query;
627
628 query.name = aClassName;
629
630 retry:
631
632 if (!result && class_hash) {
633 // Check ordinary classes
634 mutex_locker_t lock(classLock);
635 result = (Class)NXHashGet(class_hash, &query);
636 }
637
638 if (!result && includeUnconnected && unconnected_class_hash) {
639 // Check not-yet-connected classes
640 mutex_locker_t lock(classLock);
641 result = (Class)NXHashGet(unconnected_class_hash, &query);
642 }
643
644 if (!result && includeClassLoader && _objc_classLoader) {
645 // Try class loader callback
646 if ((*_objc_classLoader)(aClassName)) {
647 // Re-try lookup without class loader
648 includeClassLoader = NO;
649 goto retry;
650 }
651 }
652
653 if (!result && includeClassHandler && objc_classHandler) {
654 // Try class handler callback
655 if ((*objc_classHandler)(aClassName)) {
656 // Re-try lookup without class handler or class loader
657 includeClassLoader = NO;
658 includeClassHandler = NO;
659 goto retry;
660 }
661 }
662
663 return result;
664 }
665
666
667 /***********************************************************************
668 * objc_class::isConnected
669 * Returns TRUE if class cls is connected.
670 * A connected class has either a connected superclass or a nil superclass,
671 * and is present in class_hash.
672 **********************************************************************/
673 bool objc_class::isConnected()
674 {
675 mutex_locker_t lock(classLock);
676 return NXHashMember(class_hash, this);
677 }
678
679
680 /***********************************************************************
681 * pendingClassRefsMapTable. Return a pointer to the lookup table for
682 * pending class refs.
683 **********************************************************************/
684 static inline NXMapTable *pendingClassRefsMapTable(void)
685 {
686 // Allocate table if needed
687 if (!pendingClassRefsMap) {
688 pendingClassRefsMap = NXCreateMapTable(NXStrValueMapPrototype, 10);
689 }
690
691 // Return table pointer
692 return pendingClassRefsMap;
693 }
694
695
696 /***********************************************************************
697 * pendingSubclassesMapTable. Return a pointer to the lookup table for
698 * pending subclasses.
699 **********************************************************************/
700 static inline NXMapTable *pendingSubclassesMapTable(void)
701 {
702 // Allocate table if needed
703 if (!pendingSubclassesMap) {
704 pendingSubclassesMap = NXCreateMapTable(NXStrValueMapPrototype, 10);
705 }
706
707 // Return table pointer
708 return pendingSubclassesMap;
709 }
710
711
712 /***********************************************************************
713 * pendClassInstallation
714 * Finish connecting class cls when its superclass becomes connected.
715 * Check for multiple pends of the same class because connect_class does not.
716 **********************************************************************/
717 static void pendClassInstallation(Class cls, const char *superName)
718 {
719 NXMapTable *table;
720 PendingSubclass *pending;
721 PendingSubclass *oldList;
722 PendingSubclass *l;
723
724 // Create and/or locate pending class lookup table
725 table = pendingSubclassesMapTable ();
726
727 // Make sure this class isn't already in the pending list.
728 oldList = (PendingSubclass *)NXMapGet(table, superName);
729 for (l = oldList; l != nil; l = l->next) {
730 if (l->subclass == cls) return; // already here, nothing to do
731 }
732
733 // Create entry referring to this class
734 pending = (PendingSubclass *)malloc(sizeof(PendingSubclass));
735 pending->subclass = cls;
736
737 // Link new entry into head of list of entries for this class
738 pending->next = oldList;
739
740 // (Re)place entry list in the table
741 NXMapKeyCopyingInsert (table, superName, pending);
742 }
743
744
745 /***********************************************************************
746 * pendClassReference
747 * Fix up a class ref when the class with the given name becomes connected.
748 **********************************************************************/
749 static void pendClassReference(Class *ref, const char *className, bool isMeta)
750 {
751 NXMapTable *table;
752 PendingClassRef *pending;
753
754 // Create and/or locate pending class lookup table
755 table = pendingClassRefsMapTable ();
756
757 // Create entry containing the class reference
758 pending = (PendingClassRef *)malloc(sizeof(PendingClassRef));
759 pending->ref = ref;
760 if (isMeta) {
761 pending->ref = (Class *)((uintptr_t)pending->ref | 1);
762 }
763
764 // Link new entry into head of list of entries for this class
765 pending->next = (PendingClassRef *)NXMapGet(table, className);
766
767 // (Re)place entry list in the table
768 NXMapKeyCopyingInsert (table, className, pending);
769
770 if (PrintConnecting) {
771 _objc_inform("CONNECT: pended reference to class '%s%s' at %p",
772 className, isMeta ? " (meta)" : "", (void *)ref);
773 }
774 }
775
776
777 /***********************************************************************
778 * resolve_references_to_class
779 * Fix up any pending class refs to this class.
780 **********************************************************************/
781 static void resolve_references_to_class(Class cls)
782 {
783 PendingClassRef *pending;
784
785 if (!pendingClassRefsMap) return; // no unresolved refs for any class
786
787 pending = (PendingClassRef *)NXMapGet(pendingClassRefsMap, cls->name);
788 if (!pending) return; // no unresolved refs for this class
789
790 NXMapKeyFreeingRemove(pendingClassRefsMap, cls->name);
791
792 if (PrintConnecting) {
793 _objc_inform("CONNECT: resolving references to class '%s'", cls->name);
794 }
795
796 while (pending) {
797 PendingClassRef *next = pending->next;
798 if (pending->ref) {
799 bool isMeta = (uintptr_t)pending->ref & 1;
800 Class *ref =
801 (Class *)((uintptr_t)pending->ref & ~(uintptr_t)1);
802 *ref = isMeta ? cls->ISA() : cls;
803 }
804 free(pending);
805 pending = next;
806 }
807
808 if (NXCountMapTable(pendingClassRefsMap) == 0) {
809 NXFreeMapTable(pendingClassRefsMap);
810 pendingClassRefsMap = nil;
811 }
812 }
813
814
815 /***********************************************************************
816 * resolve_subclasses_of_class
817 * Fix up any pending subclasses of this class.
818 **********************************************************************/
819 static void resolve_subclasses_of_class(Class cls)
820 {
821 PendingSubclass *pending;
822
823 if (!pendingSubclassesMap) return; // no unresolved subclasses
824
825 pending = (PendingSubclass *)NXMapGet(pendingSubclassesMap, cls->name);
826 if (!pending) return; // no unresolved subclasses for this class
827
828 NXMapKeyFreeingRemove(pendingSubclassesMap, cls->name);
829
830 // Destroy the pending table if it's now empty, to save memory.
831 if (NXCountMapTable(pendingSubclassesMap) == 0) {
832 NXFreeMapTable(pendingSubclassesMap);
833 pendingSubclassesMap = nil;
834 }
835
836 if (PrintConnecting) {
837 _objc_inform("CONNECT: resolving subclasses of class '%s'", cls->name);
838 }
839
840 while (pending) {
841 PendingSubclass *next = pending->next;
842 if (pending->subclass) connect_class(pending->subclass);
843 free(pending);
844 pending = next;
845 }
846 }
847
848
849 /***********************************************************************
850 * really_connect_class
851 * Connect cls to superclass supercls unconditionally.
852 * Also adjust the class hash tables and handle pended subclasses.
853 *
854 * This should be called from connect_class() ONLY.
855 **********************************************************************/
856 static void really_connect_class(Class cls,
857 Class supercls)
858 {
859 Class oldCls;
860
861 // Connect superclass pointers.
862 set_superclass(cls, supercls, YES);
863
864 // Update GC layouts
865 // For paranoia, this is a conservative update:
866 // only non-strong -> strong and weak -> strong are corrected.
867 if (UseGC && supercls &&
868 (cls->info & CLS_EXT) && (supercls->info & CLS_EXT))
869 {
870 bool layoutChanged;
871 layout_bitmap ivarBitmap =
872 layout_bitmap_create(cls->ivar_layout,
873 cls->instance_size,
874 cls->instance_size, NO);
875
876 layout_bitmap superBitmap =
877 layout_bitmap_create(supercls->ivar_layout,
878 supercls->instance_size,
879 supercls->instance_size, NO);
880
881 // non-strong -> strong: bits set in super should be set in sub
882 layoutChanged = layout_bitmap_or(ivarBitmap, superBitmap, cls->name);
883 layout_bitmap_free(superBitmap);
884
885 if (layoutChanged) {
886 layout_bitmap weakBitmap = {};
887 bool weakLayoutChanged = NO;
888
889 if (cls->ext && cls->ext->weak_ivar_layout) {
890 // weak -> strong: strong bits should be cleared in weak layout
891 // This is a subset of non-strong -> strong
892 weakBitmap =
893 layout_bitmap_create(cls->ext->weak_ivar_layout,
894 cls->instance_size,
895 cls->instance_size, YES);
896
897 weakLayoutChanged =
898 layout_bitmap_clear(weakBitmap, ivarBitmap, cls->name);
899 } else {
900 // no existing weak ivars, so no weak -> strong changes
901 }
902
903 // Rebuild layout strings.
904 if (PrintIvars) {
905 _objc_inform("IVARS: gc layout changed "
906 "for class %s (super %s)",
907 cls->name, supercls->name);
908 if (weakLayoutChanged) {
909 _objc_inform("IVARS: gc weak layout changed "
910 "for class %s (super %s)",
911 cls->name, supercls->name);
912 }
913 }
914 cls->ivar_layout = layout_string_create(ivarBitmap);
915 if (weakLayoutChanged) {
916 cls->ext->weak_ivar_layout = layout_string_create(weakBitmap);
917 }
918
919 layout_bitmap_free(weakBitmap);
920 }
921
922 layout_bitmap_free(ivarBitmap);
923 }
924
925 // Done!
926 cls->info |= CLS_CONNECTED;
927
928 {
929 mutex_locker_t lock(classLock);
930
931 // Update hash tables.
932 NXHashRemove(unconnected_class_hash, cls);
933 oldCls = (Class)NXHashInsert(class_hash, cls);
934 objc_addRegisteredClass(cls);
935
936 // Delete unconnected_class_hash if it is now empty.
937 if (NXCountHashTable(unconnected_class_hash) == 0) {
938 NXFreeHashTable(unconnected_class_hash);
939 unconnected_class_hash = nil;
940 }
941
942 // No duplicate classes allowed.
943 // Duplicates should have been rejected by _objc_read_classes_from_image
944 assert(!oldCls);
945 }
946
947 // Fix up pended class refs to this class, if any
948 resolve_references_to_class(cls);
949
950 // Connect newly-connectable subclasses
951 resolve_subclasses_of_class(cls);
952
953 // GC debugging: make sure all classes with -dealloc also have -finalize
954 if (DebugFinalizers) {
955 extern IMP findIMPInClass(Class cls, SEL sel);
956 if (findIMPInClass(cls, sel_getUid("dealloc")) &&
957 ! findIMPInClass(cls, sel_getUid("finalize")))
958 {
959 _objc_inform("GC: class '%s' implements -dealloc but not -finalize", cls->name);
960 }
961 }
962
963 // Debugging: if this class has ivars, make sure this class's ivars don't
964 // overlap with its super's. This catches some broken fragile base classes.
965 // Do not use super->instance_size vs. self->ivar[0] to check this.
966 // Ivars may be packed across instance_size boundaries.
967 if (DebugFragileSuperclasses && cls->ivars && cls->ivars->ivar_count) {
968 Class ivar_cls = supercls;
969
970 // Find closest superclass that has some ivars, if one exists.
971 while (ivar_cls &&
972 (!ivar_cls->ivars || ivar_cls->ivars->ivar_count == 0))
973 {
974 ivar_cls = ivar_cls->superclass;
975 }
976
977 if (ivar_cls) {
978 // Compare superclass's last ivar to this class's first ivar
979 old_ivar *super_ivar =
980 &ivar_cls->ivars->ivar_list[ivar_cls->ivars->ivar_count - 1];
981 old_ivar *self_ivar =
982 &cls->ivars->ivar_list[0];
983
984 // fixme could be smarter about super's ivar size
985 if (self_ivar->ivar_offset <= super_ivar->ivar_offset) {
986 _objc_inform("WARNING: ivars of superclass '%s' and "
987 "subclass '%s' overlap; superclass may have "
988 "changed since subclass was compiled",
989 ivar_cls->name, cls->name);
990 }
991 }
992 }
993 }
994
995
996 /***********************************************************************
997 * connect_class
998 * Connect class cls to its superclasses, if possible.
999 * If cls becomes connected, move it from unconnected_class_hash
1000 * to connected_class_hash.
1001 * Returns TRUE if cls is connected.
1002 * Returns FALSE if cls could not be connected for some reason
1003 * (missing superclass or still-unconnected superclass)
1004 **********************************************************************/
1005 static bool connect_class(Class cls)
1006 {
1007 if (cls->isConnected()) {
1008 // This class is already connected to its superclass.
1009 // Do nothing.
1010 return TRUE;
1011 }
1012 else if (cls->superclass == nil) {
1013 // This class is a root class.
1014 // Connect it to itself.
1015
1016 if (PrintConnecting) {
1017 _objc_inform("CONNECT: class '%s' now connected (root class)",
1018 cls->name);
1019 }
1020
1021 really_connect_class(cls, nil);
1022 return TRUE;
1023 }
1024 else {
1025 // This class is not a root class and is not yet connected.
1026 // Connect it if its superclass and root class are already connected.
1027 // Otherwise, add this class to the to-be-connected list,
1028 // pending the completion of its superclass and root class.
1029
1030 // At this point, cls->superclass and cls->ISA()->ISA() are still STRINGS
1031 char *supercls_name = (char *)cls->superclass;
1032 Class supercls;
1033
1034 // YES unconnected, YES class handler
1035 if (nil == (supercls = look_up_class(supercls_name, YES, YES))) {
1036 // Superclass does not exist yet.
1037 // pendClassInstallation will handle duplicate pends of this class
1038 pendClassInstallation(cls, supercls_name);
1039
1040 if (PrintConnecting) {
1041 _objc_inform("CONNECT: class '%s' NOT connected (missing super)", cls->name);
1042 }
1043 return FALSE;
1044 }
1045
1046 if (! connect_class(supercls)) {
1047 // Superclass exists but is not yet connected.
1048 // pendClassInstallation will handle duplicate pends of this class
1049 pendClassInstallation(cls, supercls_name);
1050
1051 if (PrintConnecting) {
1052 _objc_inform("CONNECT: class '%s' NOT connected (unconnected super)", cls->name);
1053 }
1054 return FALSE;
1055 }
1056
1057 // Superclass exists and is connected.
1058 // Connect this class to the superclass.
1059
1060 if (PrintConnecting) {
1061 _objc_inform("CONNECT: class '%s' now connected", cls->name);
1062 }
1063
1064 really_connect_class(cls, supercls);
1065 return TRUE;
1066 }
1067 }
1068
1069
1070 /***********************************************************************
1071 * _objc_read_categories_from_image.
1072 * Read all categories from the given image.
1073 * Install them on their parent classes, or register them for later
1074 * installation.
1075 * Returns YES if some method caches now need to be flushed.
1076 **********************************************************************/
1077 static bool _objc_read_categories_from_image (header_info * hi)
1078 {
1079 Module mods;
1080 size_t midx;
1081 bool needFlush = NO;
1082
1083 if (_objcHeaderIsReplacement(hi)) {
1084 // Ignore any categories in this image
1085 return NO;
1086 }
1087
1088
1089 // Major loop - process all modules in the header
1090 mods = hi->mod_ptr;
1091
1092 // NOTE: The module and category lists are traversed backwards
1093 // to preserve the pre-10.4 processing order. Changing the order
1094 // would have a small chance of introducing binary compatibility bugs.
1095 midx = hi->mod_count;
1096 while (midx-- > 0) {
1097 unsigned int index;
1098 unsigned int total;
1099
1100 // Nothing to do for a module without a symbol table
1101 if (mods[midx].symtab == nil)
1102 continue;
1103
1104 // Total entries in symbol table (class entries followed
1105 // by category entries)
1106 total = mods[midx].symtab->cls_def_cnt +
1107 mods[midx].symtab->cat_def_cnt;
1108
1109 // Minor loop - register all categories from given module
1110 index = total;
1111 while (index-- > mods[midx].symtab->cls_def_cnt) {
1112 old_category *cat = (old_category *)mods[midx].symtab->defs[index];
1113 needFlush |= _objc_register_category(cat, (int)mods[midx].version);
1114 }
1115 }
1116
1117 return needFlush;
1118 }
1119
1120
1121 /***********************************************************************
1122 * _objc_read_classes_from_image.
1123 * Read classes from the given image, perform assorted minor fixups,
1124 * scan for +load implementation.
1125 * Does not connect classes to superclasses.
1126 * Does attach pended categories to the classes.
1127 * Adds all classes to unconnected_class_hash. class_hash is unchanged.
1128 **********************************************************************/
1129 static void _objc_read_classes_from_image(header_info *hi)
1130 {
1131 unsigned int index;
1132 unsigned int midx;
1133 Module mods;
1134 int isBundle = headerIsBundle(hi);
1135
1136 if (_objcHeaderIsReplacement(hi)) {
1137 // Ignore any classes in this image
1138 return;
1139 }
1140
1141 // class_hash starts small, enough only for libobjc itself.
1142 // If other Objective-C libraries are found, immediately resize
1143 // class_hash, assuming that Foundation and AppKit are about
1144 // to add lots of classes.
1145 {
1146 mutex_locker_t lock(classLock);
1147 if (hi->mhdr != libobjc_header && _NXHashCapacity(class_hash) < 1024) {
1148 _NXHashRehashToCapacity(class_hash, 1024);
1149 }
1150 }
1151
1152 // Major loop - process all modules in the image
1153 mods = hi->mod_ptr;
1154 for (midx = 0; midx < hi->mod_count; midx += 1)
1155 {
1156 // Skip module containing no classes
1157 if (mods[midx].symtab == nil)
1158 continue;
1159
1160 // Minor loop - process all the classes in given module
1161 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
1162 {
1163 Class newCls, oldCls;
1164 bool rejected;
1165
1166 // Locate the class description pointer
1167 newCls = (Class)mods[midx].symtab->defs[index];
1168
1169 // Classes loaded from Mach-O bundles can be unloaded later.
1170 // Nothing uses this class yet, so cls->setInfo is not needed.
1171 if (isBundle) newCls->info |= CLS_FROM_BUNDLE;
1172 if (isBundle) newCls->ISA()->info |= CLS_FROM_BUNDLE;
1173
1174 // Use common static empty cache instead of nil
1175 if (newCls->cache == nil)
1176 newCls->cache = (Cache) &_objc_empty_cache;
1177 if (newCls->ISA()->cache == nil)
1178 newCls->ISA()->cache = (Cache) &_objc_empty_cache;
1179
1180 // Set metaclass version
1181 newCls->ISA()->version = mods[midx].version;
1182
1183 // methodLists is nil or a single list, not an array
1184 newCls->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY;
1185 newCls->ISA()->info |= CLS_NO_METHOD_ARRAY|CLS_NO_PROPERTY_ARRAY;
1186
1187 // class has no subclasses for cache flushing
1188 newCls->info |= CLS_LEAF;
1189 newCls->ISA()->info |= CLS_LEAF;
1190
1191 if (mods[midx].version >= 6) {
1192 // class structure has ivar_layout and ext fields
1193 newCls->info |= CLS_EXT;
1194 newCls->ISA()->info |= CLS_EXT;
1195 }
1196
1197 // Check for +load implementation before categories are attached
1198 if (_class_hasLoadMethod(newCls)) {
1199 newCls->ISA()->info |= CLS_HAS_LOAD_METHOD;
1200 }
1201
1202 // Install into unconnected_class_hash.
1203 {
1204 mutex_locker_t lock(classLock);
1205
1206 if (future_class_hash) {
1207 Class futureCls = (Class)
1208 NXHashRemove(future_class_hash, newCls);
1209 if (futureCls) {
1210 // Another class structure for this class was already
1211 // prepared by objc_getFutureClass(). Use it instead.
1212 free((char *)futureCls->name);
1213 memcpy(futureCls, newCls, sizeof(objc_class));
1214 setOriginalClassForFutureClass(futureCls, newCls);
1215 newCls = futureCls;
1216
1217 if (NXCountHashTable(future_class_hash) == 0) {
1218 NXFreeHashTable(future_class_hash);
1219 future_class_hash = nil;
1220 }
1221 }
1222 }
1223
1224 if (!unconnected_class_hash) {
1225 unconnected_class_hash =
1226 NXCreateHashTable(classHashPrototype, 128, nil);
1227 }
1228
1229 if ((oldCls = (Class)NXHashGet(class_hash, newCls)) ||
1230 (oldCls = (Class)NXHashGet(unconnected_class_hash, newCls)))
1231 {
1232 // Another class with this name exists. Complain and reject.
1233 inform_duplicate(newCls->name, oldCls, newCls);
1234 rejected = YES;
1235 }
1236 else {
1237 NXHashInsert(unconnected_class_hash, newCls);
1238 rejected = NO;
1239 }
1240 }
1241
1242 if (!rejected) {
1243 // Attach pended categories for this class, if any
1244 resolve_categories_for_class(newCls);
1245 }
1246 }
1247 }
1248 }
1249
1250
1251 /***********************************************************************
1252 * _objc_connect_classes_from_image.
1253 * Connect the classes in the given image to their superclasses,
1254 * or register them for later connection if any superclasses are missing.
1255 **********************************************************************/
1256 static void _objc_connect_classes_from_image(header_info *hi)
1257 {
1258 unsigned int index;
1259 unsigned int midx;
1260 Module mods;
1261 bool replacement = _objcHeaderIsReplacement(hi);
1262
1263 // Major loop - process all modules in the image
1264 mods = hi->mod_ptr;
1265 for (midx = 0; midx < hi->mod_count; midx += 1)
1266 {
1267 // Skip module containing no classes
1268 if (mods[midx].symtab == nil)
1269 continue;
1270
1271 // Minor loop - process all the classes in given module
1272 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
1273 {
1274 Class cls = (Class)mods[midx].symtab->defs[index];
1275 if (! replacement) {
1276 bool connected;
1277 Class futureCls = getFutureClassForOriginalClass(cls);
1278 if (futureCls) {
1279 // objc_getFutureClass() requested a different class
1280 // struct. Fix up the original struct's superclass
1281 // field for [super ...] use, but otherwise perform
1282 // fixups on the new class struct only.
1283 const char *super_name = (const char *) cls->superclass;
1284 if (super_name) cls->superclass = objc_getClass(super_name);
1285 cls = futureCls;
1286 }
1287 connected = connect_class(cls);
1288 if (connected && callbackFunction) {
1289 (*callbackFunction)(cls, 0);
1290 }
1291 } else {
1292 // Replacement image - fix up superclass only (#3704817)
1293 // And metaclass's superclass (#5351107)
1294 const char *super_name = (const char *) cls->superclass;
1295 if (super_name) {
1296 cls->superclass = objc_getClass(super_name);
1297 // metaclass's superclass is superclass's metaclass
1298 cls->ISA()->superclass = cls->superclass->ISA();
1299 } else {
1300 // Replacement for a root class
1301 // cls->superclass already nil
1302 // root metaclass's superclass is root class
1303 cls->ISA()->superclass = cls;
1304 }
1305 }
1306 }
1307 }
1308 }
1309
1310
1311 /***********************************************************************
1312 * _objc_map_class_refs_for_image. Convert the class ref entries from
1313 * a class name string pointer to a class pointer. If the class does
1314 * not yet exist, the reference is added to a list of pending references
1315 * to be fixed up at a later date.
1316 **********************************************************************/
1317 static void fix_class_ref(Class *ref, const char *name, bool isMeta)
1318 {
1319 Class cls;
1320
1321 // Get pointer to class of this name
1322 // NO unconnected, YES class loader
1323 // (real class with weak-missing superclass is unconnected now)
1324 cls = look_up_class(name, NO, YES);
1325 if (cls) {
1326 // Referenced class exists. Fix up the reference.
1327 *ref = isMeta ? cls->ISA() : cls;
1328 } else {
1329 // Referenced class does not exist yet. Insert nil for now
1330 // (weak-linking) and fix up the reference if the class arrives later.
1331 pendClassReference (ref, name, isMeta);
1332 *ref = nil;
1333 }
1334 }
1335
1336 static void _objc_map_class_refs_for_image (header_info * hi)
1337 {
1338 Class *cls_refs;
1339 size_t count;
1340 unsigned int index;
1341
1342 // Locate class refs in image
1343 cls_refs = _getObjcClassRefs (hi, &count);
1344 if (cls_refs) {
1345 // Process each class ref
1346 for (index = 0; index < count; index += 1) {
1347 // Ref is initially class name char*
1348 const char *name = (const char *) cls_refs[index];
1349 if (!name) continue;
1350 fix_class_ref(&cls_refs[index], name, NO /*never meta*/);
1351 }
1352 }
1353 }
1354
1355
1356 /***********************************************************************
1357 * _objc_remove_pending_class_refs_in_image
1358 * Delete any pending class ref fixups for class refs in the given image,
1359 * because the image is about to be unloaded.
1360 **********************************************************************/
1361 static void removePendingReferences(Class *refs, size_t count)
1362 {
1363 Class *end = refs + count;
1364
1365 if (!refs) return;
1366 if (!pendingClassRefsMap) return;
1367
1368 // Search the pending class ref table for class refs in this range.
1369 // The class refs may have already been stomped with nil,
1370 // so there's no way to recover the original class name.
1371
1372 {
1373 const char *key;
1374 PendingClassRef *pending;
1375 NXMapState state = NXInitMapState(pendingClassRefsMap);
1376 while(NXNextMapState(pendingClassRefsMap, &state,
1377 (const void **)&key, (const void **)&pending))
1378 {
1379 for ( ; pending != nil; pending = pending->next) {
1380 if (pending->ref >= refs && pending->ref < end) {
1381 pending->ref = nil;
1382 }
1383 }
1384 }
1385 }
1386 }
1387
1388 static void _objc_remove_pending_class_refs_in_image(header_info *hi)
1389 {
1390 Class *cls_refs;
1391 size_t count;
1392
1393 // Locate class refs in this image
1394 cls_refs = _getObjcClassRefs(hi, &count);
1395 removePendingReferences(cls_refs, count);
1396 }
1397
1398
1399 /***********************************************************************
1400 * map_selrefs. For each selector in the specified array,
1401 * replace the name pointer with a uniqued selector.
1402 * If copy is TRUE, all selector data is always copied. This is used
1403 * for registering selectors from unloadable bundles, so the selector
1404 * can still be used after the bundle's data segment is unmapped.
1405 * Returns YES if dst was written to, NO if it was unchanged.
1406 **********************************************************************/
1407 static inline void map_selrefs(SEL *sels, size_t count, bool copy)
1408 {
1409 size_t index;
1410
1411 if (!sels) return;
1412
1413 sel_lock();
1414
1415 // Process each selector
1416 for (index = 0; index < count; index += 1)
1417 {
1418 SEL sel;
1419
1420 // Lookup pointer to uniqued string
1421 sel = sel_registerNameNoLock((const char *) sels[index], copy);
1422
1423 // Replace this selector with uniqued one (avoid
1424 // modifying the VM page if this would be a NOP)
1425 if (sels[index] != sel) {
1426 sels[index] = sel;
1427 }
1428 }
1429
1430 sel_unlock();
1431 }
1432
1433
1434 /***********************************************************************
1435 * map_method_descs. For each method in the specified method list,
1436 * replace the name pointer with a uniqued selector.
1437 * If copy is TRUE, all selector data is always copied. This is used
1438 * for registering selectors from unloadable bundles, so the selector
1439 * can still be used after the bundle's data segment is unmapped.
1440 **********************************************************************/
1441 static void map_method_descs (struct objc_method_description_list * methods, bool copy)
1442 {
1443 int index;
1444
1445 if (!methods) return;
1446
1447 sel_lock();
1448
1449 // Process each method
1450 for (index = 0; index < methods->count; index += 1)
1451 {
1452 struct objc_method_description * method;
1453 SEL sel;
1454
1455 // Get method entry to fix up
1456 method = &methods->list[index];
1457
1458 // Lookup pointer to uniqued string
1459 sel = sel_registerNameNoLock((const char *) method->name, copy);
1460
1461 // Replace this selector with uniqued one (avoid
1462 // modifying the VM page if this would be a NOP)
1463 if (method->name != sel)
1464 method->name = sel;
1465 }
1466
1467 sel_unlock();
1468 }
1469
1470
1471 /***********************************************************************
1472 * ext_for_protocol
1473 * Returns the protocol extension for the given protocol.
1474 * Returns nil if the protocol has no extension.
1475 **********************************************************************/
1476 static old_protocol_ext *ext_for_protocol(old_protocol *proto)
1477 {
1478 if (!proto) return nil;
1479 if (!protocol_ext_map) return nil;
1480 else return (old_protocol_ext *)NXMapGet(protocol_ext_map, proto);
1481 }
1482
1483
1484 /***********************************************************************
1485 * lookup_method
1486 * Search a protocol method list for a selector.
1487 **********************************************************************/
1488 static struct objc_method_description *
1489 lookup_method(struct objc_method_description_list *mlist, SEL aSel)
1490 {
1491 if (mlist) {
1492 int i;
1493 for (i = 0; i < mlist->count; i++) {
1494 if (mlist->list[i].name == aSel) {
1495 return mlist->list+i;
1496 }
1497 }
1498 }
1499 return nil;
1500 }
1501
1502
1503 /***********************************************************************
1504 * lookup_protocol_method
1505 * Search for a selector in a protocol
1506 * (and optionally recursively all incorporated protocols)
1507 **********************************************************************/
1508 struct objc_method_description *
1509 lookup_protocol_method(old_protocol *proto, SEL aSel,
1510 bool isRequiredMethod, bool isInstanceMethod,
1511 bool recursive)
1512 {
1513 struct objc_method_description *m = nil;
1514 old_protocol_ext *ext;
1515
1516 if (isRequiredMethod) {
1517 if (isInstanceMethod) {
1518 m = lookup_method(proto->instance_methods, aSel);
1519 } else {
1520 m = lookup_method(proto->class_methods, aSel);
1521 }
1522 } else if ((ext = ext_for_protocol(proto))) {
1523 if (isInstanceMethod) {
1524 m = lookup_method(ext->optional_instance_methods, aSel);
1525 } else {
1526 m = lookup_method(ext->optional_class_methods, aSel);
1527 }
1528 }
1529
1530 if (!m && recursive && proto->protocol_list) {
1531 int i;
1532 for (i = 0; !m && i < proto->protocol_list->count; i++) {
1533 m = lookup_protocol_method(proto->protocol_list->list[i], aSel,
1534 isRequiredMethod,isInstanceMethod,true);
1535 }
1536 }
1537
1538 return m;
1539 }
1540
1541
1542 /***********************************************************************
1543 * protocol_getName
1544 * Returns the name of the given protocol.
1545 **********************************************************************/
1546 const char *protocol_getName(Protocol *p)
1547 {
1548 old_protocol *proto = oldprotocol(p);
1549 if (!proto) return "nil";
1550 return proto->protocol_name;
1551 }
1552
1553
1554 /***********************************************************************
1555 * protocol_getMethodDescription
1556 * Returns the description of a named method.
1557 * Searches either required or optional methods.
1558 * Searches either instance or class methods.
1559 **********************************************************************/
1560 struct objc_method_description
1561 protocol_getMethodDescription(Protocol *p, SEL aSel,
1562 BOOL isRequiredMethod, BOOL isInstanceMethod)
1563 {
1564 struct objc_method_description empty = {nil, nil};
1565 old_protocol *proto = oldprotocol(p);
1566 struct objc_method_description *desc;
1567 if (!proto) return empty;
1568
1569 desc = lookup_protocol_method(proto, aSel,
1570 isRequiredMethod, isInstanceMethod, true);
1571 if (desc) return *desc;
1572 else return empty;
1573 }
1574
1575
1576 /***********************************************************************
1577 * protocol_copyMethodDescriptionList
1578 * Returns an array of method descriptions from a protocol.
1579 * Copies either required or optional methods.
1580 * Copies either instance or class methods.
1581 **********************************************************************/
1582 struct objc_method_description *
1583 protocol_copyMethodDescriptionList(Protocol *p,
1584 BOOL isRequiredMethod,
1585 BOOL isInstanceMethod,
1586 unsigned int *outCount)
1587 {
1588 struct objc_method_description_list *mlist = nil;
1589 old_protocol *proto = oldprotocol(p);
1590 old_protocol_ext *ext;
1591 unsigned int i, count;
1592 struct objc_method_description *result;
1593
1594 if (!proto) {
1595 if (outCount) *outCount = 0;
1596 return nil;
1597 }
1598
1599 if (isRequiredMethod) {
1600 if (isInstanceMethod) {
1601 mlist = proto->instance_methods;
1602 } else {
1603 mlist = proto->class_methods;
1604 }
1605 } else if ((ext = ext_for_protocol(proto))) {
1606 if (isInstanceMethod) {
1607 mlist = ext->optional_instance_methods;
1608 } else {
1609 mlist = ext->optional_class_methods;
1610 }
1611 }
1612
1613 if (!mlist) {
1614 if (outCount) *outCount = 0;
1615 return nil;
1616 }
1617
1618 count = mlist->count;
1619 result = (struct objc_method_description *)
1620 calloc(count + 1, sizeof(struct objc_method_description));
1621 for (i = 0; i < count; i++) {
1622 result[i] = mlist->list[i];
1623 }
1624
1625 if (outCount) *outCount = count;
1626 return result;
1627 }
1628
1629
1630 objc_property_t protocol_getProperty(Protocol *p, const char *name,
1631 BOOL isRequiredProperty, BOOL isInstanceProperty)
1632 {
1633 old_protocol *proto = oldprotocol(p);
1634 old_protocol_ext *ext;
1635 old_protocol_list *proto_list;
1636
1637 if (!proto || !name) return nil;
1638
1639 if (!isRequiredProperty || !isInstanceProperty) {
1640 // Only required instance properties are currently supported
1641 return nil;
1642 }
1643
1644 if ((ext = ext_for_protocol(proto))) {
1645 old_property_list *plist;
1646 if ((plist = ext->instance_properties)) {
1647 uint32_t i;
1648 for (i = 0; i < plist->count; i++) {
1649 old_property *prop = property_list_nth(plist, i);
1650 if (0 == strcmp(name, prop->name)) {
1651 return (objc_property_t)prop;
1652 }
1653 }
1654 }
1655 }
1656
1657 if ((proto_list = proto->protocol_list)) {
1658 int i;
1659 for (i = 0; i < proto_list->count; i++) {
1660 objc_property_t prop =
1661 protocol_getProperty((Protocol *)proto_list->list[i], name,
1662 isRequiredProperty, isInstanceProperty);
1663 if (prop) return prop;
1664 }
1665 }
1666
1667 return nil;
1668 }
1669
1670
1671 objc_property_t *protocol_copyPropertyList(Protocol *p, unsigned int *outCount)
1672 {
1673 old_property **result = nil;
1674 old_protocol_ext *ext;
1675 old_property_list *plist;
1676
1677 old_protocol *proto = oldprotocol(p);
1678 if (! (ext = ext_for_protocol(proto))) {
1679 if (outCount) *outCount = 0;
1680 return nil;
1681 }
1682
1683 plist = ext->instance_properties;
1684 result = copyPropertyList(plist, outCount);
1685
1686 return (objc_property_t *)result;
1687 }
1688
1689
1690 /***********************************************************************
1691 * protocol_copyProtocolList
1692 * Copies this protocol's incorporated protocols.
1693 * Does not copy those protocol's incorporated protocols in turn.
1694 **********************************************************************/
1695 Protocol * __unsafe_unretained *
1696 protocol_copyProtocolList(Protocol *p, unsigned int *outCount)
1697 {
1698 unsigned int count = 0;
1699 Protocol **result = nil;
1700 old_protocol *proto = oldprotocol(p);
1701
1702 if (!proto) {
1703 if (outCount) *outCount = 0;
1704 return nil;
1705 }
1706
1707 if (proto->protocol_list) {
1708 count = (unsigned int)proto->protocol_list->count;
1709 }
1710 if (count > 0) {
1711 unsigned int i;
1712 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
1713
1714 for (i = 0; i < count; i++) {
1715 result[i] = (Protocol *)proto->protocol_list->list[i];
1716 }
1717 result[i] = nil;
1718 }
1719
1720 if (outCount) *outCount = count;
1721 return result;
1722 }
1723
1724
1725 BOOL protocol_conformsToProtocol(Protocol *self_gen, Protocol *other_gen)
1726 {
1727 old_protocol *self = oldprotocol(self_gen);
1728 old_protocol *other = oldprotocol(other_gen);
1729
1730 if (!self || !other) {
1731 return NO;
1732 }
1733
1734 if (0 == strcmp(self->protocol_name, other->protocol_name)) {
1735 return YES;
1736 }
1737
1738 if (self->protocol_list) {
1739 int i;
1740 for (i = 0; i < self->protocol_list->count; i++) {
1741 old_protocol *proto = self->protocol_list->list[i];
1742 if (0 == strcmp(other->protocol_name, proto->protocol_name)) {
1743 return YES;
1744 }
1745 if (protocol_conformsToProtocol((Protocol *)proto, other_gen)) {
1746 return YES;
1747 }
1748 }
1749 }
1750
1751 return NO;
1752 }
1753
1754
1755 BOOL protocol_isEqual(Protocol *self, Protocol *other)
1756 {
1757 if (self == other) return YES;
1758 if (!self || !other) return NO;
1759
1760 if (!protocol_conformsToProtocol(self, other)) return NO;
1761 if (!protocol_conformsToProtocol(other, self)) return NO;
1762
1763 return YES;
1764 }
1765
1766
1767 /***********************************************************************
1768 * _protocol_getMethodTypeEncoding
1769 * Return the @encode string for the requested protocol method.
1770 * Returns nil if the compiler did not emit any extended @encode data.
1771 * Locking: runtimeLock must not be held by the caller
1772 **********************************************************************/
1773 const char *
1774 _protocol_getMethodTypeEncoding(Protocol *proto_gen, SEL sel,
1775 BOOL isRequiredMethod, BOOL isInstanceMethod)
1776 {
1777 old_protocol *proto = oldprotocol(proto_gen);
1778 if (!proto) return nil;
1779 old_protocol_ext *ext = ext_for_protocol(proto);
1780 if (!ext) return nil;
1781 if (ext->size < offsetof(old_protocol_ext, extendedMethodTypes) + sizeof(ext->extendedMethodTypes)) return nil;
1782 if (! ext->extendedMethodTypes) return nil;
1783
1784 struct objc_method_description *m =
1785 lookup_protocol_method(proto, sel,
1786 isRequiredMethod, isInstanceMethod, false);
1787 if (!m) {
1788 // No method with that name. Search incorporated protocols.
1789 if (proto->protocol_list) {
1790 for (int i = 0; i < proto->protocol_list->count; i++) {
1791 const char *enc =
1792 _protocol_getMethodTypeEncoding((Protocol *)proto->protocol_list->list[i], sel, isRequiredMethod, isInstanceMethod);
1793 if (enc) return enc;
1794 }
1795 }
1796 return nil;
1797 }
1798
1799 int i = 0;
1800 if (isRequiredMethod && isInstanceMethod) {
1801 i += ((uintptr_t)m - (uintptr_t)proto->instance_methods) / sizeof(proto->instance_methods->list[0]);
1802 goto done;
1803 } else if (proto->instance_methods) {
1804 i += proto->instance_methods->count;
1805 }
1806
1807 if (isRequiredMethod && !isInstanceMethod) {
1808 i += ((uintptr_t)m - (uintptr_t)proto->class_methods) / sizeof(proto->class_methods->list[0]);
1809 goto done;
1810 } else if (proto->class_methods) {
1811 i += proto->class_methods->count;
1812 }
1813
1814 if (!isRequiredMethod && isInstanceMethod) {
1815 i += ((uintptr_t)m - (uintptr_t)ext->optional_instance_methods) / sizeof(ext->optional_instance_methods->list[0]);
1816 goto done;
1817 } else if (ext->optional_instance_methods) {
1818 i += ext->optional_instance_methods->count;
1819 }
1820
1821 if (!isRequiredMethod && !isInstanceMethod) {
1822 i += ((uintptr_t)m - (uintptr_t)ext->optional_class_methods) / sizeof(ext->optional_class_methods->list[0]);
1823 goto done;
1824 } else if (ext->optional_class_methods) {
1825 i += ext->optional_class_methods->count;
1826 }
1827
1828 done:
1829 return ext->extendedMethodTypes[i];
1830 }
1831
1832
1833 /***********************************************************************
1834 * objc_allocateProtocol
1835 * Creates a new protocol. The protocol may not be used until
1836 * objc_registerProtocol() is called.
1837 * Returns nil if a protocol with the same name already exists.
1838 * Locking: acquires classLock
1839 **********************************************************************/
1840 Protocol *
1841 objc_allocateProtocol(const char *name)
1842 {
1843 Class cls = objc_getClass("__IncompleteProtocol");
1844
1845 mutex_locker_t lock(classLock);
1846
1847 if (NXMapGet(protocol_map, name)) return nil;
1848
1849 old_protocol *result = (old_protocol *)
1850 calloc(1, sizeof(old_protocol)
1851 + sizeof(old_protocol_ext));
1852 old_protocol_ext *ext = (old_protocol_ext *)(result+1);
1853
1854 result->isa = cls;
1855 result->protocol_name = strdup(name);
1856 ext->size = sizeof(old_protocol_ext);
1857
1858 // fixme reserve name without installing
1859
1860 NXMapInsert(protocol_ext_map, result, result+1);
1861
1862 return (Protocol *)result;
1863 }
1864
1865
1866 /***********************************************************************
1867 * objc_registerProtocol
1868 * Registers a newly-constructed protocol. The protocol is now
1869 * ready for use and immutable.
1870 * Locking: acquires classLock
1871 **********************************************************************/
1872 void objc_registerProtocol(Protocol *proto_gen)
1873 {
1874 old_protocol *proto = oldprotocol(proto_gen);
1875
1876 Class oldcls = objc_getClass("__IncompleteProtocol");
1877 Class cls = objc_getClass("Protocol");
1878
1879 mutex_locker_t lock(classLock);
1880
1881 if (proto->isa == cls) {
1882 _objc_inform("objc_registerProtocol: protocol '%s' was already "
1883 "registered!", proto->protocol_name);
1884 return;
1885 }
1886 if (proto->isa != oldcls) {
1887 _objc_inform("objc_registerProtocol: protocol '%s' was not allocated "
1888 "with objc_allocateProtocol!", proto->protocol_name);
1889 return;
1890 }
1891
1892 proto->isa = cls;
1893
1894 NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto);
1895 }
1896
1897
1898 /***********************************************************************
1899 * protocol_addProtocol
1900 * Adds an incorporated protocol to another protocol.
1901 * No method enforcement is performed.
1902 * `proto` must be under construction. `addition` must not.
1903 * Locking: acquires classLock
1904 **********************************************************************/
1905 void
1906 protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen)
1907 {
1908 old_protocol *proto = oldprotocol(proto_gen);
1909 old_protocol *addition = oldprotocol(addition_gen);
1910
1911 Class cls = objc_getClass("__IncompleteProtocol");
1912
1913 if (!proto_gen) return;
1914 if (!addition_gen) return;
1915
1916 mutex_locker_t lock(classLock);
1917
1918 if (proto->isa != cls) {
1919 _objc_inform("protocol_addProtocol: modified protocol '%s' is not "
1920 "under construction!", proto->protocol_name);
1921 return;
1922 }
1923 if (addition->isa == cls) {
1924 _objc_inform("protocol_addProtocol: added protocol '%s' is still "
1925 "under construction!", addition->protocol_name);
1926 return;
1927 }
1928
1929 old_protocol_list *protolist = proto->protocol_list;
1930 if (protolist) {
1931 size_t size = sizeof(old_protocol_list)
1932 + protolist->count * sizeof(protolist->list[0]);
1933 protolist = (old_protocol_list *)
1934 realloc(protolist, size);
1935 } else {
1936 protolist = (old_protocol_list *)
1937 calloc(1, sizeof(old_protocol_list));
1938 }
1939
1940 protolist->list[protolist->count++] = addition;
1941 proto->protocol_list = protolist;
1942 }
1943
1944
1945 /***********************************************************************
1946 * protocol_addMethodDescription
1947 * Adds a method to a protocol. The protocol must be under construction.
1948 * Locking: acquires classLock
1949 **********************************************************************/
1950 static void
1951 _protocol_addMethod(struct objc_method_description_list **list, SEL name, const char *types)
1952 {
1953 if (!*list) {
1954 *list = (struct objc_method_description_list *)
1955 calloc(sizeof(struct objc_method_description_list), 1);
1956 } else {
1957 size_t size = sizeof(struct objc_method_description_list)
1958 + (*list)->count * sizeof(struct objc_method_description);
1959 *list = (struct objc_method_description_list *)
1960 realloc(*list, size);
1961 }
1962
1963 struct objc_method_description *desc = &(*list)->list[(*list)->count++];
1964 desc->name = name;
1965 desc->types = strdup(types ?: "");
1966 }
1967
1968 void
1969 protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types,
1970 BOOL isRequiredMethod, BOOL isInstanceMethod)
1971 {
1972 old_protocol *proto = oldprotocol(proto_gen);
1973
1974 Class cls = objc_getClass("__IncompleteProtocol");
1975
1976 if (!proto_gen) return;
1977
1978 mutex_locker_t lock(classLock);
1979
1980 if (proto->isa != cls) {
1981 _objc_inform("protocol_addMethodDescription: protocol '%s' is not "
1982 "under construction!", proto->protocol_name);
1983 return;
1984 }
1985
1986 if (isRequiredMethod && isInstanceMethod) {
1987 _protocol_addMethod(&proto->instance_methods, name, types);
1988 } else if (isRequiredMethod && !isInstanceMethod) {
1989 _protocol_addMethod(&proto->class_methods, name, types);
1990 } else if (!isRequiredMethod && isInstanceMethod) {
1991 old_protocol_ext *ext = (old_protocol_ext *)(proto+1);
1992 _protocol_addMethod(&ext->optional_instance_methods, name, types);
1993 } else /* !isRequiredMethod && !isInstanceMethod) */ {
1994 old_protocol_ext *ext = (old_protocol_ext *)(proto+1);
1995 _protocol_addMethod(&ext->optional_class_methods, name, types);
1996 }
1997 }
1998
1999
2000 /***********************************************************************
2001 * protocol_addProperty
2002 * Adds a property to a protocol. The protocol must be under construction.
2003 * Locking: acquires classLock
2004 **********************************************************************/
2005 static void
2006 _protocol_addProperty(old_property_list **plist, const char *name,
2007 const objc_property_attribute_t *attrs,
2008 unsigned int count)
2009 {
2010 if (!*plist) {
2011 *plist = (old_property_list *)
2012 calloc(sizeof(old_property_list), 1);
2013 (*plist)->entsize = sizeof(old_property);
2014 } else {
2015 *plist = (old_property_list *)
2016 realloc(*plist, sizeof(old_property_list)
2017 + (*plist)->count * (*plist)->entsize);
2018 }
2019
2020 old_property *prop = property_list_nth(*plist, (*plist)->count++);
2021 prop->name = strdup(name);
2022 prop->attributes = copyPropertyAttributeString(attrs, count);
2023 }
2024
2025 void
2026 protocol_addProperty(Protocol *proto_gen, const char *name,
2027 const objc_property_attribute_t *attrs,
2028 unsigned int count,
2029 BOOL isRequiredProperty, BOOL isInstanceProperty)
2030 {
2031 old_protocol *proto = oldprotocol(proto_gen);
2032
2033 Class cls = objc_getClass("__IncompleteProtocol");
2034
2035 if (!proto) return;
2036 if (!name) return;
2037
2038 mutex_locker_t lock(classLock);
2039
2040 if (proto->isa != cls) {
2041 _objc_inform("protocol_addProperty: protocol '%s' is not "
2042 "under construction!", proto->protocol_name);
2043 return;
2044 }
2045
2046 old_protocol_ext *ext = ext_for_protocol(proto);
2047
2048 if (isRequiredProperty && isInstanceProperty) {
2049 _protocol_addProperty(&ext->instance_properties, name, attrs, count);
2050 }
2051 //else if (isRequiredProperty && !isInstanceProperty) {
2052 // _protocol_addProperty(&ext->class_properties, name, attrs, count);
2053 //} else if (!isRequiredProperty && isInstanceProperty) {
2054 // _protocol_addProperty(&ext->optional_instance_properties, name, attrs, count);
2055 //} else /* !isRequiredProperty && !isInstanceProperty) */ {
2056 // _protocol_addProperty(&ext->optional_class_properties, name, attrs, count);
2057 //}
2058 }
2059
2060
2061 /***********************************************************************
2062 * _objc_fixup_protocol_objects_for_image. For each protocol in the
2063 * specified image, selectorize the method names and add to the protocol hash.
2064 **********************************************************************/
2065
2066 static bool versionIsExt(uintptr_t version, const char *names, size_t size)
2067 {
2068 // CodeWarrior used isa field for string "Protocol"
2069 // from section __OBJC,__class_names. rdar://4951638
2070 // gcc (10.4 and earlier) used isa field for version number;
2071 // the only version number used on Mac OS X was 2.
2072 // gcc (10.5 and later) uses isa field for ext pointer
2073
2074 if (version < 4096 /* not PAGE_SIZE */) {
2075 return NO;
2076 }
2077
2078 if (version >= (uintptr_t)names && version < (uintptr_t)(names + size)) {
2079 return NO;
2080 }
2081
2082 return YES;
2083 }
2084
2085 static void fix_protocol(old_protocol *proto, Class protocolClass,
2086 bool isBundle, const char *names, size_t names_size)
2087 {
2088 uintptr_t version;
2089 if (!proto) return;
2090
2091 version = (uintptr_t)proto->isa;
2092
2093 // Set the protocol's isa
2094 proto->isa = protocolClass;
2095
2096 // Fix up method lists
2097 // fixme share across duplicates
2098 map_method_descs (proto->instance_methods, isBundle);
2099 map_method_descs (proto->class_methods, isBundle);
2100
2101 // Fix up ext, if any
2102 if (versionIsExt(version, names, names_size)) {
2103 old_protocol_ext *ext = (old_protocol_ext *)version;
2104 NXMapInsert(protocol_ext_map, proto, ext);
2105 map_method_descs (ext->optional_instance_methods, isBundle);
2106 map_method_descs (ext->optional_class_methods, isBundle);
2107 }
2108
2109 // Record the protocol it if we don't have one with this name yet
2110 // fixme bundles - copy protocol
2111 // fixme unloading
2112 if (!NXMapGet(protocol_map, proto->protocol_name)) {
2113 NXMapKeyCopyingInsert(protocol_map, proto->protocol_name, proto);
2114 if (PrintProtocols) {
2115 _objc_inform("PROTOCOLS: protocol at %p is %s",
2116 proto, proto->protocol_name);
2117 }
2118 } else {
2119 // duplicate - do nothing
2120 if (PrintProtocols) {
2121 _objc_inform("PROTOCOLS: protocol at %p is %s (duplicate)",
2122 proto, proto->protocol_name);
2123 }
2124 }
2125 }
2126
2127 static void _objc_fixup_protocol_objects_for_image (header_info * hi)
2128 {
2129 Class protocolClass = objc_getClass("Protocol");
2130 size_t count, i;
2131 old_protocol **protos;
2132 int isBundle = headerIsBundle(hi);
2133 const char *names;
2134 size_t names_size;
2135
2136 mutex_locker_t lock(classLock);
2137
2138 // Allocate the protocol registry if necessary.
2139 if (!protocol_map) {
2140 protocol_map =
2141 NXCreateMapTable(NXStrValueMapPrototype, 32);
2142 }
2143 if (!protocol_ext_map) {
2144 protocol_ext_map =
2145 NXCreateMapTable(NXPtrValueMapPrototype, 32);
2146 }
2147
2148 protos = _getObjcProtocols(hi, &count);
2149 names = _getObjcClassNames(hi, &names_size);
2150 for (i = 0; i < count; i++) {
2151 fix_protocol(protos[i], protocolClass, isBundle, names, names_size);
2152 }
2153 }
2154
2155
2156 /***********************************************************************
2157 * _objc_fixup_selector_refs. Register all of the selectors in each
2158 * image, and fix them all up.
2159 **********************************************************************/
2160 static void _objc_fixup_selector_refs (const header_info *hi)
2161 {
2162 size_t count;
2163 SEL *sels;
2164
2165 bool preoptimized = hi->isPreoptimized();
2166 # if SUPPORT_IGNORED_SELECTOR_CONSTANT
2167 // shared cache can't fix constant ignored selectors
2168 if (UseGC) preoptimized = NO;
2169 # endif
2170
2171 if (PrintPreopt) {
2172 if (preoptimized) {
2173 _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors in %s",
2174 hi->fname);
2175 }
2176 else if (_objcHeaderOptimizedByDyld(hi)) {
2177 _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors in %s",
2178 hi->fname);
2179 }
2180 }
2181
2182 if (preoptimized) return;
2183
2184 sels = _getObjcSelectorRefs (hi, &count);
2185
2186 map_selrefs(sels, count, headerIsBundle(hi));
2187 }
2188
2189 static inline bool _is_threaded() {
2190 #if TARGET_OS_WIN32
2191 return YES;
2192 #else
2193 return pthread_is_threaded_np() != 0;
2194 #endif
2195 }
2196
2197 #if !TARGET_OS_WIN32
2198 /***********************************************************************
2199 * unmap_image
2200 * Process the given image which is about to be unmapped by dyld.
2201 * mh is mach_header instead of headerType because that's what
2202 * dyld_priv.h says even for 64-bit.
2203 **********************************************************************/
2204 void
2205 unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide)
2206 {
2207 recursive_mutex_locker_t lock(loadMethodLock);
2208 unmap_image_nolock(mh);
2209 }
2210
2211
2212 /***********************************************************************
2213 * map_images
2214 * Process the given images which are being mapped in by dyld.
2215 * Calls ABI-agnostic code after taking ABI-specific locks.
2216 **********************************************************************/
2217 const char *
2218 map_2_images(enum dyld_image_states state, uint32_t infoCount,
2219 const struct dyld_image_info infoList[])
2220 {
2221 recursive_mutex_locker_t lock(loadMethodLock);
2222 return map_images_nolock(state, infoCount, infoList);
2223 }
2224
2225
2226 /***********************************************************************
2227 * load_images
2228 * Process +load in the given images which are being mapped in by dyld.
2229 * Calls ABI-agnostic code after taking ABI-specific locks.
2230 *
2231 * Locking: acquires classLock and loadMethodLock
2232 **********************************************************************/
2233 const char *
2234 load_images(enum dyld_image_states state, uint32_t infoCount,
2235 const struct dyld_image_info infoList[])
2236 {
2237 bool found;
2238
2239 recursive_mutex_locker_t lock(loadMethodLock);
2240
2241 // Discover +load methods
2242 found = load_images_nolock(state, infoCount, infoList);
2243
2244 // Call +load methods (without classLock - re-entrant)
2245 if (found) {
2246 call_load_methods();
2247 }
2248
2249 return nil;
2250 }
2251 #endif
2252
2253
2254 /***********************************************************************
2255 * _read_images
2256 * Perform metadata processing for hCount images starting with firstNewHeader
2257 **********************************************************************/
2258 void _read_images(header_info **hList, uint32_t hCount)
2259 {
2260 uint32_t i;
2261 bool categoriesLoaded = NO;
2262
2263 if (!class_hash) _objc_init_class_hash();
2264
2265 // Parts of this order are important for correctness or performance.
2266
2267 // Read classes from all images.
2268 for (i = 0; i < hCount; i++) {
2269 _objc_read_classes_from_image(hList[i]);
2270 }
2271
2272 // Read categories from all images.
2273 // But not if any other threads are running - they might
2274 // call a category method before the fixups below are complete.
2275 if (!_is_threaded()) {
2276 bool needFlush = NO;
2277 for (i = 0; i < hCount; i++) {
2278 needFlush |= _objc_read_categories_from_image(hList[i]);
2279 }
2280 if (needFlush) flush_marked_caches();
2281 categoriesLoaded = YES;
2282 }
2283
2284 // Connect classes from all images.
2285 for (i = 0; i < hCount; i++) {
2286 _objc_connect_classes_from_image(hList[i]);
2287 }
2288
2289 // Fix up class refs, selector refs, and protocol objects from all images.
2290 for (i = 0; i < hCount; i++) {
2291 _objc_map_class_refs_for_image(hList[i]);
2292 _objc_fixup_selector_refs(hList[i]);
2293 _objc_fixup_protocol_objects_for_image(hList[i]);
2294 }
2295
2296 // Read categories from all images.
2297 // But not if this is the only thread - it's more
2298 // efficient to attach categories earlier if safe.
2299 if (!categoriesLoaded) {
2300 bool needFlush = NO;
2301 for (i = 0; i < hCount; i++) {
2302 needFlush |= _objc_read_categories_from_image(hList[i]);
2303 }
2304 if (needFlush) flush_marked_caches();
2305 }
2306
2307 // Multi-threaded category load MUST BE LAST to avoid a race.
2308 }
2309
2310
2311 /***********************************************************************
2312 * prepare_load_methods
2313 * Schedule +load for classes in this image, any un-+load-ed
2314 * superclasses in other images, and any categories in this image.
2315 **********************************************************************/
2316 // Recursively schedule +load for cls and any un-+load-ed superclasses.
2317 // cls must already be connected.
2318 static void schedule_class_load(Class cls)
2319 {
2320 if (cls->info & CLS_LOADED) return;
2321 if (cls->superclass) schedule_class_load(cls->superclass);
2322 add_class_to_loadable_list(cls);
2323 cls->info |= CLS_LOADED;
2324 }
2325
2326 bool hasLoadMethods(const headerType *mhdr)
2327 {
2328 return true;
2329 }
2330
2331 void prepare_load_methods(const headerType *mhdr)
2332 {
2333 Module mods;
2334 unsigned int midx;
2335
2336 header_info *hi;
2337 for (hi = FirstHeader; hi; hi = hi->next) {
2338 if (mhdr == hi->mhdr) break;
2339 }
2340 if (!hi) return;
2341
2342 if (_objcHeaderIsReplacement(hi)) {
2343 // Ignore any classes in this image
2344 return;
2345 }
2346
2347 // Major loop - process all modules in the image
2348 mods = hi->mod_ptr;
2349 for (midx = 0; midx < hi->mod_count; midx += 1)
2350 {
2351 unsigned int index;
2352
2353 // Skip module containing no classes
2354 if (mods[midx].symtab == nil)
2355 continue;
2356
2357 // Minor loop - process all the classes in given module
2358 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
2359 {
2360 // Locate the class description pointer
2361 Class cls = (Class)mods[midx].symtab->defs[index];
2362 if (cls->info & CLS_CONNECTED) {
2363 schedule_class_load(cls);
2364 }
2365 }
2366 }
2367
2368
2369 // Major loop - process all modules in the header
2370 mods = hi->mod_ptr;
2371
2372 // NOTE: The module and category lists are traversed backwards
2373 // to preserve the pre-10.4 processing order. Changing the order
2374 // would have a small chance of introducing binary compatibility bugs.
2375 midx = (unsigned int)hi->mod_count;
2376 while (midx-- > 0) {
2377 unsigned int index;
2378 unsigned int total;
2379 Symtab symtab = mods[midx].symtab;
2380
2381 // Nothing to do for a module without a symbol table
2382 if (mods[midx].symtab == nil)
2383 continue;
2384 // Total entries in symbol table (class entries followed
2385 // by category entries)
2386 total = mods[midx].symtab->cls_def_cnt +
2387 mods[midx].symtab->cat_def_cnt;
2388
2389 // Minor loop - register all categories from given module
2390 index = total;
2391 while (index-- > mods[midx].symtab->cls_def_cnt) {
2392 old_category *cat = (old_category *)symtab->defs[index];
2393 add_category_to_loadable_list((Category)cat);
2394 }
2395 }
2396 }
2397
2398
2399 #if TARGET_OS_WIN32
2400
2401 void unload_class(Class cls)
2402 {
2403 }
2404
2405 #else
2406
2407 /***********************************************************************
2408 * _objc_remove_classes_in_image
2409 * Remove all classes in the given image from the runtime, because
2410 * the image is about to be unloaded.
2411 * Things to clean up:
2412 * class_hash
2413 * unconnected_class_hash
2414 * pending subclasses list (only if class is still unconnected)
2415 * loadable class list
2416 * class's method caches
2417 * class refs in all other images
2418 **********************************************************************/
2419 // Re-pend any class references in refs that point into [start..end)
2420 static void rependClassReferences(Class *refs, size_t count,
2421 uintptr_t start, uintptr_t end)
2422 {
2423 size_t i;
2424
2425 if (!refs) return;
2426
2427 // Process each class ref
2428 for (i = 0; i < count; i++) {
2429 if ((uintptr_t)(refs[i]) >= start && (uintptr_t)(refs[i]) < end) {
2430 pendClassReference(&refs[i], refs[i]->name,
2431 refs[i]->info & CLS_META);
2432 refs[i] = nil;
2433 }
2434 }
2435 }
2436
2437
2438 void try_free(const void *p)
2439 {
2440 if (p && malloc_size(p)) free((void *)p);
2441 }
2442
2443 // Deallocate all memory in a method list
2444 static void unload_mlist(old_method_list *mlist)
2445 {
2446 int i;
2447 for (i = 0; i < mlist->method_count; i++) {
2448 try_free(mlist->method_list[i].method_types);
2449 }
2450 try_free(mlist);
2451 }
2452
2453 static void unload_property_list(old_property_list *proplist)
2454 {
2455 uint32_t i;
2456
2457 if (!proplist) return;
2458
2459 for (i = 0; i < proplist->count; i++) {
2460 old_property *prop = property_list_nth(proplist, i);
2461 try_free(prop->name);
2462 try_free(prop->attributes);
2463 }
2464 try_free(proplist);
2465 }
2466
2467
2468 // Deallocate all memory in a class.
2469 void unload_class(Class cls)
2470 {
2471 // Free method cache
2472 // This dereferences the cache contents; do this before freeing methods
2473 if (cls->cache && cls->cache != &_objc_empty_cache) {
2474 _cache_free(cls->cache);
2475 }
2476
2477 // Free ivar lists
2478 if (cls->ivars) {
2479 int i;
2480 for (i = 0; i < cls->ivars->ivar_count; i++) {
2481 try_free(cls->ivars->ivar_list[i].ivar_name);
2482 try_free(cls->ivars->ivar_list[i].ivar_type);
2483 }
2484 try_free(cls->ivars);
2485 }
2486
2487 // Free fixed-up method lists and method list array
2488 if (cls->methodLists) {
2489 // more than zero method lists
2490 if (cls->info & CLS_NO_METHOD_ARRAY) {
2491 // one method list
2492 unload_mlist((old_method_list *)cls->methodLists);
2493 }
2494 else {
2495 // more than one method list
2496 old_method_list **mlistp;
2497 for (mlistp = cls->methodLists;
2498 *mlistp != nil && *mlistp != END_OF_METHODS_LIST;
2499 mlistp++)
2500 {
2501 unload_mlist(*mlistp);
2502 }
2503 free(cls->methodLists);
2504 }
2505 }
2506
2507 // Free protocol list
2508 old_protocol_list *protos = cls->protocols;
2509 while (protos) {
2510 old_protocol_list *dead = protos;
2511 protos = protos->next;
2512 try_free(dead);
2513 }
2514
2515 if ((cls->info & CLS_EXT)) {
2516 if (cls->ext) {
2517 // Free property lists and property list array
2518 if (cls->ext->propertyLists) {
2519 // more than zero property lists
2520 if (cls->info & CLS_NO_PROPERTY_ARRAY) {
2521 // one property list
2522 old_property_list *proplist =
2523 (old_property_list *)cls->ext->propertyLists;
2524 unload_property_list(proplist);
2525 } else {
2526 // more than one property list
2527 old_property_list **plistp;
2528 for (plistp = cls->ext->propertyLists;
2529 *plistp != nil;
2530 plistp++)
2531 {
2532 unload_property_list(*plistp);
2533 }
2534 try_free(cls->ext->propertyLists);
2535 }
2536 }
2537
2538 // Free weak ivar layout
2539 try_free(cls->ext->weak_ivar_layout);
2540
2541 // Free ext
2542 try_free(cls->ext);
2543 }
2544
2545 // Free non-weak ivar layout
2546 try_free(cls->ivar_layout);
2547 }
2548
2549 // Free class name
2550 try_free(cls->name);
2551
2552 // Free cls
2553 try_free(cls);
2554 }
2555
2556
2557 static void _objc_remove_classes_in_image(header_info *hi)
2558 {
2559 unsigned int index;
2560 unsigned int midx;
2561 Module mods;
2562
2563 mutex_locker_t lock(classLock);
2564
2565 // Major loop - process all modules in the image
2566 mods = hi->mod_ptr;
2567 for (midx = 0; midx < hi->mod_count; midx += 1)
2568 {
2569 // Skip module containing no classes
2570 if (mods[midx].symtab == nil)
2571 continue;
2572
2573 // Minor loop - process all the classes in given module
2574 for (index = 0; index < mods[midx].symtab->cls_def_cnt; index += 1)
2575 {
2576 Class cls;
2577
2578 // Locate the class description pointer
2579 cls = (Class)mods[midx].symtab->defs[index];
2580
2581 // Remove from loadable class list, if present
2582 remove_class_from_loadable_list(cls);
2583
2584 // Remove from unconnected_class_hash and pending subclasses
2585 if (unconnected_class_hash && NXHashMember(unconnected_class_hash, cls)) {
2586 NXHashRemove(unconnected_class_hash, cls);
2587 if (pendingSubclassesMap) {
2588 // Find this class in its superclass's pending list
2589 char *supercls_name = (char *)cls->superclass;
2590 PendingSubclass *pending = (PendingSubclass *)
2591 NXMapGet(pendingSubclassesMap, supercls_name);
2592 for ( ; pending != nil; pending = pending->next) {
2593 if (pending->subclass == cls) {
2594 pending->subclass = Nil;
2595 break;
2596 }
2597 }
2598 }
2599 }
2600
2601 // Remove from class_hash
2602 NXHashRemove(class_hash, cls);
2603 objc_removeRegisteredClass(cls);
2604
2605 // Free heap memory pointed to by the class
2606 unload_class(cls->ISA());
2607 unload_class(cls);
2608 }
2609 }
2610
2611
2612 // Search all other images for class refs that point back to this range.
2613 // Un-fix and re-pend any such class refs.
2614
2615 // Get the location of the dying image's __OBJC segment
2616 uintptr_t seg;
2617 unsigned long seg_size;
2618 seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size);
2619
2620 header_info *other_hi;
2621 for (other_hi = FirstHeader; other_hi != nil; other_hi = other_hi->next) {
2622 Class *other_refs;
2623 size_t count;
2624 if (other_hi == hi) continue; // skip the image being unloaded
2625
2626 // Fix class refs in the other image
2627 other_refs = _getObjcClassRefs(other_hi, &count);
2628 rependClassReferences(other_refs, count, seg, seg+seg_size);
2629 }
2630 }
2631
2632
2633 /***********************************************************************
2634 * _objc_remove_categories_in_image
2635 * Remove all categories in the given image from the runtime, because
2636 * the image is about to be unloaded.
2637 * Things to clean up:
2638 * unresolved category list
2639 * loadable category list
2640 **********************************************************************/
2641 static void _objc_remove_categories_in_image(header_info *hi)
2642 {
2643 Module mods;
2644 unsigned int midx;
2645
2646 // Major loop - process all modules in the header
2647 mods = hi->mod_ptr;
2648
2649 for (midx = 0; midx < hi->mod_count; midx++) {
2650 unsigned int index;
2651 unsigned int total;
2652 Symtab symtab = mods[midx].symtab;
2653
2654 // Nothing to do for a module without a symbol table
2655 if (symtab == nil) continue;
2656
2657 // Total entries in symbol table (class entries followed
2658 // by category entries)
2659 total = symtab->cls_def_cnt + symtab->cat_def_cnt;
2660
2661 // Minor loop - check all categories from given module
2662 for (index = symtab->cls_def_cnt; index < total; index++) {
2663 old_category *cat = (old_category *)symtab->defs[index];
2664
2665 // Clean up loadable category list
2666 remove_category_from_loadable_list((Category)cat);
2667
2668 // Clean up category_hash
2669 if (category_hash) {
2670 _objc_unresolved_category *cat_entry = (_objc_unresolved_category *)NXMapGet(category_hash, cat->class_name);
2671 for ( ; cat_entry != nil; cat_entry = cat_entry->next) {
2672 if (cat_entry->cat == cat) {
2673 cat_entry->cat = nil;
2674 break;
2675 }
2676 }
2677 }
2678 }
2679 }
2680 }
2681
2682
2683 /***********************************************************************
2684 * unload_paranoia
2685 * Various paranoid debugging checks that look for poorly-behaving
2686 * unloadable bundles.
2687 * Called by _objc_unmap_image when OBJC_UNLOAD_DEBUG is set.
2688 **********************************************************************/
2689 static void unload_paranoia(header_info *hi)
2690 {
2691 // Get the location of the dying image's __OBJC segment
2692 uintptr_t seg;
2693 unsigned long seg_size;
2694 seg = (uintptr_t)getsegmentdata(hi->mhdr, "__OBJC", &seg_size);
2695
2696 _objc_inform("UNLOAD DEBUG: unloading image '%s' [%p..%p]",
2697 hi->fname, (void *)seg, (void*)(seg+seg_size));
2698
2699 mutex_locker_t lock(classLock);
2700
2701 // Make sure the image contains no categories on surviving classes.
2702 {
2703 Module mods;
2704 unsigned int midx;
2705
2706 // Major loop - process all modules in the header
2707 mods = hi->mod_ptr;
2708
2709 for (midx = 0; midx < hi->mod_count; midx++) {
2710 unsigned int index;
2711 unsigned int total;
2712 Symtab symtab = mods[midx].symtab;
2713
2714 // Nothing to do for a module without a symbol table
2715 if (symtab == nil) continue;
2716
2717 // Total entries in symbol table (class entries followed
2718 // by category entries)
2719 total = symtab->cls_def_cnt + symtab->cat_def_cnt;
2720
2721 // Minor loop - check all categories from given module
2722 for (index = symtab->cls_def_cnt; index < total; index++) {
2723 old_category *cat = (old_category *)symtab->defs[index];
2724 struct objc_class query;
2725
2726 query.name = cat->class_name;
2727 if (NXHashMember(class_hash, &query)) {
2728 _objc_inform("UNLOAD DEBUG: dying image contains category '%s(%s)' on surviving class '%s'!", cat->class_name, cat->category_name, cat->class_name);
2729 }
2730 }
2731 }
2732 }
2733
2734 // Make sure no surviving class is in the dying image.
2735 // Make sure no surviving class has a superclass in the dying image.
2736 // fixme check method implementations too
2737 {
2738 Class cls;
2739 NXHashState state;
2740
2741 state = NXInitHashState(class_hash);
2742 while (NXNextHashState(class_hash, &state, (void **)&cls)) {
2743 if ((vm_address_t)cls >= seg &&
2744 (vm_address_t)cls < seg+seg_size)
2745 {
2746 _objc_inform("UNLOAD DEBUG: dying image contains surviving class '%s'!", cls->name);
2747 }
2748
2749 if ((vm_address_t)cls->superclass >= seg &&
2750 (vm_address_t)cls->superclass < seg+seg_size)
2751 {
2752 _objc_inform("UNLOAD DEBUG: dying image contains superclass '%s' of surviving class '%s'!", cls->superclass->name, cls->name);
2753 }
2754 }
2755 }
2756 }
2757
2758
2759 /***********************************************************************
2760 * _unload_image
2761 * Only handles MH_BUNDLE for now.
2762 * Locking: loadMethodLock acquired by unmap_image
2763 **********************************************************************/
2764 void _unload_image(header_info *hi)
2765 {
2766 loadMethodLock.assertLocked();
2767
2768 // Cleanup:
2769 // Remove image's classes from the class list and free auxiliary data.
2770 // Remove image's unresolved or loadable categories and free auxiliary data
2771 // Remove image's unresolved class refs.
2772 _objc_remove_classes_in_image(hi);
2773 _objc_remove_categories_in_image(hi);
2774 _objc_remove_pending_class_refs_in_image(hi);
2775
2776 // Perform various debugging checks if requested.
2777 if (DebugUnload) unload_paranoia(hi);
2778 }
2779
2780 #endif
2781
2782
2783 /***********************************************************************
2784 * objc_addClass. Add the specified class to the table of known classes,
2785 * after doing a little verification and fixup.
2786 **********************************************************************/
2787 void objc_addClass (Class cls)
2788 {
2789 OBJC_WARN_DEPRECATED;
2790
2791 // Synchronize access to hash table
2792 mutex_locker_t lock(classLock);
2793
2794 // Make sure both the class and the metaclass have caches!
2795 // Clear all bits of the info fields except CLS_CLASS and CLS_META.
2796 // Normally these bits are already clear but if someone tries to cons
2797 // up their own class on the fly they might need to be cleared.
2798 if (cls->cache == nil) {
2799 cls->cache = (Cache) &_objc_empty_cache;
2800 cls->info = CLS_CLASS;
2801 }
2802
2803 if (cls->ISA()->cache == nil) {
2804 cls->ISA()->cache = (Cache) &_objc_empty_cache;
2805 cls->ISA()->info = CLS_META;
2806 }
2807
2808 // methodLists should be:
2809 // 1. nil (Tiger and later only)
2810 // 2. A -1 terminated method list array
2811 // In either case, CLS_NO_METHOD_ARRAY remains clear.
2812 // If the user manipulates the method list directly,
2813 // they must use the magic private format.
2814
2815 // Add the class to the table
2816 (void) NXHashInsert (class_hash, cls);
2817 objc_addRegisteredClass(cls);
2818
2819 // Superclass is no longer a leaf for cache flushing
2820 if (cls->superclass && (cls->superclass->info & CLS_LEAF)) {
2821 cls->superclass->clearInfo(CLS_LEAF);
2822 cls->superclass->ISA()->clearInfo(CLS_LEAF);
2823 }
2824 }
2825
2826 /***********************************************************************
2827 * _objcTweakMethodListPointerForClass.
2828 * Change the class's method list pointer to a method list array.
2829 * Does nothing if the method list pointer is already a method list array.
2830 * If the class is currently in use, methodListLock must be held by the caller.
2831 **********************************************************************/
2832 static void _objcTweakMethodListPointerForClass(Class cls)
2833 {
2834 old_method_list * originalList;
2835 const int initialEntries = 4;
2836 size_t mallocSize;
2837 old_method_list ** ptr;
2838
2839 // Do nothing if methodLists is already an array.
2840 if (cls->methodLists && !(cls->info & CLS_NO_METHOD_ARRAY)) return;
2841
2842 // Remember existing list
2843 originalList = (old_method_list *) cls->methodLists;
2844
2845 // Allocate and zero a method list array
2846 mallocSize = sizeof(old_method_list *) * initialEntries;
2847 ptr = (old_method_list **) calloc(1, mallocSize);
2848
2849 // Insert the existing list into the array
2850 ptr[initialEntries - 1] = END_OF_METHODS_LIST;
2851 ptr[0] = originalList;
2852
2853 // Replace existing list with array
2854 cls->methodLists = ptr;
2855 cls->clearInfo(CLS_NO_METHOD_ARRAY);
2856 }
2857
2858
2859 /***********************************************************************
2860 * _objc_insertMethods.
2861 * Adds methods to a class.
2862 * Does not flush any method caches.
2863 * Does not take any locks.
2864 * If the class is already in use, use class_addMethods() instead.
2865 **********************************************************************/
2866 void _objc_insertMethods(Class cls, old_method_list *mlist, old_category *cat)
2867 {
2868 old_method_list ***list;
2869 old_method_list **ptr;
2870 ptrdiff_t endIndex;
2871 size_t oldSize;
2872 size_t newSize;
2873
2874 if (!cls->methodLists) {
2875 // cls has no methods - simply use this method list
2876 cls->methodLists = (old_method_list **)mlist;
2877 cls->setInfo(CLS_NO_METHOD_ARRAY);
2878 return;
2879 }
2880
2881 // Log any existing methods being replaced
2882 if (PrintReplacedMethods) {
2883 int i;
2884 for (i = 0; i < mlist->method_count; i++) {
2885 extern IMP findIMPInClass(Class cls, SEL sel);
2886 SEL sel = sel_registerName((char *)mlist->method_list[i].method_name);
2887 IMP newImp = mlist->method_list[i].method_imp;
2888 IMP oldImp;
2889
2890 if ((oldImp = findIMPInClass(cls, sel))) {
2891 logReplacedMethod(cls->name, sel, ISMETA(cls),
2892 cat ? cat->category_name : nil,
2893 oldImp, newImp);
2894 }
2895 }
2896 }
2897
2898 // Create method list array if necessary
2899 _objcTweakMethodListPointerForClass(cls);
2900
2901 list = &cls->methodLists;
2902
2903 // Locate unused entry for insertion point
2904 ptr = *list;
2905 while ((*ptr != 0) && (*ptr != END_OF_METHODS_LIST))
2906 ptr += 1;
2907
2908 // If array is full, add to it
2909 if (*ptr == END_OF_METHODS_LIST)
2910 {
2911 // Calculate old and new dimensions
2912 endIndex = ptr - *list;
2913 oldSize = (endIndex + 1) * sizeof(void *);
2914 newSize = oldSize + sizeof(old_method_list *); // only increase by 1
2915
2916 // Grow the method list array by one.
2917 *list = (old_method_list **)realloc(*list, newSize);
2918
2919 // Zero out addition part of new array
2920 bzero (&((*list)[endIndex]), newSize - oldSize);
2921
2922 // Place new end marker
2923 (*list)[(newSize/sizeof(void *)) - 1] = END_OF_METHODS_LIST;
2924
2925 // Insertion point corresponds to old array end
2926 ptr = &((*list)[endIndex]);
2927 }
2928
2929 // Right shift existing entries by one
2930 bcopy (*list, (*list) + 1, (uint8_t *)ptr - (uint8_t *)*list);
2931
2932 // Insert at method list at beginning of array
2933 **list = mlist;
2934 }
2935
2936 /***********************************************************************
2937 * _objc_removeMethods.
2938 * Remove methods from a class.
2939 * Does not take any locks.
2940 * Does not flush any method caches.
2941 * If the class is currently in use, use class_removeMethods() instead.
2942 **********************************************************************/
2943 void _objc_removeMethods(Class cls, old_method_list *mlist)
2944 {
2945 old_method_list ***list;
2946 old_method_list **ptr;
2947
2948 if (cls->methodLists == nil) {
2949 // cls has no methods
2950 return;
2951 }
2952 if (cls->methodLists == (old_method_list **)mlist) {
2953 // mlist is the class's only method list - erase it
2954 cls->methodLists = nil;
2955 return;
2956 }
2957 if (cls->info & CLS_NO_METHOD_ARRAY) {
2958 // cls has only one method list, and this isn't it - do nothing
2959 return;
2960 }
2961
2962 // cls has a method list array - search it
2963
2964 list = &cls->methodLists;
2965
2966 // Locate list in the array
2967 ptr = *list;
2968 while (*ptr != mlist) {
2969 // fix for radar # 2538790
2970 if ( *ptr == END_OF_METHODS_LIST ) return;
2971 ptr += 1;
2972 }
2973
2974 // Remove this entry
2975 *ptr = 0;
2976
2977 // Left shift the following entries
2978 while (*(++ptr) != END_OF_METHODS_LIST)
2979 *(ptr-1) = *ptr;
2980 *(ptr-1) = 0;
2981 }
2982
2983 /***********************************************************************
2984 * _objc_add_category. Install the specified category's methods and
2985 * protocols into the class it augments.
2986 * The class is assumed not to be in use yet: no locks are taken and
2987 * no method caches are flushed.
2988 **********************************************************************/
2989 static inline void _objc_add_category(Class cls, old_category *category, int version)
2990 {
2991 if (PrintConnecting) {
2992 _objc_inform("CONNECT: attaching category '%s (%s)'", cls->name, category->category_name);
2993 }
2994
2995 // Augment instance methods
2996 if (category->instance_methods)
2997 _objc_insertMethods (cls, category->instance_methods, category);
2998
2999 // Augment class methods
3000 if (category->class_methods)
3001 _objc_insertMethods (cls->ISA(), category->class_methods, category);
3002
3003 // Augment protocols
3004 if ((version >= 5) && category->protocols)
3005 {
3006 if (cls->ISA()->version >= 5)
3007 {
3008 category->protocols->next = cls->protocols;
3009 cls->protocols = category->protocols;
3010 cls->ISA()->protocols = category->protocols;
3011 }
3012 else
3013 {
3014 _objc_inform ("unable to add protocols from category %s...\n", category->category_name);
3015 _objc_inform ("class `%s' must be recompiled\n", category->class_name);
3016 }
3017 }
3018
3019 // Augment properties
3020 if (version >= 7 && category->instance_properties) {
3021 if (cls->ISA()->version >= 6) {
3022 _class_addProperties(cls, category->instance_properties);
3023 } else {
3024 _objc_inform ("unable to add properties from category %s...\n", category->category_name);
3025 _objc_inform ("class `%s' must be recompiled\n", category->class_name);
3026 }
3027 }
3028 }
3029
3030 /***********************************************************************
3031 * _objc_add_category_flush_caches. Install the specified category's
3032 * methods into the class it augments, and flush the class' method cache.
3033 * Return YES if some method caches now need to be flushed.
3034 **********************************************************************/
3035 static bool _objc_add_category_flush_caches(Class cls, old_category *category, int version)
3036 {
3037 bool needFlush = NO;
3038
3039 // Install the category's methods into its intended class
3040 {
3041 mutex_locker_t lock(methodListLock);
3042 _objc_add_category (cls, category, version);
3043 }
3044
3045 // Queue for cache flushing so category's methods can get called
3046 if (category->instance_methods) {
3047 cls->setInfo(CLS_FLUSH_CACHE);
3048 needFlush = YES;
3049 }
3050 if (category->class_methods) {
3051 cls->ISA()->setInfo(CLS_FLUSH_CACHE);
3052 needFlush = YES;
3053 }
3054
3055 return needFlush;
3056 }
3057
3058
3059 /***********************************************************************
3060 * reverse_cat
3061 * Reverse the given linked list of pending categories.
3062 * The pending category list is built backwards, and needs to be
3063 * reversed before actually attaching the categories to a class.
3064 * Returns the head of the new linked list.
3065 **********************************************************************/
3066 static _objc_unresolved_category *reverse_cat(_objc_unresolved_category *cat)
3067 {
3068 _objc_unresolved_category *prev;
3069 _objc_unresolved_category *cur;
3070 _objc_unresolved_category *ahead;
3071
3072 if (!cat) return nil;
3073
3074 prev = nil;
3075 cur = cat;
3076 ahead = cat->next;
3077
3078 while (cur) {
3079 ahead = cur->next;
3080 cur->next = prev;
3081 prev = cur;
3082 cur = ahead;
3083 }
3084
3085 return prev;
3086 }
3087
3088
3089 /***********************************************************************
3090 * resolve_categories_for_class.
3091 * Install all existing categories intended for the specified class.
3092 * cls must be a true class and not a metaclass.
3093 **********************************************************************/
3094 static void resolve_categories_for_class(Class cls)
3095 {
3096 _objc_unresolved_category * pending;
3097 _objc_unresolved_category * next;
3098
3099 // Nothing to do if there are no categories at all
3100 if (!category_hash) return;
3101
3102 // Locate and remove first element in category list
3103 // associated with this class
3104 pending = (_objc_unresolved_category *)
3105 NXMapKeyFreeingRemove (category_hash, cls->name);
3106
3107 // Traverse the list of categories, if any, registered for this class
3108
3109 // The pending list is built backwards. Reverse it and walk forwards.
3110 pending = reverse_cat(pending);
3111
3112 while (pending) {
3113 if (pending->cat) {
3114 // Install the category
3115 // use the non-flush-cache version since we are only
3116 // called from the class intialization code
3117 _objc_add_category(cls, pending->cat, (int)pending->version);
3118 }
3119
3120 // Delink and reclaim this registration
3121 next = pending->next;
3122 free(pending);
3123 pending = next;
3124 }
3125 }
3126
3127
3128 /***********************************************************************
3129 * _objc_resolve_categories_for_class.
3130 * Public version of resolve_categories_for_class. This was
3131 * exported pre-10.4 for Omni et al. to workaround a problem
3132 * with too-lazy category attachment.
3133 * cls should be a class, but this function can also cope with metaclasses.
3134 **********************************************************************/
3135 void _objc_resolve_categories_for_class(Class cls)
3136 {
3137 // If cls is a metaclass, get the class.
3138 // resolve_categories_for_class() requires a real class to work correctly.
3139 if (ISMETA(cls)) {
3140 if (strncmp(cls->name, "_%", 2) == 0) {
3141 // Posee's meta's name is smashed and isn't in the class_hash,
3142 // so objc_getClass doesn't work.
3143 const char *baseName = strchr(cls->name, '%'); // get posee's real name
3144 cls = objc_getClass(baseName);
3145 } else {
3146 cls = objc_getClass(cls->name);
3147 }
3148 }
3149
3150 resolve_categories_for_class(cls);
3151 }
3152
3153
3154 /***********************************************************************
3155 * _objc_register_category.
3156 * Process a category read from an image.
3157 * If the category's class exists, attach the category immediately.
3158 * Classes that need cache flushing are marked but not flushed.
3159 * If the category's class does not exist yet, pend the category for
3160 * later attachment. Pending categories are attached in the order
3161 * they were discovered.
3162 * Returns YES if some method caches now need to be flushed.
3163 **********************************************************************/
3164 static bool _objc_register_category(old_category *cat, int version)
3165 {
3166 _objc_unresolved_category * new_cat;
3167 _objc_unresolved_category * old;
3168 Class theClass;
3169
3170 // If the category's class exists, attach the category.
3171 if ((theClass = objc_lookUpClass(cat->class_name))) {
3172 return _objc_add_category_flush_caches(theClass, cat, version);
3173 }
3174
3175 // If the category's class exists but is unconnected,
3176 // then attach the category to the class but don't bother
3177 // flushing any method caches (because they must be empty).
3178 // YES unconnected, NO class_handler
3179 if ((theClass = look_up_class(cat->class_name, YES, NO))) {
3180 _objc_add_category(theClass, cat, version);
3181 return NO;
3182 }
3183
3184
3185 // Category's class does not exist yet.
3186 // Save the category for later attachment.
3187
3188 if (PrintConnecting) {
3189 _objc_inform("CONNECT: pending category '%s (%s)'", cat->class_name, cat->category_name);
3190 }
3191
3192 // Create category lookup table if needed
3193 if (!category_hash)
3194 category_hash = NXCreateMapTable(NXStrValueMapPrototype, 128);
3195
3196 // Locate an existing list of categories, if any, for the class.
3197 old = (_objc_unresolved_category *)
3198 NXMapGet (category_hash, cat->class_name);
3199
3200 // Register the category to be fixed up later.
3201 // The category list is built backwards, and is reversed again
3202 // by resolve_categories_for_class().
3203 new_cat = (_objc_unresolved_category *)
3204 malloc(sizeof(_objc_unresolved_category));
3205 new_cat->next = old;
3206 new_cat->cat = cat;
3207 new_cat->version = version;
3208 (void) NXMapKeyCopyingInsert (category_hash, cat->class_name, new_cat);
3209
3210 return NO;
3211 }
3212
3213
3214 const char **
3215 _objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount)
3216 {
3217 Module mods;
3218 unsigned int m;
3219 const char **list;
3220 int count;
3221 int allocated;
3222
3223 list = nil;
3224 count = 0;
3225 allocated = 0;
3226
3227 mods = hi->mod_ptr;
3228 for (m = 0; m < hi->mod_count; m++) {
3229 int d;
3230
3231 if (!mods[m].symtab) continue;
3232
3233 for (d = 0; d < mods[m].symtab->cls_def_cnt; d++) {
3234 Class cls = (Class)mods[m].symtab->defs[d];
3235 // fixme what about future-ified classes?
3236 if (cls->isConnected()) {
3237 if (count == allocated) {
3238 allocated = allocated*2 + 16;
3239 list = (const char **)
3240 realloc((void *)list, allocated * sizeof(char *));
3241 }
3242 list[count++] = cls->name;
3243 }
3244 }
3245 }
3246
3247 if (count > 0) {
3248 // nil-terminate non-empty list
3249 if (count == allocated) {
3250 allocated = allocated+1;
3251 list = (const char **)
3252 realloc((void *)list, allocated * sizeof(char *));
3253 }
3254 list[count] = nil;
3255 }
3256
3257 if (outCount) *outCount = count;
3258 return list;
3259 }
3260
3261 Class gdb_class_getClass(Class cls)
3262 {
3263 const char *className = cls->name;
3264 if(!className || !strlen(className)) return Nil;
3265 Class rCls = look_up_class(className, NO, NO);
3266 return rCls;
3267
3268 }
3269
3270 Class gdb_object_getClass(id obj)
3271 {
3272 if (!obj) return nil;
3273 return gdb_class_getClass(obj->getIsa());
3274 }
3275
3276
3277 /***********************************************************************
3278 * Lock management
3279 **********************************************************************/
3280 rwlock_t selLock;
3281 mutex_t classLock;
3282 mutex_t methodListLock;
3283 mutex_t cacheUpdateLock;
3284 recursive_mutex_t loadMethodLock;
3285
3286 void lock_init(void)
3287 {
3288 }
3289
3290
3291 #endif