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