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