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