]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-class-old.m
objc4-493.9.tar.gz
[apple/objc4.git] / runtime / objc-class-old.m
1 /*
2 * Copyright (c) 1999-2009 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-class-old.m
26 * Support for old-ABI classes, methods, and categories.
27 **********************************************************************/
28
29 #if !__OBJC2__
30
31 #include "objc-private.h"
32 #include "objc-runtime-old.h"
33
34 // Freed objects have their isa set to point to this dummy class.
35 // This avoids the need to check for Nil classes in the messenger.
36 static const struct old_class freedObjectClass =
37 {
38 Nil, // isa
39 Nil, // super_class
40 "FREED(id)", // name
41 0, // version
42 0, // info
43 0, // instance_size
44 NULL, // ivars
45 NULL, // methodLists
46 (Cache) &_objc_empty_cache, // cache
47 NULL // protocols
48 };
49
50
51 /***********************************************************************
52 * _class_getFreedObjectClass. Return a pointer to the dummy freed
53 * object class. Freed objects get their isa pointers replaced with
54 * a pointer to the freedObjectClass, so that we can catch usages of
55 * the freed object.
56 **********************************************************************/
57 static Class _class_getFreedObjectClass(void)
58 {
59 return (Class)&freedObjectClass;
60 }
61
62
63 /***********************************************************************
64 * _objc_getFreedObjectClass. Return a pointer to the dummy freed
65 * object class. Freed objects get their isa pointers replaced with
66 * a pointer to the freedObjectClass, so that we can catch usages of
67 * the freed object.
68 **********************************************************************/
69 Class _objc_getFreedObjectClass(void)
70 {
71 return _class_getFreedObjectClass();
72 }
73
74
75 static void allocateExt(struct old_class *cls)
76 {
77 if (! (cls->info & CLS_EXT)) {
78 _objc_inform("class '%s' needs to be recompiled", cls->name);
79 return;
80 }
81 if (!cls->ext) {
82 uint32_t size = (uint32_t)sizeof(struct old_class_ext);
83 cls->ext = _calloc_internal(size, 1);
84 cls->ext->size = size;
85 }
86 }
87
88
89 static inline struct old_method *_findNamedMethodInList(struct old_method_list * mlist, const char *meth_name) {
90 int i;
91 if (!mlist) return NULL;
92 if (ignoreSelectorNamed(meth_name)) return NULL;
93 for (i = 0; i < mlist->method_count; i++) {
94 struct old_method *m = &mlist->method_list[i];
95 if (0 == strcmp((const char *)(m->method_name), meth_name)) {
96 return m;
97 }
98 }
99 return NULL;
100 }
101
102
103 /***********************************************************************
104 * Method list fixup markers.
105 * mlist->obsolete == fixed_up_method_list marks method lists with real SELs
106 * versus method lists with un-uniqued char*.
107 * PREOPTIMIZED VERSION:
108 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP
109 * dyld shared cache sets this for method lists it preoptimizes.
110 * UN-PREOPTIMIZED VERSION
111 * Fixed-up method lists get mlist->obsolete == OBJC_FIXED_UP_outside_dyld
112 * dyld shared cache uses OBJC_FIXED_UP, but those aren't trusted.
113 **********************************************************************/
114 #define OBJC_FIXED_UP ((void *)1771)
115 #define OBJC_FIXED_UP_outside_dyld ((void *)1773)
116 static void *fixed_up_method_list = OBJC_FIXED_UP;
117
118 // sel_init() decided that selectors in the dyld shared cache are untrustworthy
119 PRIVATE_EXTERN void disableSharedCacheOptimizations(void)
120 {
121 fixed_up_method_list = OBJC_FIXED_UP_outside_dyld;
122 }
123
124 /***********************************************************************
125 * fixupSelectorsInMethodList
126 * Uniques selectors in the given method list.
127 * Also replaces imps for GC-ignored selectors
128 * The given method list must be non-NULL and not already fixed-up.
129 * If the class was loaded from a bundle:
130 * fixes up the given list in place with heap-allocated selector strings
131 * If the class was not from a bundle:
132 * allocates a copy of the method list, fixes up the copy, and returns
133 * the copy. The given list is unmodified.
134 *
135 * If cls is already in use, methodListLock must be held by the caller.
136 **********************************************************************/
137 static struct old_method_list *fixupSelectorsInMethodList(struct old_class *cls, struct old_method_list *mlist)
138 {
139 int i;
140 size_t size;
141 struct old_method *method;
142 struct old_method_list *old_mlist;
143
144 if ( ! mlist ) return NULL;
145 if ( mlist->obsolete == fixed_up_method_list ) {
146 // method list OK
147 } else {
148 BOOL isBundle = (cls->info & CLS_FROM_BUNDLE) ? YES : NO;
149 if (!isBundle) {
150 old_mlist = mlist;
151 size = sizeof(struct old_method_list) - sizeof(struct old_method) + old_mlist->method_count * sizeof(struct old_method);
152 mlist = _malloc_internal(size);
153 memmove(mlist, old_mlist, size);
154 } else {
155 // Mach-O bundles are fixed up in place.
156 // This prevents leaks when a bundle is unloaded.
157 }
158 sel_lock();
159 for ( i = 0; i < mlist->method_count; i += 1 ) {
160 method = &mlist->method_list[i];
161 method->method_name =
162 sel_registerNameNoLock((const char *)method->method_name, isBundle); // Always copy selector data from bundles.
163
164 if (ignoreSelector(method->method_name)) {
165 method->method_imp = (IMP)&_objc_ignored_method;
166 }
167 }
168 sel_unlock();
169 mlist->obsolete = fixed_up_method_list;
170 }
171 return mlist;
172 }
173
174
175 /***********************************************************************
176 * nextMethodList
177 * Returns successive method lists from the given class.
178 * Method lists are returned in method search order (i.e. highest-priority
179 * implementations first).
180 * All necessary method list fixups are performed, so the
181 * returned method list is fully-constructed.
182 *
183 * If cls is already in use, methodListLock must be held by the caller.
184 * For full thread-safety, methodListLock must be continuously held by the
185 * caller across all calls to nextMethodList(). If the lock is released,
186 * the bad results listed in class_nextMethodList() may occur.
187 *
188 * void *iterator = NULL;
189 * struct old_method_list *mlist;
190 * mutex_lock(&methodListLock);
191 * while ((mlist = nextMethodList(cls, &iterator))) {
192 * // do something with mlist
193 * }
194 * mutex_unlock(&methodListLock);
195 **********************************************************************/
196 static struct old_method_list *nextMethodList(struct old_class *cls,
197 void **it)
198 {
199 uintptr_t index = *(uintptr_t *)it;
200 struct old_method_list **resultp;
201
202 if (index == 0) {
203 // First call to nextMethodList.
204 if (!cls->methodLists) {
205 resultp = NULL;
206 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
207 resultp = (struct old_method_list **)&cls->methodLists;
208 } else {
209 resultp = &cls->methodLists[0];
210 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
211 resultp = NULL;
212 }
213 }
214 } else {
215 // Subsequent call to nextMethodList.
216 if (!cls->methodLists) {
217 resultp = NULL;
218 } else if (cls->info & CLS_NO_METHOD_ARRAY) {
219 resultp = NULL;
220 } else {
221 resultp = &cls->methodLists[index];
222 if (!*resultp || *resultp == END_OF_METHODS_LIST) {
223 resultp = NULL;
224 }
225 }
226 }
227
228 // resultp now is NULL, meaning there are no more method lists,
229 // OR the address of the method list pointer to fix up and return.
230
231 if (resultp) {
232 if (*resultp) {
233 *resultp = fixupSelectorsInMethodList(cls, *resultp);
234 }
235 *it = (void *)(index + 1);
236 return *resultp;
237 } else {
238 *it = 0;
239 return NULL;
240 }
241 }
242
243
244 /* These next three functions are the heart of ObjC method lookup.
245 * If the class is currently in use, methodListLock must be held by the caller.
246 */
247 static inline struct old_method *_findMethodInList(struct old_method_list * mlist, SEL sel) {
248 int i;
249 if (!mlist) return NULL;
250 for (i = 0; i < mlist->method_count; i++) {
251 struct old_method *m = &mlist->method_list[i];
252 if (m->method_name == sel) {
253 return m;
254 }
255 }
256 return NULL;
257 }
258
259 static inline struct old_method * _findMethodInClass(struct old_class *cls, SEL sel) __attribute__((always_inline));
260 static inline struct old_method * _findMethodInClass(struct old_class *cls, SEL sel) {
261 // Flattened version of nextMethodList(). The optimizer doesn't
262 // do a good job with hoisting the conditionals out of the loop.
263 // Conceptually, this looks like:
264 // while ((mlist = nextMethodList(cls, &iterator))) {
265 // struct old_method *m = _findMethodInList(mlist, sel);
266 // if (m) return m;
267 // }
268
269 if (!cls->methodLists) {
270 // No method lists.
271 return NULL;
272 }
273 else if (cls->info & CLS_NO_METHOD_ARRAY) {
274 // One method list.
275 struct old_method_list **mlistp;
276 mlistp = (struct old_method_list **)&cls->methodLists;
277 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
278 return _findMethodInList(*mlistp, sel);
279 }
280 else {
281 // Multiple method lists.
282 struct old_method_list **mlistp;
283 for (mlistp = cls->methodLists;
284 *mlistp != NULL && *mlistp != END_OF_METHODS_LIST;
285 mlistp++)
286 {
287 struct old_method *m;
288 *mlistp = fixupSelectorsInMethodList(cls, *mlistp);
289 m = _findMethodInList(*mlistp, sel);
290 if (m) return m;
291 }
292 return NULL;
293 }
294 }
295
296 static inline struct old_method * _getMethod(struct old_class *cls, SEL sel) {
297 for (; cls; cls = cls->super_class) {
298 struct old_method *m;
299 m = _findMethodInClass(cls, sel);
300 if (m) return m;
301 }
302 return NULL;
303 }
304
305
306 // fixme for gc debugging temporary use
307 PRIVATE_EXTERN IMP findIMPInClass(struct old_class *cls, SEL sel)
308 {
309 struct old_method *m = _findMethodInClass(cls, sel);
310 if (m) return m->method_imp;
311 else return NULL;
312 }
313
314
315 /***********************************************************************
316 * _freedHandler.
317 **********************************************************************/
318 static void _freedHandler(id obj, SEL sel)
319 {
320 __objc_error (obj, "message %s sent to freed object=%p",
321 sel_getName(sel), obj);
322 }
323
324
325 /***********************************************************************
326 * ABI-specific lookUpMethod helpers.
327 **********************************************************************/
328 PRIVATE_EXTERN void lockForMethodLookup(void)
329 {
330 mutex_lock(&methodListLock);
331 }
332 PRIVATE_EXTERN void unlockForMethodLookup(void)
333 {
334 mutex_unlock(&methodListLock);
335 }
336 PRIVATE_EXTERN IMP prepareForMethodLookup(Class cls, SEL sel, BOOL init)
337 {
338 mutex_assert_unlocked(&methodListLock);
339
340 // Check for freed class
341 if (cls == _class_getFreedObjectClass())
342 return (IMP) _freedHandler;
343
344 if (init && !_class_isInitialized(cls)) {
345 _class_initialize (cls);
346 // If sel == initialize, _class_initialize will send +initialize and
347 // then the messenger will send +initialize again after this
348 // procedure finishes. Of course, if this is not being called
349 // from the messenger then it won't happen. 2778172
350 }
351
352 return NULL;
353 }
354
355
356 /***********************************************************************
357 * class_getVariable. Return the named instance variable.
358 **********************************************************************/
359 PRIVATE_EXTERN
360 Ivar _class_getVariable(Class cls_gen, const char *name, Class *memberOf)
361 {
362 struct old_class *cls = oldcls(cls_gen);
363
364 for (; cls != Nil; cls = cls->super_class) {
365 int i;
366
367 // Skip class having no ivars
368 if (!cls->ivars) continue;
369
370 for (i = 0; i < cls->ivars->ivar_count; i++) {
371 // Check this ivar's name. Be careful because the
372 // compiler generates ivar entries with NULL ivar_name
373 // (e.g. for anonymous bit fields).
374 struct old_ivar *ivar = &cls->ivars->ivar_list[i];
375 if (ivar->ivar_name && 0 == strcmp(name, ivar->ivar_name)) {
376 if (memberOf) *memberOf = (Class)cls;
377 return (Ivar)ivar;
378 }
379 }
380 }
381
382 // Not found
383 return NULL;
384 }
385
386
387 PRIVATE_EXTERN struct old_property *
388 property_list_nth(const struct old_property_list *plist, uint32_t i)
389 {
390 return (struct old_property *)(i*plist->entsize + (char *)&plist->first);
391 }
392
393 PRIVATE_EXTERN struct old_property **
394 copyPropertyList(struct old_property_list *plist, unsigned int *outCount)
395 {
396 struct old_property **result = NULL;
397 unsigned int count = 0;
398
399 if (plist) {
400 count = plist->count;
401 }
402
403 if (count > 0) {
404 unsigned int i;
405 result = malloc((count+1) * sizeof(struct old_property *));
406
407 for (i = 0; i < count; i++) {
408 result[i] = property_list_nth(plist, i);
409 }
410 result[i] = NULL;
411 }
412
413 if (outCount) *outCount = count;
414 return result;
415 }
416
417
418 static struct old_property_list *
419 nextPropertyList(struct old_class *cls, uintptr_t *indexp)
420 {
421 struct old_property_list *result = NULL;
422
423 mutex_assert_locked(&classLock);
424 if (! ((cls->info & CLS_EXT) && cls->ext)) {
425 // No class ext
426 result = NULL;
427 } else if (!cls->ext->propertyLists) {
428 // No property lists
429 result = NULL;
430 } else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
431 // Only one property list
432 if (*indexp == 0) {
433 result = (struct old_property_list *)cls->ext->propertyLists;
434 } else {
435 result = NULL;
436 }
437 } else {
438 // More than one property list
439 result = cls->ext->propertyLists[*indexp];
440 }
441
442 if (result) {
443 ++*indexp;
444 return result;
445 } else {
446 *indexp = 0;
447 return NULL;
448 }
449 }
450
451
452 /***********************************************************************
453 * class_getIvarLayout
454 * NULL means all-scanned. "" means non-scanned.
455 **********************************************************************/
456 const uint8_t *
457 class_getIvarLayout(Class cls_gen)
458 {
459 struct old_class *cls = oldcls(cls_gen);
460 if (cls && (cls->info & CLS_EXT)) {
461 return cls->ivar_layout;
462 } else {
463 return NULL; // conservative scan
464 }
465 }
466
467
468 /***********************************************************************
469 * class_getWeakIvarLayout
470 * NULL means no weak ivars.
471 **********************************************************************/
472 const uint8_t *
473 class_getWeakIvarLayout(Class cls_gen)
474 {
475 struct old_class *cls = oldcls(cls_gen);
476 if (cls && (cls->info & CLS_EXT) && cls->ext) {
477 return cls->ext->weak_ivar_layout;
478 } else {
479 return NULL; // no weak ivars
480 }
481 }
482
483
484 /***********************************************************************
485 * class_setIvarLayout
486 * NULL means all-scanned. "" means non-scanned.
487 **********************************************************************/
488 void class_setIvarLayout(Class cls_gen, const uint8_t *layout)
489 {
490 struct old_class *cls = oldcls(cls_gen);
491 if (!cls) return;
492
493 if (! (cls->info & CLS_EXT)) {
494 _objc_inform("class '%s' needs to be recompiled", cls->name);
495 return;
496 }
497
498 // fixme leak
499 cls->ivar_layout = _ustrdup_internal(layout);
500 }
501
502 // SPI: Instance-specific object layout.
503
504 void _class_setIvarLayoutAccessor(Class cls_gen, const uint8_t* (*accessor) (id object)) {
505 struct old_class *cls = oldcls(cls_gen);
506 if (!cls) return;
507
508 if (! (cls->info & CLS_EXT)) {
509 _objc_inform("class '%s' needs to be recompiled", cls->name);
510 return;
511 }
512
513 // fixme leak
514 cls->ivar_layout = (const uint8_t *)accessor;
515 _class_setInfo(cls_gen, CLS_HAS_INSTANCE_SPECIFIC_LAYOUT);
516 }
517
518 const uint8_t *_object_getIvarLayout(Class cls_gen, id object) {
519 struct old_class *cls = oldcls(cls_gen);
520 if (cls && (cls->info & CLS_EXT)) {
521 const uint8_t* layout = cls->ivar_layout;
522 if (cls->info & CLS_HAS_INSTANCE_SPECIFIC_LAYOUT) {
523 const uint8_t* (*accessor) (id object) = (const uint8_t* (*)(id))layout;
524 layout = accessor(object);
525 }
526 return layout;
527 } else {
528 return NULL;
529 }
530 }
531
532 /***********************************************************************
533 * class_setWeakIvarLayout
534 * NULL means no weak ivars.
535 **********************************************************************/
536 void class_setWeakIvarLayout(Class cls_gen, const uint8_t *layout)
537 {
538 struct old_class *cls = oldcls(cls_gen);
539 if (!cls) return;
540
541 mutex_lock(&classLock);
542
543 allocateExt(cls);
544
545 // fixme leak
546 cls->ext->weak_ivar_layout = _ustrdup_internal(layout);
547
548 mutex_unlock(&classLock);
549 }
550
551
552 /***********************************************************************
553 * _class_changeInfo
554 * Atomically sets and clears some bits in cls's info field.
555 * set and clear must not overlap.
556 **********************************************************************/
557 PRIVATE_EXTERN void _class_changeInfo(Class cls, long set, long clear)
558 {
559 struct old_class *old = oldcls(cls);
560 long newinfo;
561 long oldinfo;
562 do {
563 oldinfo = old->info;
564 newinfo = (oldinfo | set) & ~clear;
565 } while (! OSAtomicCompareAndSwapLong(oldinfo, newinfo, &old->info));
566 }
567
568
569 /***********************************************************************
570 * _class_getInfo
571 * Returns YES iff all set bits in get are also set in cls's info field.
572 **********************************************************************/
573 PRIVATE_EXTERN BOOL _class_getInfo(Class cls, int get)
574 {
575 struct old_class *old = oldcls(cls);
576 return ((old->info & get) == get) ? YES : NO;
577 }
578
579
580 /***********************************************************************
581 * _class_setInfo
582 * Atomically sets some bits in cls's info field.
583 **********************************************************************/
584 PRIVATE_EXTERN void _class_setInfo(Class cls, long set)
585 {
586 _class_changeInfo(cls, set, 0);
587 }
588
589
590 /***********************************************************************
591 * _class_clearInfo
592 * Atomically clears some bits in cls's info field.
593 **********************************************************************/
594 PRIVATE_EXTERN void _class_clearInfo(Class cls, long clear)
595 {
596 _class_changeInfo(cls, 0, clear);
597 }
598
599
600 /***********************************************************************
601 * isInitializing
602 * Return YES if cls is currently being initialized.
603 * The initializing bit is stored in the metaclass only.
604 **********************************************************************/
605 PRIVATE_EXTERN BOOL _class_isInitializing(Class cls)
606 {
607 return _class_getInfo(_class_getMeta(cls), CLS_INITIALIZING);
608 }
609
610
611 /***********************************************************************
612 * isInitialized
613 * Return YES if cls is already initialized.
614 * The initialized bit is stored in the metaclass only.
615 **********************************************************************/
616 PRIVATE_EXTERN BOOL _class_isInitialized(Class cls)
617 {
618 return _class_getInfo(_class_getMeta(cls), CLS_INITIALIZED);
619 }
620
621
622 /***********************************************************************
623 * setInitializing
624 * Mark cls as initialization in progress.
625 **********************************************************************/
626 PRIVATE_EXTERN void _class_setInitializing(Class cls)
627 {
628 _class_setInfo(_class_getMeta(cls), CLS_INITIALIZING);
629 }
630
631
632 /***********************************************************************
633 * setInitialized
634 * Atomically mark cls as initialized and not initializing.
635 **********************************************************************/
636 PRIVATE_EXTERN void _class_setInitialized(Class cls)
637 {
638 _class_changeInfo(_class_getMeta(cls), CLS_INITIALIZED, CLS_INITIALIZING);
639 }
640
641
642 /***********************************************************************
643 * class_setVersion. Record the specified version with the class.
644 **********************************************************************/
645 void class_setVersion(Class cls, int version)
646 {
647 if (!cls) return;
648 cls->version = version;
649 }
650
651 /***********************************************************************
652 * class_getVersion. Return the version recorded with the class.
653 **********************************************************************/
654 int class_getVersion(Class cls)
655 {
656 if (!cls) return 0;
657 return (int)cls->version;
658 }
659
660
661 PRIVATE_EXTERN Class _class_getMeta(Class cls)
662 {
663 if (_class_getInfo(cls, CLS_META)) return cls;
664 else return ((id)cls)->isa;
665 }
666
667 PRIVATE_EXTERN BOOL _class_isMetaClass(Class cls)
668 {
669 if (!cls) return NO;
670 return _class_getInfo(cls, CLS_META);
671 }
672
673
674 /***********************************************************************
675 * _class_getNonMetaClass.
676 * Return the ordinary class for this class or metaclass.
677 * Used by +initialize.
678 **********************************************************************/
679 PRIVATE_EXTERN Class _class_getNonMetaClass(Class cls)
680 {
681 // fixme ick
682 if (_class_isMetaClass(cls)) {
683 if (strncmp(_class_getName(cls), "_%", 2) == 0) {
684 // Posee's meta's name is smashed and isn't in the class_hash,
685 // so objc_getClass doesn't work.
686 const char *baseName = strchr(_class_getName(cls), '%'); // get posee's real name
687 cls = (Class)objc_getClass(baseName);
688 } else {
689 cls = (Class)objc_getClass(_class_getName(cls));
690 }
691 assert(cls);
692 }
693
694 return cls;
695 }
696
697
698 PRIVATE_EXTERN Class _class_getSuperclass(Class cls)
699 {
700 if (!cls) return nil;
701 return (Class)cls->super_class;
702 }
703
704
705 PRIVATE_EXTERN Cache _class_getCache(Class cls)
706 {
707 return cls->cache;
708 }
709
710 PRIVATE_EXTERN void _class_setCache(Class cls, Cache cache)
711 {
712 cls->cache = cache;
713 }
714
715 PRIVATE_EXTERN size_t _class_getInstanceSize(Class cls)
716 {
717 if (!cls) return 0;
718 return (cls->instance_size + WORD_MASK) & ~WORD_MASK;
719 }
720
721 PRIVATE_EXTERN const char * _class_getName(Class cls)
722 {
723 if (!cls) return "nil";
724 return cls->name;
725 }
726
727
728
729 PRIVATE_EXTERN const char *_category_getName(Category cat)
730 {
731 return oldcategory(cat)->category_name;
732 }
733
734 PRIVATE_EXTERN const char *_category_getClassName(Category cat)
735 {
736 return oldcategory(cat)->class_name;
737 }
738
739 PRIVATE_EXTERN Class _category_getClass(Category cat)
740 {
741 return (Class)objc_getClass(oldcategory(cat)->class_name);
742 }
743
744 PRIVATE_EXTERN IMP _category_getLoadMethod(Category cat)
745 {
746 struct old_method_list *mlist = oldcategory(cat)->class_methods;
747 if (mlist) {
748 return lookupNamedMethodInMethodList(mlist, "load");
749 } else {
750 return NULL;
751 }
752 }
753
754
755
756 /***********************************************************************
757 * class_nextMethodList.
758 * External version of nextMethodList().
759 *
760 * This function is not fully thread-safe. A series of calls to
761 * class_nextMethodList() may fail if methods are added to or removed
762 * from the class between calls.
763 * If methods are added between calls to class_nextMethodList(), it may
764 * return previously-returned method lists again, and may fail to return
765 * newly-added lists.
766 * If methods are removed between calls to class_nextMethodList(), it may
767 * omit surviving method lists or simply crash.
768 **********************************************************************/
769 OBJC_EXPORT struct objc_method_list *class_nextMethodList(Class cls, void **it)
770 {
771 struct old_method_list *result;
772
773 OBJC_WARN_DEPRECATED;
774
775 mutex_lock(&methodListLock);
776 result = nextMethodList(oldcls(cls), it);
777 mutex_unlock(&methodListLock);
778 return (struct objc_method_list *)result;
779 }
780
781
782 /***********************************************************************
783 * class_addMethods.
784 *
785 * Formerly class_addInstanceMethods ()
786 **********************************************************************/
787 OBJC_EXPORT void class_addMethods(Class cls, struct objc_method_list *meths)
788 {
789 OBJC_WARN_DEPRECATED;
790
791 // Add the methods.
792 mutex_lock(&methodListLock);
793 _objc_insertMethods(oldcls(cls), (struct old_method_list *)meths, NULL);
794 mutex_unlock(&methodListLock);
795
796 // Must flush when dynamically adding methods. No need to flush
797 // all the class method caches. If cls is a meta class, though,
798 // this will still flush it and any of its sub-meta classes.
799 flush_caches (cls, NO);
800 }
801
802
803 /***********************************************************************
804 * class_removeMethods.
805 **********************************************************************/
806 OBJC_EXPORT void class_removeMethods(Class cls, struct objc_method_list *meths)
807 {
808 OBJC_WARN_DEPRECATED;
809
810 // Remove the methods
811 mutex_lock(&methodListLock);
812 _objc_removeMethods(oldcls(cls), (struct old_method_list *)meths);
813 mutex_unlock(&methodListLock);
814
815 // Must flush when dynamically removing methods. No need to flush
816 // all the class method caches. If cls is a meta class, though,
817 // this will still flush it and any of its sub-meta classes.
818 flush_caches (cls, NO);
819 }
820
821 /***********************************************************************
822 * lookupNamedMethodInMethodList
823 * Only called to find +load/-.cxx_construct/-.cxx_destruct methods,
824 * without fixing up the entire method list.
825 * The class is not yet in use, so methodListLock is not taken.
826 **********************************************************************/
827 PRIVATE_EXTERN IMP lookupNamedMethodInMethodList(struct old_method_list *mlist, const char *meth_name)
828 {
829 struct old_method *m;
830 m = meth_name ? _findNamedMethodInList(mlist, meth_name) : NULL;
831 return (m ? m->method_imp : NULL);
832 }
833
834 PRIVATE_EXTERN Method _class_getMethod(Class cls, SEL sel)
835 {
836 Method result;
837
838 mutex_lock(&methodListLock);
839 result = (Method)_getMethod(oldcls(cls), sel);
840 mutex_unlock(&methodListLock);
841
842 return result;
843 }
844
845 PRIVATE_EXTERN Method _class_getMethodNoSuper(Class cls, SEL sel)
846 {
847 Method result;
848
849 mutex_lock(&methodListLock);
850 result = (Method)_findMethodInClass(oldcls(cls), sel);
851 mutex_unlock(&methodListLock);
852
853 return result;
854 }
855
856 PRIVATE_EXTERN Method _class_getMethodNoSuper_nolock(Class cls, SEL sel)
857 {
858 mutex_assert_locked(&methodListLock);
859 return (Method)_findMethodInClass(oldcls(cls), sel);
860 }
861
862
863 BOOL class_conformsToProtocol(Class cls_gen, Protocol *proto_gen)
864 {
865 struct old_class *cls = oldcls(cls_gen);
866 struct old_protocol *proto = oldprotocol(proto_gen);
867
868 if (!cls_gen) return NO;
869 if (!proto) return NO;
870
871 if (cls->isa->version >= 3) {
872 struct old_protocol_list *list;
873 for (list = cls->protocols; list != NULL; list = list->next) {
874 int i;
875 for (i = 0; i < list->count; i++) {
876 if (list->list[i] == proto) return YES;
877 if (protocol_conformsToProtocol((Protocol *)list->list[i], proto_gen)) return YES;
878 }
879 if (cls->isa->version <= 4) break;
880 }
881 }
882 return NO;
883 }
884
885
886 static NXMapTable * posed_class_hash = NULL;
887
888 /***********************************************************************
889 * objc_getOrigClass.
890 **********************************************************************/
891 PRIVATE_EXTERN Class _objc_getOrigClass(const char *name)
892 {
893 Class ret;
894
895 // Look for class among the posers
896 ret = Nil;
897 mutex_lock(&classLock);
898 if (posed_class_hash)
899 ret = (Class) NXMapGet (posed_class_hash, name);
900 mutex_unlock(&classLock);
901 if (ret)
902 return ret;
903
904 // Not a poser. Do a normal lookup.
905 ret = (Class)objc_getClass (name);
906 if (!ret)
907 _objc_inform ("class `%s' not linked into application", name);
908
909 return ret;
910 }
911
912 Class objc_getOrigClass(const char *name)
913 {
914 OBJC_WARN_DEPRECATED;
915 return _objc_getOrigClass(name);
916 }
917
918 /***********************************************************************
919 * _objc_addOrigClass. This function is only used from class_poseAs.
920 * Registers the original class names, before they get obscured by
921 * posing, so that [super ..] will work correctly from categories
922 * in posing classes and in categories in classes being posed for.
923 **********************************************************************/
924 static void _objc_addOrigClass (struct old_class *origClass)
925 {
926 mutex_lock(&classLock);
927
928 // Create the poser's hash table on first use
929 if (!posed_class_hash)
930 {
931 posed_class_hash = NXCreateMapTableFromZone (NXStrValueMapPrototype,
932 8,
933 _objc_internal_zone ());
934 }
935
936 // Add the named class iff it is not already there (or collides?)
937 if (NXMapGet (posed_class_hash, origClass->name) == 0)
938 NXMapInsert (posed_class_hash, origClass->name, origClass);
939
940 mutex_unlock(&classLock);
941 }
942
943
944 /***********************************************************************
945 * change_class_references
946 * Change classrefs and superclass pointers from original to imposter
947 * But if copy!=nil, don't change copy->super_class.
948 * If changeSuperRefs==YES, also change [super message] classrefs.
949 * Used by class_poseAs and objc_setFutureClass
950 * classLock must be locked.
951 **********************************************************************/
952 PRIVATE_EXTERN
953 void change_class_references(struct old_class *imposter,
954 struct old_class *original,
955 struct old_class *copy,
956 BOOL changeSuperRefs)
957 {
958 header_info *hInfo;
959 struct old_class *clsObject;
960 NXHashState state;
961
962 // Change all subclasses of the original to point to the imposter.
963 state = NXInitHashState (class_hash);
964 while (NXNextHashState (class_hash, &state, (void **) &clsObject))
965 {
966 while ((clsObject) && (clsObject != imposter) &&
967 (clsObject != copy))
968 {
969 if (clsObject->super_class == original)
970 {
971 clsObject->super_class = imposter;
972 clsObject->isa->super_class = imposter->isa;
973 // We must flush caches here!
974 break;
975 }
976
977 clsObject = clsObject->super_class;
978 }
979 }
980
981 // Replace the original with the imposter in all class refs
982 // Major loop - process all headers
983 for (hInfo = FirstHeader; hInfo != NULL; hInfo = hInfo->next)
984 {
985 struct old_class **cls_refs;
986 size_t refCount;
987 unsigned int index;
988
989 // Fix class refs associated with this header
990 cls_refs = _getObjcClassRefs(hInfo, &refCount);
991 if (cls_refs) {
992 for (index = 0; index < refCount; index += 1) {
993 if (cls_refs[index] == original) {
994 cls_refs[index] = imposter;
995 }
996 }
997 }
998 }
999 }
1000
1001
1002 /***********************************************************************
1003 * class_poseAs.
1004 *
1005 * !!! class_poseAs () does not currently flush any caches.
1006 **********************************************************************/
1007 Class class_poseAs(Class imposter_gen, Class original_gen)
1008 {
1009 struct old_class *imposter = oldcls(imposter_gen);
1010 struct old_class *original = oldcls(original_gen);
1011 char * imposterNamePtr;
1012 struct old_class * copy;
1013
1014 OBJC_WARN_DEPRECATED;
1015
1016 // Trivial case is easy
1017 if (imposter_gen == original_gen)
1018 return imposter_gen;
1019
1020 // Imposter must be an immediate subclass of the original
1021 if (imposter->super_class != original) {
1022 __objc_error((id)imposter_gen,
1023 "[%s poseAs:%s]: target not immediate superclass",
1024 imposter->name, original->name);
1025 }
1026
1027 // Can't pose when you have instance variables (how could it work?)
1028 if (imposter->ivars) {
1029 __objc_error((id)imposter_gen,
1030 "[%s poseAs:%s]: %s defines new instance variables",
1031 imposter->name, original->name, imposter->name);
1032 }
1033
1034 // Build a string to use to replace the name of the original class.
1035 #if TARGET_OS_WIN32
1036 # define imposterNamePrefix "_%"
1037 imposterNamePtr = _malloc_internal(strlen(original->name) + strlen(imposterNamePrefix) + 1);
1038 strcpy(imposterNamePtr, imposterNamePrefix);
1039 strcat(imposterNamePtr, original->name);
1040 # undef imposterNamePrefix
1041 #else
1042 asprintf(&imposterNamePtr, "_%%%s", original->name);
1043 #endif
1044
1045 // We lock the class hashtable, so we are thread safe with respect to
1046 // calls to objc_getClass (). However, the class names are not
1047 // changed atomically, nor are all of the subclasses updated
1048 // atomically. I have ordered the operations so that you will
1049 // never crash, but you may get inconsistent results....
1050
1051 // Register the original class so that [super ..] knows
1052 // exactly which classes are the "original" classes.
1053 _objc_addOrigClass (original);
1054 _objc_addOrigClass (imposter);
1055
1056 // Copy the imposter, so that the imposter can continue
1057 // its normal life in addition to changing the behavior of
1058 // the original. As a hack we don't bother to copy the metaclass.
1059 // For some reason we modify the original rather than the copy.
1060 copy = (struct old_class *)_malloc_internal(sizeof(struct old_class));
1061 memmove(copy, imposter, sizeof(struct old_class));
1062
1063 mutex_lock(&classLock);
1064
1065 // Remove both the imposter and the original class.
1066 NXHashRemove (class_hash, imposter);
1067 NXHashRemove (class_hash, original);
1068
1069 NXHashInsert (class_hash, copy);
1070 objc_addRegisteredClass((Class)copy); // imposter & original will rejoin later, just track the new guy
1071
1072 // Mark the imposter as such
1073 _class_setInfo((Class)imposter, CLS_POSING);
1074 _class_setInfo((Class)imposter->isa, CLS_POSING);
1075
1076 // Change the name of the imposter to that of the original class.
1077 imposter->name = original->name;
1078 imposter->isa->name = original->isa->name;
1079
1080 // Also copy the version field to avoid archiving problems.
1081 imposter->version = original->version;
1082
1083 // Change classrefs and superclass pointers
1084 // Don't change copy->super_class
1085 // Don't change [super ...] messages
1086 change_class_references(imposter, original, copy, NO);
1087
1088 // Change the name of the original class.
1089 original->name = imposterNamePtr + 1;
1090 original->isa->name = imposterNamePtr;
1091
1092 // Restore the imposter and the original class with their new names.
1093 NXHashInsert (class_hash, imposter);
1094 NXHashInsert (class_hash, original);
1095
1096 mutex_unlock(&classLock);
1097
1098 return imposter_gen;
1099 }
1100
1101
1102 /***********************************************************************
1103 * flush_caches. Flush the instance and optionally class method caches
1104 * of cls and all its subclasses.
1105 *
1106 * Specifying Nil for the class "all classes."
1107 **********************************************************************/
1108 PRIVATE_EXTERN void flush_caches(Class target_gen, BOOL flush_meta)
1109 {
1110 NXHashState state;
1111 struct old_class *target = oldcls(target_gen);
1112 struct old_class *clsObject;
1113 #ifdef OBJC_INSTRUMENTED
1114 unsigned int classesVisited;
1115 unsigned int subclassCount;
1116 #endif
1117
1118 mutex_lock(&classLock);
1119 mutex_lock(&cacheUpdateLock);
1120
1121 // Leaf classes are fastest because there are no subclass caches to flush.
1122 // fixme instrument
1123 if (target && (target->info & CLS_LEAF)) {
1124 _cache_flush ((Class)target);
1125
1126 if (!flush_meta) {
1127 mutex_unlock(&cacheUpdateLock);
1128 mutex_unlock(&classLock);
1129 return; // done
1130 } else if (target->isa && (target->isa->info & CLS_LEAF)) {
1131 _cache_flush ((Class)target->isa);
1132 mutex_unlock(&cacheUpdateLock);
1133 mutex_unlock(&classLock);
1134 return; // done
1135 } else {
1136 // Reset target and handle it by one of the methods below.
1137 target = target->isa;
1138 flush_meta = NO;
1139 // NOT done
1140 }
1141 }
1142
1143 state = NXInitHashState(class_hash);
1144
1145 // Handle nil and root instance class specially: flush all
1146 // instance and class method caches. Nice that this
1147 // loop is linear vs the N-squared loop just below.
1148 if (!target || !target->super_class)
1149 {
1150 #ifdef OBJC_INSTRUMENTED
1151 LinearFlushCachesCount += 1;
1152 classesVisited = 0;
1153 subclassCount = 0;
1154 #endif
1155 // Traverse all classes in the hash table
1156 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1157 {
1158 struct old_class *metaClsObject;
1159 #ifdef OBJC_INSTRUMENTED
1160 classesVisited += 1;
1161 #endif
1162
1163 // Skip class that is known not to be a subclass of this root
1164 // (the isa pointer of any meta class points to the meta class
1165 // of the root).
1166 // NOTE: When is an isa pointer of a hash tabled class ever nil?
1167 metaClsObject = clsObject->isa;
1168 if (target && metaClsObject && target->isa != metaClsObject->isa) {
1169 continue;
1170 }
1171
1172 #ifdef OBJC_INSTRUMENTED
1173 subclassCount += 1;
1174 #endif
1175
1176 _cache_flush ((Class)clsObject);
1177 if (flush_meta && metaClsObject != NULL) {
1178 _cache_flush ((Class)metaClsObject);
1179 }
1180 }
1181 #ifdef OBJC_INSTRUMENTED
1182 LinearFlushCachesVisitedCount += classesVisited;
1183 if (classesVisited > MaxLinearFlushCachesVisitedCount)
1184 MaxLinearFlushCachesVisitedCount = classesVisited;
1185 IdealFlushCachesCount += subclassCount;
1186 if (subclassCount > MaxIdealFlushCachesCount)
1187 MaxIdealFlushCachesCount = subclassCount;
1188 #endif
1189
1190 mutex_unlock(&cacheUpdateLock);
1191 mutex_unlock(&classLock);
1192 return;
1193 }
1194
1195 // Outer loop - flush any cache that could now get a method from
1196 // cls (i.e. the cache associated with cls and any of its subclasses).
1197 #ifdef OBJC_INSTRUMENTED
1198 NonlinearFlushCachesCount += 1;
1199 classesVisited = 0;
1200 subclassCount = 0;
1201 #endif
1202 while (NXNextHashState(class_hash, &state, (void**)&clsObject))
1203 {
1204 struct old_class *clsIter;
1205
1206 #ifdef OBJC_INSTRUMENTED
1207 NonlinearFlushCachesClassCount += 1;
1208 #endif
1209
1210 // Inner loop - Process a given class
1211 clsIter = clsObject;
1212 while (clsIter)
1213 {
1214
1215 #ifdef OBJC_INSTRUMENTED
1216 classesVisited += 1;
1217 #endif
1218 // Flush clsObject instance method cache if
1219 // clsObject is a subclass of cls, or is cls itself
1220 // Flush the class method cache if that was asked for
1221 if (clsIter == target)
1222 {
1223 #ifdef OBJC_INSTRUMENTED
1224 subclassCount += 1;
1225 #endif
1226 _cache_flush ((Class)clsObject);
1227 if (flush_meta)
1228 _cache_flush ((Class)clsObject->isa);
1229
1230 break;
1231
1232 }
1233
1234 // Flush clsObject class method cache if cls is
1235 // the meta class of clsObject or of one
1236 // of clsObject's superclasses
1237 else if (clsIter->isa == target)
1238 {
1239 #ifdef OBJC_INSTRUMENTED
1240 subclassCount += 1;
1241 #endif
1242 _cache_flush ((Class)clsObject->isa);
1243 break;
1244 }
1245
1246 // Move up superclass chain
1247 // else if (_class_isInitialized(clsIter))
1248 clsIter = clsIter->super_class;
1249
1250 // clsIter is not initialized, so its cache
1251 // must be empty. This happens only when
1252 // clsIter == clsObject, because
1253 // superclasses are initialized before
1254 // subclasses, and this loop traverses
1255 // from sub- to super- classes.
1256 // else
1257 // break;
1258 }
1259 }
1260 #ifdef OBJC_INSTRUMENTED
1261 NonlinearFlushCachesVisitedCount += classesVisited;
1262 if (classesVisited > MaxNonlinearFlushCachesVisitedCount)
1263 MaxNonlinearFlushCachesVisitedCount = classesVisited;
1264 IdealFlushCachesCount += subclassCount;
1265 if (subclassCount > MaxIdealFlushCachesCount)
1266 MaxIdealFlushCachesCount = subclassCount;
1267 #endif
1268
1269 mutex_unlock(&cacheUpdateLock);
1270 mutex_unlock(&classLock);
1271 }
1272
1273
1274 /***********************************************************************
1275 * flush_marked_caches. Flush the method cache of any class marked
1276 * CLS_FLUSH_CACHE (and all subclasses thereof)
1277 * fixme instrument
1278 **********************************************************************/
1279 PRIVATE_EXTERN void flush_marked_caches(void)
1280 {
1281 struct old_class *cls;
1282 struct old_class *supercls;
1283 NXHashState state;
1284
1285 mutex_lock(&classLock);
1286 mutex_lock(&cacheUpdateLock);
1287
1288 state = NXInitHashState(class_hash);
1289 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1290 for (supercls = cls; supercls; supercls = supercls->super_class) {
1291 if (supercls->info & CLS_FLUSH_CACHE) {
1292 _cache_flush((Class)cls);
1293 break;
1294 }
1295 }
1296
1297 for (supercls = cls->isa; supercls; supercls = supercls->super_class) {
1298 if (supercls->info & CLS_FLUSH_CACHE) {
1299 _cache_flush((Class)cls->isa);
1300 break;
1301 }
1302 }
1303 }
1304
1305 state = NXInitHashState(class_hash);
1306 while (NXNextHashState(class_hash, &state, (void**)&cls)) {
1307 if (cls->info & CLS_FLUSH_CACHE) {
1308 _class_clearInfo((Class)cls, CLS_FLUSH_CACHE);
1309 }
1310 if (cls->isa->info & CLS_FLUSH_CACHE) {
1311 _class_clearInfo((Class)cls->isa, CLS_FLUSH_CACHE);
1312 }
1313 }
1314
1315 mutex_unlock(&cacheUpdateLock);
1316 mutex_unlock(&classLock);
1317 }
1318
1319
1320 /***********************************************************************
1321 * get_base_method_list
1322 * Returns the method list containing the class's own methods,
1323 * ignoring any method lists added by categories or class_addMethods.
1324 * Called only by add_class_to_loadable_list.
1325 * Does not hold methodListLock because add_class_to_loadable_list
1326 * does not manipulate in-use classes.
1327 **********************************************************************/
1328 static struct old_method_list *get_base_method_list(struct old_class *cls)
1329 {
1330 struct old_method_list **ptr;
1331
1332 if (!cls->methodLists) return NULL;
1333 if (cls->info & CLS_NO_METHOD_ARRAY) return (struct old_method_list *)cls->methodLists;
1334 ptr = cls->methodLists;
1335 if (!*ptr || *ptr == END_OF_METHODS_LIST) return NULL;
1336 while ( *ptr != 0 && *ptr != END_OF_METHODS_LIST ) { ptr++; }
1337 --ptr;
1338 return *ptr;
1339 }
1340
1341
1342 static IMP _class_getLoadMethod_nocheck(struct old_class *cls)
1343 {
1344 struct old_method_list *mlist;
1345 mlist = get_base_method_list(cls->isa);
1346 if (mlist) {
1347 return lookupNamedMethodInMethodList (mlist, "load");
1348 }
1349 return NULL;
1350 }
1351
1352
1353 PRIVATE_EXTERN BOOL _class_hasLoadMethod(Class cls)
1354 {
1355 if (oldcls(cls)->isa->info & CLS_HAS_LOAD_METHOD) return YES;
1356 return (_class_getLoadMethod_nocheck(oldcls(cls)) ? YES : NO);
1357 }
1358
1359
1360 /***********************************************************************
1361 * _class_getLoadMethod
1362 * Returns cls's +load implementation, or NULL if it doesn't have one.
1363 **********************************************************************/
1364 PRIVATE_EXTERN IMP _class_getLoadMethod(Class cls_gen)
1365 {
1366 struct old_class *cls = oldcls(cls_gen);
1367 if (cls->isa->info & CLS_HAS_LOAD_METHOD) {
1368 return _class_getLoadMethod_nocheck(cls);
1369 }
1370 return NULL;
1371 }
1372
1373
1374 PRIVATE_EXTERN BOOL _class_shouldGrowCache(Class cls)
1375 {
1376 return _class_getInfo(cls, CLS_GROW_CACHE);
1377 }
1378
1379 PRIVATE_EXTERN void _class_setGrowCache(Class cls, BOOL grow)
1380 {
1381 if (grow) _class_setInfo(cls, CLS_GROW_CACHE);
1382 else _class_clearInfo(cls, CLS_GROW_CACHE);
1383 }
1384
1385 PRIVATE_EXTERN BOOL _class_hasCxxStructors(Class cls)
1386 {
1387 // this DOES check superclasses too, because set_superclass
1388 // propagates the flag from the superclass.
1389 return _class_getInfo(cls, CLS_HAS_CXX_STRUCTORS);
1390 }
1391
1392 PRIVATE_EXTERN BOOL _class_shouldFinalizeOnMainThread(Class cls) {
1393 return _class_getInfo(cls, CLS_FINALIZE_ON_MAIN_THREAD);
1394 }
1395
1396 PRIVATE_EXTERN void _class_setFinalizeOnMainThread(Class cls) {
1397 _class_setInfo(cls, CLS_FINALIZE_ON_MAIN_THREAD);
1398 }
1399
1400 PRIVATE_EXTERN BOOL _class_instancesHaveAssociatedObjects(Class cls) {
1401 return _class_getInfo(cls, CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS);
1402 }
1403
1404 PRIVATE_EXTERN void _class_setInstancesHaveAssociatedObjects(Class cls) {
1405 _class_setInfo(cls, CLS_INSTANCES_HAVE_ASSOCIATED_OBJECTS);
1406 }
1407
1408 BOOL _class_usesAutomaticRetainRelease(Class cls)
1409 {
1410 return NO;
1411 }
1412
1413 PRIVATE_EXTERN uint32_t _class_getInstanceStart(Class cls)
1414 {
1415 _objc_fatal("_class_getInstanceStart() unimplemented for fragile instance variables");
1416 return 0; // PCB: never used just provided for ARR consistency.
1417 }
1418
1419 ptrdiff_t ivar_getOffset(Ivar ivar)
1420 {
1421 return oldivar(ivar)->ivar_offset;
1422 }
1423
1424 const char *ivar_getName(Ivar ivar)
1425 {
1426 return oldivar(ivar)->ivar_name;
1427 }
1428
1429 const char *ivar_getTypeEncoding(Ivar ivar)
1430 {
1431 return oldivar(ivar)->ivar_type;
1432 }
1433
1434
1435 IMP method_getImplementation(Method m)
1436 {
1437 if (!m) return NULL;
1438 return oldmethod(m)->method_imp;
1439 }
1440
1441 SEL method_getName(Method m)
1442 {
1443 if (!m) return NULL;
1444 return oldmethod(m)->method_name;
1445 }
1446
1447 const char *method_getTypeEncoding(Method m)
1448 {
1449 if (!m) return NULL;
1450 return oldmethod(m)->method_types;
1451 }
1452
1453 unsigned int method_getSizeOfArguments(Method m)
1454 {
1455 OBJC_WARN_DEPRECATED;
1456 if (!m) return 0;
1457 return encoding_getSizeOfArguments(method_getTypeEncoding(m));
1458 }
1459
1460 unsigned int method_getArgumentInfo(Method m, int arg,
1461 const char **type, int *offset)
1462 {
1463 OBJC_WARN_DEPRECATED;
1464 if (!m) return 0;
1465 return encoding_getArgumentInfo(method_getTypeEncoding(m),
1466 arg, type, offset);
1467 }
1468
1469
1470 static OSSpinLock impLock = OS_SPINLOCK_INIT;
1471
1472 IMP method_setImplementation(Method m_gen, IMP imp)
1473 {
1474 IMP old;
1475 struct old_method *m = oldmethod(m_gen);
1476 if (!m) return NULL;
1477 if (!imp) return NULL;
1478
1479 if (ignoreSelector(m->method_name)) {
1480 // Ignored methods stay ignored
1481 return m->method_imp;
1482 }
1483
1484 OSSpinLockLock(&impLock);
1485 old = m->method_imp;
1486 m->method_imp = imp;
1487 OSSpinLockUnlock(&impLock);
1488 return old;
1489 }
1490
1491
1492 void method_exchangeImplementations(Method m1_gen, Method m2_gen)
1493 {
1494 IMP m1_imp;
1495 struct old_method *m1 = oldmethod(m1_gen);
1496 struct old_method *m2 = oldmethod(m2_gen);
1497 if (!m1 || !m2) return;
1498
1499 if (ignoreSelector(m1->method_name) || ignoreSelector(m2->method_name)) {
1500 // Ignored methods stay ignored. Now they're both ignored.
1501 m1->method_imp = (IMP)&_objc_ignored_method;
1502 m2->method_imp = (IMP)&_objc_ignored_method;
1503 return;
1504 }
1505
1506 OSSpinLockLock(&impLock);
1507 m1_imp = m1->method_imp;
1508 m1->method_imp = m2->method_imp;
1509 m2->method_imp = m1_imp;
1510 OSSpinLockUnlock(&impLock);
1511 }
1512
1513
1514 struct objc_method_description * method_getDescription(Method m)
1515 {
1516 if (!m) return NULL;
1517 return (struct objc_method_description *)oldmethod(m);
1518 }
1519
1520
1521 const char *property_getName(objc_property_t prop)
1522 {
1523 return oldproperty(prop)->name;
1524 }
1525
1526 const char *property_getAttributes(objc_property_t prop)
1527 {
1528 return oldproperty(prop)->attributes;
1529 }
1530
1531 objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
1532 unsigned int *outCount)
1533 {
1534 if (!prop) {
1535 if (outCount) *outCount = 0;
1536 return NULL;
1537 }
1538
1539 objc_property_attribute_t *result;
1540 mutex_lock(&classLock);
1541 result = copyPropertyAttributeList(oldproperty(prop)->attributes,outCount);
1542 mutex_unlock(&classLock);
1543 return result;
1544 }
1545
1546 char * property_copyAttributeValue(objc_property_t prop, const char *name)
1547 {
1548 if (!prop || !name || *name == '\0') return NULL;
1549
1550 char *result;
1551 mutex_lock(&classLock);
1552 result = copyPropertyAttributeValue(oldproperty(prop)->attributes, name);
1553 mutex_unlock(&classLock);
1554 return result;
1555 }
1556
1557
1558 /***********************************************************************
1559 * class_addMethod
1560 **********************************************************************/
1561 static IMP _class_addMethod(Class cls_gen, SEL name, IMP imp,
1562 const char *types, BOOL replace)
1563 {
1564 struct old_class *cls = oldcls(cls_gen);
1565 struct old_method *m;
1566 IMP result = NULL;
1567
1568 if (!types) types = "";
1569
1570 mutex_lock(&methodListLock);
1571
1572 if ((m = _findMethodInClass(cls, name))) {
1573 // already exists
1574 // fixme atomic
1575 result = method_getImplementation((Method)m);
1576 if (replace) {
1577 method_setImplementation((Method)m, imp);
1578 }
1579 } else {
1580 // fixme could be faster
1581 struct old_method_list *mlist =
1582 _calloc_internal(sizeof(struct old_method_list), 1);
1583 mlist->obsolete = fixed_up_method_list;
1584 mlist->method_count = 1;
1585 mlist->method_list[0].method_name = name;
1586 mlist->method_list[0].method_types = _strdup_internal(types);
1587 if (!ignoreSelector(name)) {
1588 mlist->method_list[0].method_imp = imp;
1589 } else {
1590 mlist->method_list[0].method_imp = (IMP)&_objc_ignored_method;
1591 }
1592
1593 _objc_insertMethods(cls, mlist, NULL);
1594 if (!(cls->info & CLS_CONSTRUCTING)) {
1595 flush_caches((Class)cls, NO);
1596 } else {
1597 // in-construction class has no subclasses
1598 flush_cache((Class)cls);
1599 }
1600 result = NULL;
1601 }
1602
1603 mutex_unlock(&methodListLock);
1604
1605 return result;
1606 }
1607
1608
1609 /***********************************************************************
1610 * class_addMethod
1611 **********************************************************************/
1612 BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
1613 {
1614 IMP old;
1615 if (!cls) return NO;
1616
1617 old = _class_addMethod(cls, name, imp, types, NO);
1618 return old ? NO : YES;
1619 }
1620
1621
1622 /***********************************************************************
1623 * class_replaceMethod
1624 **********************************************************************/
1625 IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
1626 {
1627 if (!cls) return NULL;
1628
1629 return _class_addMethod(cls, name, imp, types, YES);
1630 }
1631
1632
1633 /***********************************************************************
1634 * class_addIvar
1635 **********************************************************************/
1636 BOOL class_addIvar(Class cls_gen, const char *name, size_t size,
1637 uint8_t alignment, const char *type)
1638 {
1639 struct old_class *cls = oldcls(cls_gen);
1640 BOOL result = YES;
1641
1642 if (!cls) return NO;
1643 if (ISMETA(cls)) return NO;
1644 if (!(cls->info & CLS_CONSTRUCTING)) return NO;
1645
1646 if (!type) type = "";
1647 if (name && 0 == strcmp(name, "")) name = NULL;
1648
1649 mutex_lock(&classLock);
1650
1651 // Check for existing ivar with this name
1652 // fixme check superclasses?
1653 if (cls->ivars) {
1654 int i;
1655 for (i = 0; i < cls->ivars->ivar_count; i++) {
1656 if (0 == strcmp(cls->ivars->ivar_list[i].ivar_name, name)) {
1657 result = NO;
1658 break;
1659 }
1660 }
1661 }
1662
1663 if (result) {
1664 struct old_ivar_list *old = cls->ivars;
1665 size_t oldSize;
1666 int newCount;
1667 struct old_ivar *ivar;
1668 size_t alignBytes;
1669 size_t misalign;
1670
1671 if (old) {
1672 oldSize = sizeof(struct old_ivar_list) +
1673 (old->ivar_count - 1) * sizeof(struct old_ivar);
1674 newCount = 1 + old->ivar_count;
1675 } else {
1676 oldSize = sizeof(struct old_ivar_list) - sizeof(struct old_ivar);
1677 newCount = 1;
1678 }
1679
1680 // allocate new ivar list
1681 cls->ivars = _calloc_internal(oldSize + sizeof(struct old_ivar), 1);
1682 if (old) memcpy(cls->ivars, old, oldSize);
1683 if (old && malloc_size(old)) free(old);
1684 cls->ivars->ivar_count = newCount;
1685 ivar = &cls->ivars->ivar_list[newCount-1];
1686
1687 // set ivar name and type
1688 ivar->ivar_name = _strdup_internal(name);
1689 ivar->ivar_type = _strdup_internal(type);
1690
1691 // align if necessary
1692 alignBytes = 1 << alignment;
1693 misalign = cls->instance_size % alignBytes;
1694 if (misalign) cls->instance_size += (long)(alignBytes - misalign);
1695
1696 // set ivar offset and increase instance size
1697 ivar->ivar_offset = (int)cls->instance_size;
1698 cls->instance_size += (long)size;
1699 }
1700
1701 mutex_unlock(&classLock);
1702
1703 return result;
1704 }
1705
1706
1707 /***********************************************************************
1708 * class_addProtocol
1709 **********************************************************************/
1710 BOOL class_addProtocol(Class cls_gen, Protocol *protocol_gen)
1711 {
1712 struct old_class *cls = oldcls(cls_gen);
1713 struct old_protocol *protocol = oldprotocol(protocol_gen);
1714 struct old_protocol_list *plist;
1715
1716 if (!cls) return NO;
1717 if (class_conformsToProtocol(cls_gen, protocol_gen)) return NO;
1718
1719 mutex_lock(&classLock);
1720
1721 // fixme optimize - protocol list doesn't escape?
1722 plist = _calloc_internal(sizeof(struct old_protocol_list), 1);
1723 plist->count = 1;
1724 plist->list[0] = protocol;
1725 plist->next = cls->protocols;
1726 cls->protocols = plist;
1727
1728 // fixme metaclass?
1729
1730 mutex_unlock(&classLock);
1731
1732 return YES;
1733 }
1734
1735
1736 /***********************************************************************
1737 * _class_addProperties
1738 * Internal helper to add properties to a class.
1739 * Used by category attachment and class_addProperty()
1740 * Locking: acquires classLock
1741 **********************************************************************/
1742 PRIVATE_EXTERN BOOL
1743 _class_addProperties(struct old_class *cls,
1744 struct old_property_list *additions)
1745 {
1746 struct old_property_list *newlist;
1747
1748 if (!(cls->info & CLS_EXT)) return NO;
1749
1750 newlist =
1751 _memdup_internal(additions, sizeof(*newlist) - sizeof(newlist->first)
1752 + (additions->entsize * additions->count));
1753
1754 mutex_lock(&classLock);
1755
1756 allocateExt(cls);
1757 if (!cls->ext->propertyLists) {
1758 // cls has no properties - simply use this list
1759 cls->ext->propertyLists = (struct old_property_list **)newlist;
1760 _class_setInfo((Class)cls, CLS_NO_PROPERTY_ARRAY);
1761 }
1762 else if (cls->info & CLS_NO_PROPERTY_ARRAY) {
1763 // cls has one property list - make a new array
1764 struct old_property_list **newarray =
1765 _malloc_internal(3 * sizeof(*newarray));
1766 newarray[0] = newlist;
1767 newarray[1] = (struct old_property_list *)cls->ext->propertyLists;
1768 newarray[2] = NULL;
1769 cls->ext->propertyLists = newarray;
1770 _class_clearInfo((Class)cls, CLS_NO_PROPERTY_ARRAY);
1771 }
1772 else {
1773 // cls has a property array - make a bigger one
1774 struct old_property_list **newarray;
1775 int count = 0;
1776 while (cls->ext->propertyLists[count]) count++;
1777 newarray = _malloc_internal((count+2) * sizeof(*newarray));
1778 newarray[0] = newlist;
1779 memcpy(&newarray[1], &cls->ext->propertyLists[0],
1780 count * sizeof(*newarray));
1781 newarray[count+1] = NULL;
1782 free(cls->ext->propertyLists);
1783 cls->ext->propertyLists = newarray;
1784 }
1785
1786 mutex_unlock(&classLock);
1787
1788 return YES;
1789 }
1790
1791
1792 /***********************************************************************
1793 * class_addProperty
1794 * Adds a property to a class. Returns NO if the proeprty already exists.
1795 * Locking: acquires classLock
1796 **********************************************************************/
1797 static BOOL
1798 _class_addProperty(Class cls_gen, const char *name,
1799 const objc_property_attribute_t *attrs, unsigned int count,
1800 BOOL replace)
1801 {
1802 struct old_class *cls = oldcls(cls_gen);
1803
1804 if (!cls) return NO;
1805 if (!name) return NO;
1806
1807 struct old_property *prop = oldproperty(class_getProperty(cls_gen, name));
1808 if (prop && !replace) {
1809 // already exists, refuse to replace
1810 return NO;
1811 }
1812 else if (prop) {
1813 // replace existing
1814 mutex_lock(&classLock);
1815 try_free(prop->attributes);
1816 prop->attributes = copyPropertyAttributeString(attrs, count);
1817 mutex_unlock(&classLock);
1818 return YES;
1819 }
1820 else {
1821 // add new
1822 struct old_property_list proplist;
1823 proplist.entsize = sizeof(struct old_property);
1824 proplist.count = 1;
1825 proplist.first.name = _strdup_internal(name);
1826 proplist.first.attributes = copyPropertyAttributeString(attrs, count);
1827
1828 return _class_addProperties(cls, &proplist);
1829 }
1830 }
1831
1832 BOOL
1833 class_addProperty(Class cls_gen, const char *name,
1834 const objc_property_attribute_t *attrs, unsigned int n)
1835 {
1836 return _class_addProperty(cls_gen, name, attrs, n, NO);
1837 }
1838
1839 void
1840 class_replaceProperty(Class cls_gen, const char *name,
1841 const objc_property_attribute_t *attrs, unsigned int n)
1842 {
1843 _class_addProperty(cls_gen, name, attrs, n, YES);
1844 }
1845
1846
1847 /***********************************************************************
1848 * class_copyProtocolList. Returns a heap block containing the
1849 * protocols implemented by the class, or NULL if the class
1850 * implements no protocols. Caller must free the block.
1851 * Does not copy any superclass's protocols.
1852 **********************************************************************/
1853 Protocol * __unsafe_unretained *
1854 class_copyProtocolList(Class cls_gen, unsigned int *outCount)
1855 {
1856 struct old_class *cls = oldcls(cls_gen);
1857 struct old_protocol_list *plist;
1858 Protocol **result = NULL;
1859 unsigned int count = 0;
1860 unsigned int p;
1861
1862 if (!cls) {
1863 if (outCount) *outCount = 0;
1864 return NULL;
1865 }
1866
1867 mutex_lock(&classLock);
1868
1869 for (plist = cls->protocols; plist != NULL; plist = plist->next) {
1870 count += (int)plist->count;
1871 }
1872
1873 if (count > 0) {
1874 result = malloc((count+1) * sizeof(Protocol *));
1875
1876 for (p = 0, plist = cls->protocols;
1877 plist != NULL;
1878 plist = plist->next)
1879 {
1880 int i;
1881 for (i = 0; i < plist->count; i++) {
1882 result[p++] = (Protocol *)plist->list[i];
1883 }
1884 }
1885 result[p] = NULL;
1886 }
1887
1888 mutex_unlock(&classLock);
1889
1890 if (outCount) *outCount = count;
1891 return result;
1892 }
1893
1894
1895 /***********************************************************************
1896 * class_getProperty. Return the named property.
1897 **********************************************************************/
1898 objc_property_t class_getProperty(Class cls_gen, const char *name)
1899 {
1900 struct old_property *result;
1901 struct old_class *cls = oldcls(cls_gen);
1902 if (!cls || !name) return NULL;
1903
1904 mutex_lock(&classLock);
1905
1906 for (result = NULL; cls && !result; cls = cls->super_class) {
1907 uintptr_t iterator = 0;
1908 struct old_property_list *plist;
1909 while ((plist = nextPropertyList(cls, &iterator))) {
1910 uint32_t i;
1911 for (i = 0; i < plist->count; i++) {
1912 struct old_property *p = property_list_nth(plist, i);
1913 if (0 == strcmp(name, p->name)) {
1914 result = p;
1915 goto done;
1916 }
1917 }
1918 }
1919 }
1920
1921 done:
1922 mutex_unlock(&classLock);
1923
1924 return (objc_property_t)result;
1925 }
1926
1927
1928 /***********************************************************************
1929 * class_copyPropertyList. Returns a heap block containing the
1930 * properties declared in the class, or NULL if the class
1931 * declares no properties. Caller must free the block.
1932 * Does not copy any superclass's properties.
1933 **********************************************************************/
1934 objc_property_t *class_copyPropertyList(Class cls_gen, unsigned int *outCount)
1935 {
1936 struct old_class *cls = oldcls(cls_gen);
1937 struct old_property_list *plist;
1938 uintptr_t iterator = 0;
1939 struct old_property **result = NULL;
1940 unsigned int count = 0;
1941 unsigned int p, i;
1942
1943 if (!cls) {
1944 if (outCount) *outCount = 0;
1945 return NULL;
1946 }
1947
1948 mutex_lock(&classLock);
1949
1950 iterator = 0;
1951 while ((plist = nextPropertyList(cls, &iterator))) {
1952 count += plist->count;
1953 }
1954
1955 if (count > 0) {
1956 result = malloc((count+1) * sizeof(struct old_property *));
1957
1958 p = 0;
1959 iterator = 0;
1960 while ((plist = nextPropertyList(cls, &iterator))) {
1961 for (i = 0; i < plist->count; i++) {
1962 result[p++] = property_list_nth(plist, i);
1963 }
1964 }
1965 result[p] = NULL;
1966 }
1967
1968 mutex_unlock(&classLock);
1969
1970 if (outCount) *outCount = count;
1971 return (objc_property_t *)result;
1972 }
1973
1974
1975 /***********************************************************************
1976 * class_copyMethodList. Returns a heap block containing the
1977 * methods implemented by the class, or NULL if the class
1978 * implements no methods. Caller must free the block.
1979 * Does not copy any superclass's methods.
1980 **********************************************************************/
1981 Method *class_copyMethodList(Class cls_gen, unsigned int *outCount)
1982 {
1983 struct old_class *cls = oldcls(cls_gen);
1984 struct old_method_list *mlist;
1985 void *iterator = NULL;
1986 Method *result = NULL;
1987 unsigned int count = 0;
1988 unsigned int m;
1989
1990 if (!cls) {
1991 if (outCount) *outCount = 0;
1992 return NULL;
1993 }
1994
1995 mutex_lock(&methodListLock);
1996
1997 iterator = NULL;
1998 while ((mlist = nextMethodList(cls, &iterator))) {
1999 count += mlist->method_count;
2000 }
2001
2002 if (count > 0) {
2003 result = malloc((count+1) * sizeof(Method));
2004
2005 m = 0;
2006 iterator = NULL;
2007 while ((mlist = nextMethodList(cls, &iterator))) {
2008 int i;
2009 for (i = 0; i < mlist->method_count; i++) {
2010 Method aMethod = (Method)&mlist->method_list[i];
2011 if (ignoreSelector(method_getName(aMethod))) {
2012 count--;
2013 continue;
2014 }
2015 result[m++] = aMethod;
2016 }
2017 }
2018 result[m] = NULL;
2019 }
2020
2021 mutex_unlock(&methodListLock);
2022
2023 if (outCount) *outCount = count;
2024 return result;
2025 }
2026
2027
2028 /***********************************************************************
2029 * class_copyIvarList. Returns a heap block containing the
2030 * ivars declared in the class, or NULL if the class
2031 * declares no ivars. Caller must free the block.
2032 * Does not copy any superclass's ivars.
2033 **********************************************************************/
2034 Ivar *class_copyIvarList(Class cls_gen, unsigned int *outCount)
2035 {
2036 struct old_class *cls = oldcls(cls_gen);
2037 Ivar *result = NULL;
2038 unsigned int count = 0;
2039 int i;
2040
2041 if (!cls) {
2042 if (outCount) *outCount = 0;
2043 return NULL;
2044 }
2045
2046 if (cls->ivars) {
2047 count = cls->ivars->ivar_count;
2048 }
2049
2050 if (count > 0) {
2051 result = malloc((count+1) * sizeof(Ivar));
2052
2053 for (i = 0; i < cls->ivars->ivar_count; i++) {
2054 result[i] = (Ivar)&cls->ivars->ivar_list[i];
2055 }
2056 result[i] = NULL;
2057 }
2058
2059 if (outCount) *outCount = count;
2060 return result;
2061 }
2062
2063
2064 /***********************************************************************
2065 * objc_allocateClass.
2066 **********************************************************************/
2067 PRIVATE_EXTERN
2068 void set_superclass(struct old_class *cls, struct old_class *supercls,
2069 BOOL cls_is_new)
2070 {
2071 struct old_class *meta = cls->isa;
2072
2073 if (supercls) {
2074 cls->super_class = supercls;
2075 meta->super_class = supercls->isa;
2076 meta->isa = supercls->isa->isa;
2077
2078 // Propagate C++ cdtors from superclass.
2079 if (supercls->info & CLS_HAS_CXX_STRUCTORS) {
2080 if (cls_is_new) cls->info |= CLS_HAS_CXX_STRUCTORS;
2081 else _class_setInfo((Class)cls, CLS_HAS_CXX_STRUCTORS);
2082 }
2083
2084 // Superclass is no longer a leaf for cache flushing
2085 if (supercls->info & CLS_LEAF) {
2086 _class_clearInfo((Class)supercls, CLS_LEAF);
2087 _class_clearInfo((Class)supercls->isa, CLS_LEAF);
2088 }
2089 } else {
2090 cls->super_class = Nil; // superclass of root class is nil
2091 meta->super_class = cls; // superclass of root metaclass is root class
2092 meta->isa = meta; // metaclass of root metaclass is root metaclass
2093
2094 // Root class is never a leaf for cache flushing, because the
2095 // root metaclass is a subclass. (This could be optimized, but
2096 // is too uncommon to bother.)
2097 _class_clearInfo((Class)cls, CLS_LEAF);
2098 _class_clearInfo((Class)meta, CLS_LEAF);
2099 }
2100 }
2101
2102 // &UnsetLayout is the default ivar layout during class construction
2103 static const uint8_t UnsetLayout = 0;
2104
2105 Class objc_initializeClassPair(Class superclass_gen, const char *name, Class cls_gen, Class meta_gen)
2106 {
2107 struct old_class *supercls = oldcls(superclass_gen);
2108 struct old_class *cls = oldcls(cls_gen);
2109 struct old_class *meta = oldcls(meta_gen);
2110
2111 // Connect to superclasses and metaclasses
2112 cls->isa = meta;
2113 set_superclass(cls, supercls, YES);
2114
2115 // Set basic info
2116 cls->name = _strdup_internal(name);
2117 meta->name = _strdup_internal(name);
2118 cls->version = 0;
2119 meta->version = 7;
2120 cls->info = CLS_CLASS | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2121 meta->info = CLS_META | CLS_CONSTRUCTING | CLS_EXT | CLS_LEAF;
2122
2123 // Set instance size based on superclass.
2124 if (supercls) {
2125 cls->instance_size = supercls->instance_size;
2126 meta->instance_size = supercls->isa->instance_size;
2127 } else {
2128 cls->instance_size = sizeof(struct old_class *); // just an isa
2129 meta->instance_size = sizeof(struct old_class);
2130 }
2131
2132 // No ivars. No methods. Empty cache. No protocols. No layout. Empty ext.
2133 cls->ivars = NULL;
2134 cls->methodLists = NULL;
2135 cls->cache = (Cache)&_objc_empty_cache;
2136 cls->protocols = NULL;
2137 cls->ivar_layout = &UnsetLayout;
2138 cls->ext = NULL;
2139 allocateExt(cls);
2140 cls->ext->weak_ivar_layout = &UnsetLayout;
2141
2142 meta->ivars = NULL;
2143 meta->methodLists = NULL;
2144 meta->cache = (Cache)&_objc_empty_cache;
2145 meta->protocols = NULL;
2146 meta->ext = NULL;
2147
2148 return cls_gen;
2149 }
2150
2151 Class objc_allocateClassPair(Class superclass_gen, const char *name,
2152 size_t extraBytes)
2153 {
2154 struct old_class *supercls = oldcls(superclass_gen);
2155 Class cls, meta;
2156
2157 if (objc_getClass(name)) return NO;
2158 // fixme reserve class name against simultaneous allocation
2159
2160 if (supercls && (supercls->info & CLS_CONSTRUCTING)) {
2161 // Can't make subclass of an in-construction class
2162 return NO;
2163 }
2164
2165 // Allocate new classes.
2166 if (supercls) {
2167 cls = _calloc_class(_class_getInstanceSize((Class)supercls->isa) + extraBytes);
2168 meta = _calloc_class(_class_getInstanceSize((Class)supercls->isa->isa) + extraBytes);
2169 } else {
2170 cls = _calloc_class(sizeof(struct old_class) + extraBytes);
2171 meta = _calloc_class(sizeof(struct old_class) + extraBytes);
2172 }
2173
2174
2175 objc_initializeClassPair(superclass_gen, name, cls, meta);
2176
2177 return (Class)cls;
2178 }
2179
2180
2181 void objc_registerClassPair(Class cls_gen)
2182 {
2183 struct old_class *cls = oldcls(cls_gen);
2184
2185 if ((cls->info & CLS_CONSTRUCTED) ||
2186 (cls->isa->info & CLS_CONSTRUCTED))
2187 {
2188 _objc_inform("objc_registerClassPair: class '%s' was already "
2189 "registered!", cls->name);
2190 return;
2191 }
2192
2193 if (!(cls->info & CLS_CONSTRUCTING) ||
2194 !(cls->isa->info & CLS_CONSTRUCTING))
2195 {
2196 _objc_inform("objc_registerClassPair: class '%s' was not "
2197 "allocated with objc_allocateClassPair!", cls->name);
2198 return;
2199 }
2200
2201 if (ISMETA(cls)) {
2202 _objc_inform("objc_registerClassPair: class '%s' is a metaclass, "
2203 "not a class!", cls->name);
2204 return;
2205 }
2206
2207 mutex_lock(&classLock);
2208
2209 // Build ivar layouts
2210 if (UseGC) {
2211 if (cls->ivar_layout != &UnsetLayout) {
2212 // Class builder already called class_setIvarLayout.
2213 }
2214 else if (!cls->super_class) {
2215 // Root class. Scan conservatively (should be isa ivar only).
2216 cls->ivar_layout = NULL;
2217 }
2218 else if (cls->ivars == NULL) {
2219 // No local ivars. Use superclass's layout.
2220 cls->ivar_layout =
2221 _ustrdup_internal(cls->super_class->ivar_layout);
2222 }
2223 else {
2224 // Has local ivars. Build layout based on superclass.
2225 struct old_class *supercls = cls->super_class;
2226 const uint8_t *superlayout =
2227 class_getIvarLayout((Class)supercls);
2228 layout_bitmap bitmap =
2229 layout_bitmap_create(superlayout, supercls->instance_size,
2230 cls->instance_size, NO);
2231 int i;
2232 for (i = 0; i < cls->ivars->ivar_count; i++) {
2233 struct old_ivar *iv = &cls->ivars->ivar_list[i];
2234 layout_bitmap_set_ivar(bitmap, iv->ivar_type, iv->ivar_offset);
2235 }
2236 cls->ivar_layout = layout_string_create(bitmap);
2237 layout_bitmap_free(bitmap);
2238 }
2239
2240 if (cls->ext->weak_ivar_layout != &UnsetLayout) {
2241 // Class builder already called class_setWeakIvarLayout.
2242 }
2243 else if (!cls->super_class) {
2244 // Root class. No weak ivars (should be isa ivar only)
2245 cls->ext->weak_ivar_layout = NULL;
2246 }
2247 else if (cls->ivars == NULL) {
2248 // No local ivars. Use superclass's layout.
2249 const uint8_t *weak =
2250 class_getWeakIvarLayout((Class)cls->super_class);
2251 if (weak) {
2252 cls->ext->weak_ivar_layout = _ustrdup_internal(weak);
2253 } else {
2254 cls->ext->weak_ivar_layout = NULL;
2255 }
2256 }
2257 else {
2258 // Has local ivars. Build layout based on superclass.
2259 // No way to add weak ivars yet.
2260 const uint8_t *weak =
2261 class_getWeakIvarLayout((Class)cls->super_class);
2262 if (weak) {
2263 cls->ext->weak_ivar_layout = _ustrdup_internal(weak);
2264 } else {
2265 cls->ext->weak_ivar_layout = NULL;
2266 }
2267 }
2268 }
2269
2270 // Clear "under construction" bit, set "done constructing" bit
2271 cls->info &= ~CLS_CONSTRUCTING;
2272 cls->isa->info &= ~CLS_CONSTRUCTING;
2273 cls->info |= CLS_CONSTRUCTED;
2274 cls->isa->info |= CLS_CONSTRUCTED;
2275
2276 NXHashInsertIfAbsent(class_hash, cls);
2277 objc_addRegisteredClass((Class)cls);
2278 //objc_addRegisteredClass(cls->isa); if we ever allocate classes from GC
2279
2280 mutex_unlock(&classLock);
2281 }
2282
2283
2284 Class objc_duplicateClass(Class orig_gen, const char *name, size_t extraBytes)
2285 {
2286 unsigned int count, i;
2287 struct old_method **originalMethods;
2288 struct old_method_list *duplicateMethods;
2289 struct old_class *original = oldcls(orig_gen);
2290 // Don't use sizeof(struct objc_class) here because
2291 // instance_size has historically contained two extra words,
2292 // and instance_size is what objc_getIndexedIvars() actually uses.
2293 struct old_class *duplicate = (struct old_class *)
2294 _calloc_class(_class_getInstanceSize((Class)original->isa) + extraBytes);
2295
2296 duplicate->isa = original->isa;
2297 duplicate->super_class = original->super_class;
2298 duplicate->name = strdup(name);
2299 duplicate->version = original->version;
2300 duplicate->info = original->info & (CLS_CLASS|CLS_META|CLS_INITIALIZED|CLS_JAVA_HYBRID|CLS_JAVA_CLASS|CLS_HAS_CXX_STRUCTORS|CLS_HAS_LOAD_METHOD);
2301 duplicate->instance_size = original->instance_size;
2302 duplicate->ivars = original->ivars;
2303 // methodLists handled below
2304 duplicate->cache = (Cache)&_objc_empty_cache;
2305 duplicate->protocols = original->protocols;
2306 if (original->info & CLS_EXT) {
2307 duplicate->info |= original->info & (CLS_EXT|CLS_NO_PROPERTY_ARRAY);
2308 duplicate->ivar_layout = original->ivar_layout;
2309 if (original->ext) {
2310 duplicate->ext = _malloc_internal(original->ext->size);
2311 memcpy(duplicate->ext, original->ext, original->ext->size);
2312 } else {
2313 duplicate->ext = NULL;
2314 }
2315 }
2316
2317 // Method lists are deep-copied so they can be stomped.
2318 originalMethods = (struct old_method **)
2319 class_copyMethodList(orig_gen, &count);
2320 if (originalMethods) {
2321 duplicateMethods = (struct old_method_list *)
2322 calloc(sizeof(struct old_method_list) +
2323 (count-1)*sizeof(struct old_method), 1);
2324 duplicateMethods->obsolete = fixed_up_method_list;
2325 duplicateMethods->method_count = count;
2326 for (i = 0; i < count; i++) {
2327 duplicateMethods->method_list[i] = *(originalMethods[i]);
2328 }
2329 duplicate->methodLists = (struct old_method_list **)duplicateMethods;
2330 duplicate->info |= CLS_NO_METHOD_ARRAY;
2331 free(originalMethods);
2332 }
2333
2334 mutex_lock(&classLock);
2335 NXHashInsert(class_hash, duplicate);
2336 objc_addRegisteredClass((Class)duplicate);
2337 mutex_unlock(&classLock);
2338
2339 return (Class)duplicate;
2340 }
2341
2342
2343 void objc_disposeClassPair(Class cls_gen)
2344 {
2345 struct old_class *cls = oldcls(cls_gen);
2346
2347 if (!(cls->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)) ||
2348 !(cls->isa->info & (CLS_CONSTRUCTED|CLS_CONSTRUCTING)))
2349 {
2350 // class not allocated with objc_allocateClassPair
2351 // disposing still-unregistered class is OK!
2352 _objc_inform("objc_disposeClassPair: class '%s' was not "
2353 "allocated with objc_allocateClassPair!", cls->name);
2354 return;
2355 }
2356
2357 if (ISMETA(cls)) {
2358 _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
2359 "not a class!", cls->name);
2360 return;
2361 }
2362
2363 mutex_lock(&classLock);
2364 NXHashRemove(class_hash, cls);
2365 objc_removeRegisteredClass((Class)cls);
2366 unload_class(cls->isa);
2367 unload_class(cls);
2368 mutex_unlock(&classLock);
2369 }
2370
2371
2372
2373 /***********************************************************************
2374 * _class_createInstanceFromZone. Allocate an instance of the
2375 * specified class with the specified number of bytes for indexed
2376 * variables, in the specified zone. The isa field is set to the
2377 * class, C++ default constructors are called, and all other fields are zeroed.
2378 **********************************************************************/
2379 PRIVATE_EXTERN id
2380 _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
2381 {
2382 id obj;
2383 size_t size;
2384
2385 // Can't create something for nothing
2386 if (!cls) return nil;
2387
2388 // Allocate and initialize
2389 size = _class_getInstanceSize(cls) + extraBytes;
2390
2391 // CF requires all objects be at least 16 bytes.
2392 if (size < 16) size = 16;
2393
2394 #if SUPPORT_GC
2395 if (UseGC) {
2396 obj = (id)auto_zone_allocate_object(gc_zone, size,
2397 AUTO_OBJECT_SCANNED, 0, 1);
2398 } else
2399 #endif
2400 if (zone) {
2401 obj = (id)malloc_zone_calloc (zone, 1, size);
2402 } else {
2403 obj = (id)calloc(1, size);
2404 }
2405 if (!obj) return nil;
2406
2407 obj->isa = cls;
2408
2409 if (_class_hasCxxStructors(cls)) {
2410 obj = _objc_constructOrFree(cls, obj);
2411 }
2412
2413 return obj;
2414 }
2415
2416
2417 /***********************************************************************
2418 * _class_createInstance. Allocate an instance of the specified
2419 * class with the specified number of bytes for indexed variables, in
2420 * the default zone, using _class_createInstanceFromZone.
2421 **********************************************************************/
2422 static id _class_createInstance(Class cls, size_t extraBytes)
2423 {
2424 return _class_createInstanceFromZone (cls, extraBytes, NULL);
2425 }
2426
2427
2428 static id _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
2429 {
2430 id obj;
2431 size_t size;
2432
2433 if (!oldObj) return nil;
2434
2435 obj = (*_zoneAlloc)(oldObj->isa, extraBytes, zone);
2436 size = _class_getInstanceSize(oldObj->isa) + extraBytes;
2437
2438 // fixme need C++ copy constructor
2439 objc_memmove_collectable(obj, oldObj, size);
2440
2441 #if SUPPORT_GC
2442 if (UseGC) gc_fixup_weakreferences(obj, oldObj);
2443 #endif
2444
2445 return obj;
2446 }
2447
2448
2449 /***********************************************************************
2450 * objc_destructInstance
2451 * Destroys an instance without freeing memory.
2452 * Calls C++ destructors.
2453 * Removes associative references.
2454 * Returns `obj`. Does nothing if `obj` is nil.
2455 * Be warned that GC DOES NOT CALL THIS. If you edit this, also edit finalize.
2456 * CoreFoundation and other clients do call this under GC.
2457 **********************************************************************/
2458 void *objc_destructInstance(id obj)
2459 {
2460 if (obj) {
2461 Class isa = _object_getClass(obj);
2462
2463 if (_class_hasCxxStructors(isa)) {
2464 object_cxxDestruct(obj);
2465 }
2466
2467 if (_class_instancesHaveAssociatedObjects(isa)) {
2468 _object_remove_assocations(obj);
2469 }
2470
2471 if (!UseGC) objc_clear_deallocating(obj);
2472 }
2473
2474 return obj;
2475 }
2476
2477 static id
2478 _object_dispose(id anObject)
2479 {
2480 if (anObject==nil) return nil;
2481
2482 objc_destructInstance(anObject);
2483
2484 #if SUPPORT_GC
2485 if (UseGC) {
2486 auto_zone_retain(gc_zone, anObject); // gc free expects rc==1
2487 } else
2488 #endif
2489 {
2490 // only clobber isa for non-gc
2491 anObject->isa = _objc_getFreedObjectClass ();
2492 }
2493 free(anObject);
2494 return nil;
2495 }
2496
2497 static id _object_copy(id oldObj, size_t extraBytes)
2498 {
2499 void *z = malloc_zone_from_ptr(oldObj);
2500 return _object_copyFromZone(oldObj, extraBytes,
2501 z ? z : malloc_default_zone());
2502 }
2503
2504 static id _object_reallocFromZone(id anObject, size_t nBytes,
2505 void *zone)
2506 {
2507 id newObject;
2508 Class tmp;
2509
2510 if (anObject == nil)
2511 __objc_error(nil, "reallocating nil object");
2512
2513 if (anObject->isa == _objc_getFreedObjectClass ())
2514 __objc_error(anObject, "reallocating freed object");
2515
2516 if (nBytes < _class_getInstanceSize(anObject->isa))
2517 __objc_error(anObject, "(%s, %zu) requested size too small",
2518 object_getClassName(anObject), nBytes);
2519
2520 // fixme need C++ copy constructor
2521 // fixme GC copy
2522 // Make sure not to modify space that has been declared free
2523 tmp = anObject->isa;
2524 anObject->isa = _objc_getFreedObjectClass ();
2525 newObject = (id)malloc_zone_realloc(zone, anObject, nBytes);
2526 if (newObject) {
2527 newObject->isa = tmp;
2528 } else {
2529 // realloc failed, anObject is still alive
2530 anObject->isa = tmp;
2531 }
2532 return newObject;
2533 }
2534
2535
2536 static id _object_realloc(id anObject, size_t nBytes)
2537 {
2538 void *z = malloc_zone_from_ptr(anObject);
2539 return _object_reallocFromZone(anObject,
2540 nBytes,
2541 z ? z : malloc_default_zone());
2542 }
2543
2544 id (*_alloc)(Class, size_t) = _class_createInstance;
2545 id (*_copy)(id, size_t) = _object_copy;
2546 id (*_realloc)(id, size_t) = _object_realloc;
2547 id (*_dealloc)(id) = _object_dispose;
2548 id (*_zoneAlloc)(Class, size_t, void *) = _class_createInstanceFromZone;
2549 id (*_zoneCopy)(id, size_t, void *) = _object_copyFromZone;
2550 id (*_zoneRealloc)(id, size_t, void *) = _object_reallocFromZone;
2551 void (*_error)(id, const char *, va_list) = _objc_error;
2552
2553
2554 id class_createInstance(Class cls, size_t extraBytes)
2555 {
2556 if (UseGC) {
2557 return _class_createInstance(cls, extraBytes);
2558 } else {
2559 return (*_alloc)(cls, extraBytes);
2560 }
2561 }
2562
2563 id class_createInstanceFromZone(Class cls, size_t extraBytes, void *z)
2564 {
2565 OBJC_WARN_DEPRECATED;
2566 if (UseGC) {
2567 return _class_createInstanceFromZone(cls, extraBytes, z);
2568 } else {
2569 return (*_zoneAlloc)(cls, extraBytes, z);
2570 }
2571 }
2572
2573 unsigned class_createInstances(Class cls, size_t extraBytes,
2574 id *results, unsigned num_requested)
2575 {
2576 if (UseGC || _alloc == &_class_createInstance) {
2577 return _class_createInstancesFromZone(cls, extraBytes, NULL,
2578 results, num_requested);
2579 } else {
2580 // _alloc in use, which isn't understood by the batch allocator
2581 return 0;
2582 }
2583 }
2584
2585 id object_copy(id obj, size_t extraBytes)
2586 {
2587 if (UseGC) return _object_copy(obj, extraBytes);
2588 else return (*_copy)(obj, extraBytes);
2589 }
2590
2591 id object_copyFromZone(id obj, size_t extraBytes, void *z)
2592 {
2593 OBJC_WARN_DEPRECATED;
2594 if (UseGC) return _object_copyFromZone(obj, extraBytes, z);
2595 else return (*_zoneCopy)(obj, extraBytes, z);
2596 }
2597
2598 id object_dispose(id obj)
2599 {
2600 if (UseGC) return _object_dispose(obj);
2601 else return (*_dealloc)(obj);
2602 }
2603
2604 id object_realloc(id obj, size_t nBytes)
2605 {
2606 OBJC_WARN_DEPRECATED;
2607 if (UseGC) return _object_realloc(obj, nBytes);
2608 else return (*_realloc)(obj, nBytes);
2609 }
2610
2611 id object_reallocFromZone(id obj, size_t nBytes, void *z)
2612 {
2613 OBJC_WARN_DEPRECATED;
2614 if (UseGC) return _object_reallocFromZone(obj, nBytes, z);
2615 else return (*_zoneRealloc)(obj, nBytes, z);
2616 }
2617
2618
2619 // ProKit SPI
2620 Class class_setSuperclass(Class cls, Class newSuper)
2621 {
2622 Class oldSuper = cls->super_class;
2623 set_superclass(oldcls(cls), oldcls(newSuper), NO);
2624 flush_caches(cls, YES);
2625 return oldSuper;
2626 }
2627 #endif