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