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