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