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