2 * Copyright (c) 2005-2009 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
24 /***********************************************************************
26 * Support for new-ABI classes and images.
27 **********************************************************************/
31 #include "objc-private.h"
32 #include "objc-runtime-new.h"
33 #include "objc-file.h"
34 #include <objc/message.h>
35 #include <mach/shared_region.h>
37 #define newcls(cls) ((class_t *)cls)
38 #define newmethod(meth) ((method_t *)meth)
39 #define newivar(ivar) ((ivar_t *)ivar)
40 #define newcategory(cat) ((category_t *)cat)
41 #define newprotocol(p) ((protocol_t *)p)
42 #define newproperty(p) ((property_t *)p)
44 static const char *getName(class_t *cls);
45 static uint32_t unalignedInstanceSize(class_t *cls);
46 static uint32_t alignedInstanceSize(class_t *cls);
47 static BOOL isMetaClass(class_t *cls);
48 static class_t *getSuperclass(class_t *cls);
49 static void unload_class(class_t *cls, BOOL isMeta);
50 static class_t *setSuperclass(class_t *cls, class_t *newSuper);
51 static class_t *realizeClass(class_t *cls);
52 static void flushCaches(class_t *cls);
53 static void flushVtables(class_t *cls);
54 static method_t *getMethodNoSuper_nolock(class_t *cls, SEL sel);
55 static method_t *getMethod_nolock(class_t *cls, SEL sel);
56 static void changeInfo(class_t *cls, unsigned int set, unsigned int clear);
57 static IMP _method_getImplementation(method_t *m);
58 static BOOL hasCxxStructors(class_t *cls);
59 static IMP addMethod(class_t *cls, SEL name, IMP imp, const char *types, BOOL replace);
60 static NXHashTable *realizedClasses(void);
61 static BOOL isRRSelector(SEL sel);
63 PRIVATE_EXTERN id objc_noop_imp(id self, SEL _cmd __unused) {
67 /***********************************************************************
69 * Every lock used anywhere must be managed here.
70 * Locks not managed here may cause gdb deadlocks.
71 **********************************************************************/
72 PRIVATE_EXTERN rwlock_t runtimeLock = {0};
73 PRIVATE_EXTERN rwlock_t selLock = {0};
74 PRIVATE_EXTERN mutex_t cacheUpdateLock = MUTEX_INITIALIZER;
75 PRIVATE_EXTERN recursive_mutex_t loadMethodLock = RECURSIVE_MUTEX_INITIALIZER;
76 static int debugger_runtimeLock;
77 static int debugger_selLock;
78 static int debugger_cacheUpdateLock;
79 static int debugger_loadMethodLock;
83 PRIVATE_EXTERN void lock_init(void)
85 rwlock_init(&selLock);
86 rwlock_init(&runtimeLock);
87 recursive_mutex_init(&loadMethodLock);
91 /***********************************************************************
93 * Attempt to acquire some locks for debugger mode.
94 * Returns 0 if debugger mode failed because too many locks are unavailable.
96 * Locks successfully acquired are held until endDebuggerMode().
97 * Locks not acquired are off-limits until endDebuggerMode(); any
98 * attempt to manipulate them will cause a trap.
99 * Locks not handled here may cause deadlocks in gdb.
100 **********************************************************************/
101 PRIVATE_EXTERN int startDebuggerMode(void)
103 int result = DEBUGGER_FULL;
105 // runtimeLock is required (can't do much without it)
106 if (rwlock_try_write(&runtimeLock)) {
107 debugger_runtimeLock = RDWR;
108 } else if (rwlock_try_read(&runtimeLock)) {
109 debugger_runtimeLock = RDONLY;
110 result = DEBUGGER_PARTIAL;
115 // cacheUpdateLock is required (must not fail a necessary cache flush)
116 // must be AFTER runtimeLock to avoid lock inversion
117 if (mutex_try_lock(&cacheUpdateLock)) {
118 debugger_cacheUpdateLock = RDWR;
120 rwlock_unlock(&runtimeLock, debugger_runtimeLock);
121 debugger_runtimeLock = 0;
125 // side table locks are not optional
126 if (!noSideTableLocksHeld()) {
127 rwlock_unlock(&runtimeLock, debugger_runtimeLock);
128 mutex_unlock(&cacheUpdateLock);
129 debugger_runtimeLock = 0;
133 // selLock is optional
134 if (rwlock_try_write(&selLock)) {
135 debugger_selLock = RDWR;
136 } else if (rwlock_try_read(&selLock)) {
137 debugger_selLock = RDONLY;
138 result = DEBUGGER_PARTIAL;
140 debugger_selLock = 0;
141 result = DEBUGGER_PARTIAL;
144 // loadMethodLock is optional
145 if (recursive_mutex_try_lock(&loadMethodLock)) {
146 debugger_loadMethodLock = RDWR;
148 debugger_loadMethodLock = 0;
149 result = DEBUGGER_PARTIAL;
155 /***********************************************************************
157 * Relinquish locks acquired in startDebuggerMode().
158 **********************************************************************/
159 PRIVATE_EXTERN void endDebuggerMode(void)
161 assert(debugger_runtimeLock != 0);
163 rwlock_unlock(&runtimeLock, debugger_runtimeLock);
164 debugger_runtimeLock = 0;
166 rwlock_unlock(&selLock, debugger_selLock);
167 debugger_selLock = 0;
169 assert(debugger_cacheUpdateLock == RDWR);
170 mutex_unlock(&cacheUpdateLock);
171 debugger_cacheUpdateLock = 0;
173 if (debugger_loadMethodLock) {
174 recursive_mutex_unlock(&loadMethodLock);
175 debugger_loadMethodLock = 0;
179 /***********************************************************************
180 * isManagedDuringDebugger
181 * Returns YES if the given lock is handled specially during debugger
182 * mode (i.e. debugger mode tries to acquire it).
183 **********************************************************************/
184 PRIVATE_EXTERN BOOL isManagedDuringDebugger(void *lock)
186 if (lock == &selLock) return YES;
187 if (lock == &cacheUpdateLock) return YES;
188 if (lock == &runtimeLock) return YES;
189 if (lock == &loadMethodLock) return YES;
193 /***********************************************************************
194 * isLockedDuringDebugger
195 * Returns YES if the given mutex was acquired by debugger mode.
196 * Locking a managed mutex during debugger mode causes a trap unless
198 **********************************************************************/
199 PRIVATE_EXTERN BOOL isLockedDuringDebugger(void *lock)
201 assert(DebuggerMode);
203 if (lock == &cacheUpdateLock) return YES;
204 if (lock == (mutex_t *)&loadMethodLock) return YES;
209 /***********************************************************************
210 * isReadingDuringDebugger
211 * Returns YES if the given rwlock was read-locked by debugger mode.
212 * Read-locking a managed rwlock during debugger mode causes a trap unless
214 **********************************************************************/
215 PRIVATE_EXTERN BOOL isReadingDuringDebugger(rwlock_t *lock)
217 assert(DebuggerMode);
219 // read-lock is allowed even if debugger mode actually write-locked it
220 if (debugger_runtimeLock && lock == &runtimeLock) return YES;
221 if (debugger_selLock && lock == &selLock) return YES;
226 /***********************************************************************
227 * isWritingDuringDebugger
228 * Returns YES if the given rwlock was write-locked by debugger mode.
229 * Write-locking a managed rwlock during debugger mode causes a trap unless
231 **********************************************************************/
232 PRIVATE_EXTERN BOOL isWritingDuringDebugger(rwlock_t *lock)
234 assert(DebuggerMode);
236 if (debugger_runtimeLock == RDWR && lock == &runtimeLock) return YES;
237 if (debugger_selLock == RDWR && lock == &selLock) return YES;
243 /***********************************************************************
246 * Every class gets a vtable pointer. The vtable is an array of IMPs.
247 * The selectors represented in the vtable are the same for all classes
248 * (i.e. no class has a bigger or smaller vtable).
249 * Each vtable index has an associated trampoline which dispatches to
250 * the IMP at that index for the receiver class's vtable (after
251 * checking for NULL). Dispatch fixup uses these trampolines instead
253 * Fragility: The vtable size and list of selectors is chosen at launch
254 * time. No compiler-generated code depends on any particular vtable
255 * configuration, or even the use of vtable dispatch at all.
256 * Memory size: If a class's vtable is identical to its superclass's
257 * (i.e. the class overrides none of the vtable selectors), then
258 * the class points directly to its superclass's vtable. This means
259 * selectors to be included in the vtable should be chosen so they are
260 * (1) frequently called, but (2) not too frequently overridden. In
261 * particular, -dealloc is a bad choice.
262 * Forwarding: If a class doesn't implement some vtable selector, that
263 * selector's IMP is set to objc_msgSend in that class's vtable.
264 * +initialize: Each class keeps the default vtable (which always
265 * redirects to objc_msgSend) until its +initialize is completed.
266 * Otherwise, the first message to a class could be a vtable dispatch,
267 * and the vtable trampoline doesn't include +initialize checking.
268 * Changes: Categories, addMethod, and setImplementation all force vtable
269 * reconstruction for the class and all of its subclasses, if the
270 * vtable selectors are affected.
271 **********************************************************************/
273 /***********************************************************************
274 * ABI WARNING ABI WARNING ABI WARNING ABI WARNING ABI WARNING
275 * vtable_prototype on x86_64 steals %rax and does not clear %rdx on return
276 * This means vtable dispatch must never be used for vararg calls
277 * or very large return values.
278 * ABI WARNING ABI WARNING ABI WARNING ABI WARNING ABI WARNING
279 **********************************************************************/
284 X8(x) X8(x) X8(x) X8(x) X8(x) X8(x) X8(x) X8(x)
288 #define vtableMax 128
290 // hack to avoid conflicts with compiler's internal declaration
292 "\n .globl __objc_empty_vtable "
293 "\n __objc_empty_vtable:"
295 X128("\n .quad _objc_msgSend")
297 X128("\n .long _objc_msgSend")
303 // Trampoline descriptors for gdb.
305 objc_trampoline_header *gdb_objc_trampolines = NULL;
307 void gdb_objc_trampolines_changed(objc_trampoline_header *thdr) __attribute__((noinline));
308 void gdb_objc_trampolines_changed(objc_trampoline_header *thdr)
310 rwlock_assert_writing(&runtimeLock);
311 assert(thdr == gdb_objc_trampolines);
314 _objc_inform("VTABLES: gdb_objc_trampolines_changed(%p)", thdr);
318 // fixme workaround for rdar://6667753
319 static void appendTrampolines(objc_trampoline_header *thdr) __attribute__((noinline));
321 static void appendTrampolines(objc_trampoline_header *thdr)
323 rwlock_assert_writing(&runtimeLock);
324 assert(thdr->next == NULL);
326 if (gdb_objc_trampolines != thdr->next) {
327 thdr->next = gdb_objc_trampolines;
329 gdb_objc_trampolines = thdr;
331 gdb_objc_trampolines_changed(thdr);
334 // Vtable management.
336 static size_t vtableStrlen;
337 static size_t vtableCount;
338 static SEL *vtableSelectors;
339 static IMP *vtableTrampolines;
340 static const char * const defaultVtable[] = {
346 "respondsToSelector:",
358 static const char * const defaultVtableGC[] = {
364 "respondsToSelector:",
374 "countByEnumeratingWithState:objects:count:",
377 OBJC_EXTERN id objc_msgSend_vtable0(id, SEL, ...);
378 OBJC_EXTERN id objc_msgSend_vtable1(id, SEL, ...);
379 OBJC_EXTERN id objc_msgSend_vtable2(id, SEL, ...);
380 OBJC_EXTERN id objc_msgSend_vtable3(id, SEL, ...);
381 OBJC_EXTERN id objc_msgSend_vtable4(id, SEL, ...);
382 OBJC_EXTERN id objc_msgSend_vtable5(id, SEL, ...);
383 OBJC_EXTERN id objc_msgSend_vtable6(id, SEL, ...);
384 OBJC_EXTERN id objc_msgSend_vtable7(id, SEL, ...);
385 OBJC_EXTERN id objc_msgSend_vtable8(id, SEL, ...);
386 OBJC_EXTERN id objc_msgSend_vtable9(id, SEL, ...);
387 OBJC_EXTERN id objc_msgSend_vtable10(id, SEL, ...);
388 OBJC_EXTERN id objc_msgSend_vtable11(id, SEL, ...);
389 OBJC_EXTERN id objc_msgSend_vtable12(id, SEL, ...);
390 OBJC_EXTERN id objc_msgSend_vtable13(id, SEL, ...);
391 OBJC_EXTERN id objc_msgSend_vtable14(id, SEL, ...);
392 OBJC_EXTERN id objc_msgSend_vtable15(id, SEL, ...);
394 static IMP const defaultVtableTrampolines[] = {
395 objc_msgSend_vtable0,
396 objc_msgSend_vtable1,
397 objc_msgSend_vtable2,
398 objc_msgSend_vtable3,
399 objc_msgSend_vtable4,
400 objc_msgSend_vtable5,
401 objc_msgSend_vtable6,
402 objc_msgSend_vtable7,
403 objc_msgSend_vtable8,
404 objc_msgSend_vtable9,
405 objc_msgSend_vtable10,
406 objc_msgSend_vtable11,
407 objc_msgSend_vtable12,
408 objc_msgSend_vtable13,
409 objc_msgSend_vtable14,
410 objc_msgSend_vtable15,
412 extern objc_trampoline_header defaultVtableTrampolineDescriptors;
414 static void check_vtable_size(void) __unused;
415 static void check_vtable_size(void)
417 // Fail to compile if vtable sizes don't match.
418 int c1[sizeof(defaultVtableTrampolines)-sizeof(defaultVtable)] __unused;
419 int c2[sizeof(defaultVtable)-sizeof(defaultVtableTrampolines)] __unused;
420 int c3[sizeof(defaultVtableTrampolines)-sizeof(defaultVtableGC)] __unused;
421 int c4[sizeof(defaultVtableGC)-sizeof(defaultVtableTrampolines)] __unused;
423 // Fail to compile if vtableMax is too small
424 int c5[vtableMax - sizeof(defaultVtable)] __unused;
425 int c6[vtableMax - sizeof(defaultVtableGC)] __unused;
429 extern uint8_t vtable_prototype;
430 extern uint8_t vtable_ignored;
431 extern int vtable_prototype_size;
432 extern int vtable_prototype_index_offset;
433 extern int vtable_prototype_index2_offset;
434 extern int vtable_prototype_tagtable_offset;
435 extern int vtable_prototype_tagtable_size;
436 static size_t makeVtableTrampoline(uint8_t *dst, size_t index)
439 memcpy(dst, &vtable_prototype, vtable_prototype_size);
442 #if defined(__x86_64__)
443 if (index > 255) _objc_fatal("vtable_prototype busted");
445 // `jmpq *0x7fff(%rax)` ff a0 ff 7f
446 uint16_t *p = (uint16_t *)(dst + vtable_prototype_index_offset + 2);
447 if (*p != 0x7fff) _objc_fatal("vtable_prototype busted");
451 uint16_t *p = (uint16_t *)(dst + vtable_prototype_index2_offset + 2);
452 if (*p != 0x7fff) _objc_fatal("vtable_prototype busted");
456 # warning unknown architecture
459 // insert tagged isa table
460 #if defined(__x86_64__)
462 // `movq $0x1122334455667788, %r10` 49 ba 88 77 66 55 44 33 22 11
463 if (vtable_prototype_tagtable_size != 10) {
464 _objc_fatal("vtable_prototype busted");
466 uint8_t *p = (uint8_t *)(dst + vtable_prototype_tagtable_offset);
467 if (*p++ != 0x49) _objc_fatal("vtable_prototype busted");
468 if (*p++ != 0xba) _objc_fatal("vtable_prototype busted");
469 if (*(uintptr_t *)p != 0x1122334455667788) {
470 _objc_fatal("vtable_prototype busted");
472 uintptr_t addr = (uintptr_t)_objc_tagged_isa_table;
473 memcpy(p, &addr, sizeof(addr));
476 # warning unknown architecture
479 return vtable_prototype_size;
483 static void initVtables(void)
485 if (DisableVtables) {
487 _objc_inform("VTABLES: vtable dispatch disabled by OBJC_DISABLE_VTABLES");
490 vtableSelectors = NULL;
491 vtableTrampolines = NULL;
495 const char * const *names;
499 names = defaultVtableGC;
500 vtableCount = sizeof(defaultVtableGC) / sizeof(defaultVtableGC[0]);
502 names = defaultVtable;
503 vtableCount = sizeof(defaultVtable) / sizeof(defaultVtable[0]);
505 if (vtableCount > vtableMax) vtableCount = vtableMax;
507 vtableSelectors = (SEL*)_malloc_internal(vtableCount * sizeof(SEL));
508 vtableTrampolines = (IMP*)_malloc_internal(vtableCount * sizeof(IMP));
510 // Built-in trampolines and their descriptors
512 size_t defaultVtableTrampolineCount =
513 sizeof(defaultVtableTrampolines) / sizeof(defaultVtableTrampolines[0]);
515 // debug: use generated code for 3/4 of the table
516 // Disabled even in Debug builds to avoid breaking backtrace symbol names.
517 // defaultVtableTrampolineCount /= 4;
520 for (i = 0; i < defaultVtableTrampolineCount && i < vtableCount; i++) {
521 vtableSelectors[i] = sel_registerName(names[i]);
522 vtableTrampolines[i] = defaultVtableTrampolines[i];
524 appendTrampolines(&defaultVtableTrampolineDescriptors);
527 // Generated trampolines and their descriptors
529 if (vtableCount > defaultVtableTrampolineCount) {
530 // Memory for trampoline code
531 size_t generatedCount =
532 vtableCount - defaultVtableTrampolineCount;
534 const int align = 16;
536 round_page(sizeof(objc_trampoline_header) + align +
537 generatedCount * (sizeof(objc_trampoline_descriptor)
538 + vtable_prototype_size + align));
539 void *codeAddr = mmap(0, codeSize, PROT_READ|PROT_WRITE,
540 MAP_PRIVATE|MAP_ANON,
541 VM_MAKE_TAG(VM_MEMORY_OBJC_DISPATCHERS), 0);
542 uint8_t *t = (uint8_t *)codeAddr;
545 objc_trampoline_header *thdr = (objc_trampoline_header *)t;
546 thdr->headerSize = sizeof(objc_trampoline_header);
547 thdr->descSize = sizeof(objc_trampoline_descriptor);
548 thdr->descCount = (uint32_t)generatedCount;
551 // Trampoline descriptors
552 objc_trampoline_descriptor *tdesc = (objc_trampoline_descriptor *)(thdr+1);
553 t = (uint8_t *)&tdesc[generatedCount];
554 t += align - ((uintptr_t)t % align);
558 for (i = defaultVtableTrampolineCount, tdi = 0;
562 vtableSelectors[i] = sel_registerName(names[i]);
563 if (ignoreSelector(vtableSelectors[i])) {
564 vtableTrampolines[i] = (IMP)&vtable_ignored;
565 tdesc[tdi].offset = 0;
566 tdesc[tdi].flags = 0;
568 vtableTrampolines[i] = (IMP)t;
570 (uint32_t)((uintptr_t)t - (uintptr_t)&tdesc[tdi]);
572 OBJC_TRAMPOLINE_MESSAGE|OBJC_TRAMPOLINE_VTABLE;
574 t += makeVtableTrampoline(t, i);
575 t += align - ((uintptr_t)t % align);
579 appendTrampolines(thdr);
580 sys_icache_invalidate(codeAddr, codeSize);
581 mprotect(codeAddr, codeSize, PROT_READ|PROT_EXEC);
586 for (i = 0; i < vtableCount; i++) {
587 _objc_inform("VTABLES: vtable[%zu] %p %s",
588 i, vtableTrampolines[i],
589 sel_getName(vtableSelectors[i]));
593 if (PrintVtableImages) {
594 _objc_inform("VTABLE IMAGES: '#' implemented by class");
595 _objc_inform("VTABLE IMAGES: '-' inherited from superclass");
596 _objc_inform("VTABLE IMAGES: ' ' not implemented");
597 for (i = 0; i <= vtableCount; i++) {
598 char spaces[vtableCount+1+1];
600 for (j = 0; j < i; j++) {
604 _objc_inform("VTABLE IMAGES: %s%s", spaces,
605 i<vtableCount ? sel_getName(vtableSelectors[i]) : "");
609 if (PrintVtables || PrintVtableImages) {
611 for (i = 0; i < vtableCount; i++) {
612 vtableStrlen += strlen(sel_getName(vtableSelectors[i]));
618 static int vtable_getIndex(SEL sel)
621 for (i = 0; i < vtableCount; i++) {
622 if (vtableSelectors[i] == sel) return i;
627 static BOOL vtable_containsSelector(SEL sel)
629 return (vtable_getIndex(sel) < 0) ? NO : YES;
632 static void printVtableOverrides(class_t *cls, class_t *supercls)
634 char overrideMap[vtableCount+1];
638 size_t overridesBufferSize = vtableStrlen + 2*vtableCount + 1;
640 (char *)_calloc_internal(overridesBufferSize, 1);
641 for (i = 0; i < vtableCount; i++) {
642 if (ignoreSelector(vtableSelectors[i])) {
643 overrideMap[i] = '-';
646 if (getMethodNoSuper_nolock(cls, vtableSelectors[i])) {
647 strlcat(overrides, sel_getName(vtableSelectors[i]), overridesBufferSize);
648 strlcat(overrides, ", ", overridesBufferSize);
649 overrideMap[i] = '#';
650 } else if (getMethod_nolock(cls, vtableSelectors[i])) {
651 overrideMap[i] = '-';
653 overrideMap[i] = ' ';
657 _objc_inform("VTABLES: %s%s implements %s",
658 getName(cls), isMetaClass(cls) ? "(meta)" : "",
661 _free_internal(overrides);
664 for (i = 0; i < vtableCount; i++) {
665 overrideMap[i] = '#';
669 if (PrintVtableImages) {
670 overrideMap[vtableCount] = '\0';
671 _objc_inform("VTABLE IMAGES: %s %s%s", overrideMap,
672 getName(cls), isMetaClass(cls) ? "(meta)" : "");
676 /***********************************************************************
678 * Rebuilds vtable for cls, using superclass's vtable if appropriate.
679 * Assumes superclass's vtable is up to date.
680 * Does nothing to subclass vtables.
681 * Locking: runtimeLock must be held by the caller.
682 **********************************************************************/
683 static void updateVtable(class_t *cls, BOOL force)
685 rwlock_assert_writing(&runtimeLock);
687 // Keep default vtable until +initialize is complete.
688 // Default vtable redirects to objc_msgSend, which
689 // enforces +initialize locking.
690 if (!force && !_class_isInitialized((Class)cls)) {
693 _objc_inform("VTABLES: KEEPING DEFAULT vtable for "
694 "uninitialized class %s%s",
695 getName(cls), isMetaClass(cls) ? "(meta)" : "");
701 // Decide whether this class can share its superclass's vtable.
703 class_t *supercls = getSuperclass(cls);
704 BOOL needVtable = NO;
707 // Root classes always need a vtable
710 else if (cls->data()->flags & RW_SPECIALIZED_VTABLE) {
711 // Once you have your own vtable, you never go back
715 for (i = 0; i < vtableCount; i++) {
716 if (ignoreSelector(vtableSelectors[i])) continue;
717 method_t *m = getMethodNoSuper_nolock(cls, vtableSelectors[i]);
718 // assume any local implementation differs from super's
726 // Build a vtable for this class, or not.
730 _objc_inform("VTABLES: USING SUPERCLASS vtable for class %s%s",
731 getName(cls), isMetaClass(cls) ? "(meta)" : "");
733 cls->vtable = supercls->vtable;
737 _objc_inform("VTABLES: %s vtable for class %s%s",
738 (cls->data()->flags & RW_SPECIALIZED_VTABLE) ?
739 "UPDATING SPECIALIZED" : "CREATING SPECIALIZED",
740 getName(cls), isMetaClass(cls) ? "(meta)" : "");
742 if (PrintVtables || PrintVtableImages) {
743 printVtableOverrides(cls, supercls);
747 IMP *super_vtable = supercls ? supercls->vtable : &_objc_empty_vtable;
748 // fixme use msgForward (instead of msgSend from empty vtable) ?
750 if (cls->data()->flags & RW_SPECIALIZED_VTABLE) {
751 // update cls->vtable in place
752 new_vtable = cls->vtable;
753 assert(new_vtable != &_objc_empty_vtable);
756 new_vtable = (IMP*)malloc(vtableCount * sizeof(IMP));
757 changeInfo(cls, RW_SPECIALIZED_VTABLE, 0);
760 for (i = 0; i < vtableCount; i++) {
761 if (ignoreSelector(vtableSelectors[i])) {
762 new_vtable[i] = (IMP)&vtable_ignored;
764 method_t *m = getMethodNoSuper_nolock(cls, vtableSelectors[i]);
765 if (m) new_vtable[i] = _method_getImplementation(m);
766 else new_vtable[i] = super_vtable[i];
770 if (cls->vtable != new_vtable) {
771 // don't let other threads see uninitialized parts of new_vtable
773 cls->vtable = new_vtable;
782 static void initVtables(void)
785 _objc_inform("VTABLES: no vtables on this architecture");
789 static BOOL vtable_containsSelector(SEL sel)
794 static void updateVtable(class_t *cls, BOOL force)
808 category_pair_t list[0]; // variable-size
811 #define FOREACH_METHOD_LIST(_mlist, _cls, code) \
813 const method_list_t *_mlist; \
814 if (_cls->data()->methods) { \
815 method_list_t **_mlistp; \
816 for (_mlistp = _cls->data()->methods; *_mlistp; _mlistp++) { \
823 #define FOREACH_REALIZED_CLASS_AND_SUBCLASS(_c, _cls, code) \
825 rwlock_assert_writing(&runtimeLock); \
826 class_t *_top = _cls; \
827 class_t *_c = _top; \
831 if (_c->data()->firstSubclass) { \
832 _c = _c->data()->firstSubclass; \
834 while (!_c->data()->nextSiblingClass && _c != _top) { \
835 _c = getSuperclass(_c); \
837 if (_c == _top) break; \
838 _c = _c->data()->nextSiblingClass; \
842 /* nil means all realized classes */ \
843 NXHashTable *_classes = realizedClasses(); \
844 NXHashTable *_metaclasses = realizedMetaclasses(); \
845 NXHashState _state; \
846 _state = NXInitHashState(_classes); \
847 while (NXNextHashState(_classes, &_state, (void**)&_c)) \
851 _state = NXInitHashState(_metaclasses); \
852 while (NXNextHashState(_metaclasses, &_state, (void**)&_c)) \
861 Low two bits of mlist->entsize is used as the fixed-up marker.
862 PREOPTIMIZED VERSION:
863 Fixed-up method lists get entsize&3 == 3.
864 dyld shared cache sets this for method lists it preoptimizes.
865 UN-PREOPTIMIZED VERSION:
866 Fixed-up method lists get entsize&3 == 1.
867 dyld shared cache uses 3, but those aren't trusted.
870 static uint32_t fixed_up_method_list = 3;
873 disableSharedCacheOptimizations(void)
875 fixed_up_method_list = 1;
878 static BOOL isMethodListFixedUp(const method_list_t *mlist)
880 return (mlist->entsize_NEVER_USE & 3) == fixed_up_method_list;
883 static void setMethodListFixedUp(method_list_t *mlist)
885 rwlock_assert_writing(&runtimeLock);
886 assert(!isMethodListFixedUp(mlist));
887 mlist->entsize_NEVER_USE = (mlist->entsize_NEVER_USE & ~3) | fixed_up_method_list;
891 static size_t chained_property_list_size(const chained_property_list *plist)
893 return sizeof(chained_property_list) +
894 plist->count * sizeof(property_t);
898 static size_t protocol_list_size(const protocol_list_t *plist)
900 return sizeof(protocol_list_t) + plist->count * sizeof(protocol_t *);
904 // low bit used by dyld shared cache
905 static uint32_t method_list_entsize(const method_list_t *mlist)
907 return mlist->entsize_NEVER_USE & ~(uint32_t)3;
910 static size_t method_list_size(const method_list_t *mlist)
912 return sizeof(method_list_t) + (mlist->count-1)*method_list_entsize(mlist);
915 static method_t *method_list_nth(const method_list_t *mlist, uint32_t i)
917 return (method_t *)(i*method_list_entsize(mlist) + (char *)&mlist->first);
921 static size_t ivar_list_size(const ivar_list_t *ilist)
923 return sizeof(ivar_list_t) + (ilist->count-1) * ilist->entsize;
926 static ivar_t *ivar_list_nth(const ivar_list_t *ilist, uint32_t i)
928 return (ivar_t *)(i*ilist->entsize + (char *)&ilist->first);
932 // part of ivar_t, with non-deprecated alignment
940 static uint32_t ivar_alignment(const ivar_t *ivar)
942 uint32_t alignment = ((ivar_alignment_t *)ivar)->alignment;
943 if (alignment == (uint32_t)-1) alignment = (uint32_t)WORD_SHIFT;
948 static method_list_t *cat_method_list(const category_t *cat, BOOL isMeta)
950 if (!cat) return NULL;
952 if (isMeta) return cat->classMethods;
953 else return cat->instanceMethods;
956 static uint32_t cat_method_count(const category_t *cat, BOOL isMeta)
958 method_list_t *cmlist = cat_method_list(cat, isMeta);
959 return cmlist ? cmlist->count : 0;
962 static method_t *cat_method_nth(const category_t *cat, BOOL isMeta, uint32_t i)
964 method_list_t *cmlist = cat_method_list(cat, isMeta);
965 if (!cmlist) return NULL;
967 return method_list_nth(cmlist, i);
972 property_list_nth(const property_list_t *plist, uint32_t i)
974 return (property_t *)(i*plist->entsize + (char *)&plist->first);
977 // fixme don't chain property lists
978 typedef struct chained_property_list {
979 struct chained_property_list *next;
981 property_t list[0]; // variable-size
982 } chained_property_list;
985 static void try_free(const void *p)
987 if (p && malloc_size(p)) free((void *)p);
991 /***********************************************************************
993 * Reallocates rw->ro if necessary to make it writeable.
994 * Locking: runtimeLock must be held by the caller.
995 **********************************************************************/
996 static class_ro_t *make_ro_writeable(class_rw_t *rw)
998 rwlock_assert_writing(&runtimeLock);
1000 if (rw->flags & RW_COPIED_RO) {
1001 // already writeable, do nothing
1003 class_ro_t *ro = (class_ro_t *)
1004 _memdup_internal(rw->ro, sizeof(*rw->ro));
1006 rw->flags |= RW_COPIED_RO;
1008 return (class_ro_t *)rw->ro;
1012 /***********************************************************************
1013 * unattachedCategories
1014 * Returns the class => categories map of unattached categories.
1015 * Locking: runtimeLock must be held by the caller.
1016 **********************************************************************/
1017 static NXMapTable *unattachedCategories(void)
1019 rwlock_assert_writing(&runtimeLock);
1021 static NXMapTable *category_map = NULL;
1023 if (category_map) return category_map;
1025 // fixme initial map size
1026 category_map = NXCreateMapTableFromZone(NXPtrValueMapPrototype, 16,
1027 _objc_internal_zone());
1029 return category_map;
1033 /***********************************************************************
1034 * addUnattachedCategoryForClass
1035 * Records an unattached category.
1036 * Locking: runtimeLock must be held by the caller.
1037 **********************************************************************/
1038 static void addUnattachedCategoryForClass(category_t *cat, class_t *cls,
1039 header_info *catHeader)
1041 rwlock_assert_writing(&runtimeLock);
1043 BOOL catFromBundle = (catHeader->mhdr->filetype == MH_BUNDLE) ? YES: NO;
1045 // DO NOT use cat->cls!
1046 // cls may be cat->cls->isa, or cat->cls may have been remapped.
1047 NXMapTable *cats = unattachedCategories();
1048 category_list *list;
1050 list = (category_list *)NXMapGet(cats, cls);
1052 list = (category_list *)
1053 _calloc_internal(sizeof(*list) + sizeof(list->list[0]), 1);
1055 list = (category_list *)
1056 _realloc_internal(list, sizeof(*list) + sizeof(list->list[0]) * (list->count + 1));
1058 list->list[list->count++] = (category_pair_t){cat, catFromBundle};
1059 NXMapInsert(cats, cls, list);
1063 /***********************************************************************
1064 * removeUnattachedCategoryForClass
1065 * Removes an unattached category.
1066 * Locking: runtimeLock must be held by the caller.
1067 **********************************************************************/
1068 static void removeUnattachedCategoryForClass(category_t *cat, class_t *cls)
1070 rwlock_assert_writing(&runtimeLock);
1072 // DO NOT use cat->cls!
1073 // cls may be cat->cls->isa, or cat->cls may have been remapped.
1074 NXMapTable *cats = unattachedCategories();
1075 category_list *list;
1077 list = (category_list *)NXMapGet(cats, cls);
1081 for (i = 0; i < list->count; i++) {
1082 if (list->list[i].cat == cat) {
1083 // shift entries to preserve list order
1084 memmove(&list->list[i], &list->list[i+1],
1085 (list->count-i-1) * sizeof(list->list[i]));
1093 /***********************************************************************
1094 * unattachedCategoriesForClass
1095 * Returns the list of unattached categories for a class, and
1096 * deletes them from the list.
1097 * The result must be freed by the caller.
1098 * Locking: runtimeLock must be held by the caller.
1099 **********************************************************************/
1100 static category_list *unattachedCategoriesForClass(class_t *cls)
1102 rwlock_assert_writing(&runtimeLock);
1103 return (category_list *)NXMapRemove(unattachedCategories(), cls);
1107 /***********************************************************************
1109 * Returns YES if class cls has been realized.
1110 * Locking: To prevent concurrent realization, hold runtimeLock.
1111 **********************************************************************/
1112 static BOOL isRealized(class_t *cls)
1114 return (cls->data()->flags & RW_REALIZED) ? YES : NO;
1118 /***********************************************************************
1120 * Returns YES if class cls is an unrealized future class.
1121 * Locking: To prevent concurrent realization, hold runtimeLock.
1122 **********************************************************************/
1124 // currently used in asserts only
1125 static BOOL isFuture(class_t *cls)
1127 return (cls->data()->flags & RW_FUTURE) ? YES : NO;
1132 /***********************************************************************
1134 * Implementation of PrintReplacedMethods / OBJC_PRINT_REPLACED_METHODS.
1135 * Warn about methods from cats that override other methods in cats or cls.
1136 * Assumes no methods from cats have been added to cls yet.
1137 **********************************************************************/
1138 static void printReplacements(class_t *cls, category_list *cats)
1141 BOOL isMeta = isMetaClass(cls);
1145 // Newest categories are LAST in cats
1146 // Later categories override earlier ones.
1147 for (c = 0; c < cats->count; c++) {
1148 category_t *cat = cats->list[c].cat;
1149 uint32_t cmCount = cat_method_count(cat, isMeta);
1151 for (m = 0; m < cmCount; m++) {
1153 method_t *meth2 = NULL;
1154 method_t *meth = cat_method_nth(cat, isMeta, m);
1155 SEL s = sel_registerName((const char *)meth->name);
1157 // Don't warn about GC-ignored selectors
1158 if (ignoreSelector(s)) continue;
1160 // Look for method in earlier categories
1161 for (c2 = 0; c2 < c; c2++) {
1162 category_t *cat2 = cats->list[c2].cat;
1163 uint32_t cm2Count = cat_method_count(cat2, isMeta);
1164 for (m2 = 0; m2 < cm2Count; m2++) {
1165 meth2 = cat_method_nth(cat2, isMeta, m2);
1166 SEL s2 = sel_registerName((const char *)meth2->name);
1167 if (s == s2) goto whine;
1171 // Look for method in cls
1172 FOREACH_METHOD_LIST(mlist, cls, {
1173 for (m2 = 0; m2 < mlist->count; m2++) {
1174 meth2 = method_list_nth(mlist, m2);
1175 SEL s2 = sel_registerName((const char *)meth2->name);
1176 if (s == s2) goto whine;
1180 // Didn't find any override.
1184 // Found an override.
1185 logReplacedMethod(getName(cls), s, isMetaClass(cls), cat->name,
1186 _method_getImplementation(meth2),
1187 _method_getImplementation(meth));
1193 static BOOL isBundleClass(class_t *cls)
1195 return (cls->data()->ro->flags & RO_FROM_BUNDLE) ? YES : NO;
1199 static method_list_t *
1200 fixupMethodList(method_list_t *mlist, BOOL bundleCopy)
1202 assert(!isMethodListFixedUp(mlist));
1204 mlist = (method_list_t *)
1205 _memdup_internal(mlist, method_list_size(mlist));
1207 // fixme lock less in attachMethodLists ?
1210 // Unique selectors in list.
1212 for (m = 0; m < mlist->count; m++) {
1213 method_t *meth = method_list_nth(mlist, m);
1214 SEL sel = sel_registerNameNoLock((const char *)meth->name, bundleCopy);
1217 if (ignoreSelector(sel)) {
1218 meth->imp = (IMP)&_objc_ignored_method;
1224 // Sort by selector address.
1225 method_t::SortBySELAddress sorter;
1226 std::stable_sort(mlist->begin(), mlist->end(), sorter);
1228 // Mark method list as uniqued and sorted
1229 setMethodListFixedUp(mlist);
1236 attachMethodLists(class_t *cls, method_list_t **addedLists, int addedCount,
1237 BOOL methodsFromBundle, BOOL *inoutVtablesAffected)
1239 rwlock_assert_writing(&runtimeLock);
1241 // Don't scan redundantly
1242 BOOL scanForCustomRR = !UseGC && !cls->hasCustomRR();
1244 // Method list array is NULL-terminated.
1245 // Some elements of lists are NULL; we must filter them out.
1247 method_list_t **oldLists = cls->data()->methods;
1250 while (oldLists[oldCount]) oldCount++;
1253 int newCount = oldCount + 1; // including NULL terminator
1254 for (int i = 0; i < addedCount; i++) {
1255 if (addedLists[i]) newCount++; // only non-NULL entries get added
1258 method_list_t **newLists = (method_list_t **)
1259 _malloc_internal(newCount * sizeof(*newLists));
1261 // Add method lists to array.
1262 // Reallocate un-fixed method lists.
1263 // The new methods are PREPENDED to the method list array.
1267 for (i = 0; i < addedCount; i++) {
1268 method_list_t *mlist = addedLists[i];
1269 if (!mlist) continue;
1271 // Fixup selectors if necessary
1272 if (!isMethodListFixedUp(mlist)) {
1273 mlist = fixupMethodList(mlist, methodsFromBundle);
1276 // Scan for vtable updates
1277 if (inoutVtablesAffected && !*inoutVtablesAffected) {
1279 for (m = 0; m < mlist->count; m++) {
1280 SEL sel = method_list_nth(mlist, m)->name;
1281 if (vtable_containsSelector(sel)) {
1282 *inoutVtablesAffected = YES;
1288 // Scan for method implementations tracked by the class's flags
1289 if (scanForCustomRR) {
1291 for (m = 0; m < mlist->count; m++) {
1292 SEL sel = method_list_nth(mlist, m)->name;
1293 if (isRRSelector(sel)) {
1294 cls->setHasCustomRR();
1295 scanForCustomRR = NO;
1301 // Fill method list array
1302 newLists[newCount++] = mlist;
1305 // Copy old methods to the method list array
1306 for (i = 0; i < oldCount; i++) {
1307 newLists[newCount++] = oldLists[i];
1309 if (oldLists) free(oldLists);
1312 newLists[newCount++] = NULL;
1313 cls->data()->methods = newLists;
1317 attachCategoryMethods(class_t *cls, category_list *cats,
1318 BOOL *inoutVtablesAffected)
1321 if (PrintReplacedMethods) printReplacements(cls, cats);
1323 BOOL isMeta = isMetaClass(cls);
1324 method_list_t **mlists = (method_list_t **)
1325 _malloc_internal(cats->count * sizeof(*mlists));
1327 // Count backwards through cats to get newest categories first
1329 int i = cats->count;
1330 BOOL fromBundle = NO;
1332 method_list_t *mlist = cat_method_list(cats->list[i].cat, isMeta);
1334 mlists[mcount++] = mlist;
1335 fromBundle |= cats->list[i].fromBundle;
1339 attachMethodLists(cls, mlists, mcount, fromBundle, inoutVtablesAffected);
1341 _free_internal(mlists);
1346 static chained_property_list *
1347 buildPropertyList(const property_list_t *plist, category_list *cats, BOOL isMeta)
1349 // Do NOT use cat->cls! It may have been remapped.
1350 chained_property_list *newlist;
1354 // Count properties in all lists.
1355 if (plist) count = plist->count;
1357 for (c = 0; c < cats->count; c++) {
1358 category_t *cat = cats->list[c].cat;
1360 if (isMeta && cat->classProperties) {
1361 count += cat->classProperties->count;
1364 if (!isMeta && cat->instanceProperties) {
1365 count += cat->instanceProperties->count;
1370 if (count == 0) return NULL;
1372 // Allocate new list.
1373 newlist = (chained_property_list *)
1374 _malloc_internal(sizeof(*newlist) + count * sizeof(property_t));
1376 newlist->next = NULL;
1378 // Copy properties; newest categories first, then ordinary properties
1382 property_list_t *cplist;
1383 category_t *cat = cats->list[c].cat;
1386 cplist = cat->classProperties;
1389 cplist = cat->instanceProperties;
1392 for (p = 0; p < cplist->count; p++) {
1393 newlist->list[newlist->count++] =
1394 *property_list_nth(cplist, p);
1400 for (p = 0; p < plist->count; p++) {
1401 newlist->list[newlist->count++] = *property_list_nth(plist, p);
1405 assert(newlist->count == count);
1411 static const protocol_list_t **
1412 buildProtocolList(category_list *cats, const protocol_list_t *base,
1413 const protocol_list_t **protos)
1415 // Do NOT use cat->cls! It may have been remapped.
1416 const protocol_list_t **p, **newp;
1417 const protocol_list_t **newprotos;
1418 unsigned int count = 0;
1421 // count protocol list in base
1424 // count protocol lists in cats
1425 if (cats) for (i = 0; i < cats->count; i++) {
1426 category_t *cat = cats->list[i].cat;
1427 if (cat->protocols) count++;
1430 // no base or category protocols? return existing protocols unchanged
1431 if (count == 0) return protos;
1433 // count protocol lists in protos
1434 for (p = protos; p && *p; p++) {
1438 if (count == 0) return NULL;
1440 newprotos = (const protocol_list_t **)
1441 _malloc_internal((count+1) * sizeof(protocol_list_t *));
1448 for (p = protos; p && *p; p++) {
1452 if (cats) for (i = 0; i < cats->count; i++) {
1453 category_t *cat = cats->list[i].cat;
1454 if (cat->protocols) {
1455 *newp++ = cat->protocols;
1465 /***********************************************************************
1467 * Fixes up cls's method list, protocol list, and property list.
1468 * Attaches any outstanding categories.
1470 * Locking: runtimeLock must be held by the caller
1471 **********************************************************************/
1472 static void methodizeClass(class_t *cls)
1474 category_list *cats;
1477 rwlock_assert_writing(&runtimeLock);
1479 isMeta = isMetaClass(cls);
1481 // Methodizing for the first time
1482 if (PrintConnecting) {
1483 _objc_inform("CLASS: methodizing class '%s' %s",
1484 getName(cls), isMeta ? "(meta)" : "");
1487 // Build method and protocol and property lists.
1488 // Include methods and protocols and properties from categories, if any
1489 // Do NOT use cat->cls! It may have been remapped.
1491 attachMethodLists(cls, (method_list_t **)&cls->data()->ro->baseMethods, 1,
1492 isBundleClass(cls), NULL);
1494 // Root classes get bonus method implementations if they don't have
1495 // them already. These apply before category replacements.
1497 if (cls->isRootClass()) {
1500 // Assume custom RR except NSObject, even without MM method imps.
1501 if (0 != strcmp(getName(cls), "NSObject")) cls->setHasCustomRR();
1504 else if (cls->isRootMetaclass()) {
1506 addMethod(cls, SEL_initialize, (IMP)&objc_noop_imp, "", NO);
1508 // Assume custom RR always.
1509 cls->setHasCustomRR();
1513 cats = unattachedCategoriesForClass(cls);
1514 attachCategoryMethods(cls, cats, NULL);
1516 if (cats || cls->data()->ro->baseProperties) {
1517 cls->data()->properties =
1518 buildPropertyList(cls->data()->ro->baseProperties, cats, isMeta);
1521 if (cats || cls->data()->ro->baseProtocols) {
1522 cls->data()->protocols =
1523 buildProtocolList(cats, cls->data()->ro->baseProtocols, NULL);
1526 if (PrintConnecting) {
1529 for (i = 0; i < cats->count; i++) {
1530 _objc_inform("CLASS: attached category %c%s(%s)",
1532 getName(cls), cats->list[i].cat->name);
1537 if (cats) _free_internal(cats);
1539 // No vtable until +initialize completes
1540 assert(cls->vtable == &_objc_empty_vtable);
1543 // Debug: sanity-check all SELs; log method list contents
1544 FOREACH_METHOD_LIST(mlist, cls, {
1545 method_list_t::method_iterator iter = mlist->begin();
1546 method_list_t::method_iterator end = mlist->end();
1547 for ( ; iter != end; ++iter) {
1548 if (PrintConnecting) {
1549 _objc_inform("METHOD %c[%s %s]", isMeta ? '+' : '-',
1550 getName(cls), sel_getName(iter->name));
1552 assert(ignoreSelector(iter->name) || sel_registerName(sel_getName(iter->name))==iter->name);
1559 /***********************************************************************
1561 * Attach outstanding categories to an existing class.
1562 * Fixes up cls's method list, protocol list, and property list.
1563 * Updates method caches and vtables for cls and its subclasses.
1564 * Locking: runtimeLock must be held by the caller
1565 **********************************************************************/
1566 static void remethodizeClass(class_t *cls)
1568 category_list *cats;
1571 rwlock_assert_writing(&runtimeLock);
1573 isMeta = isMetaClass(cls);
1575 // Re-methodizing: check for more categories
1576 if ((cats = unattachedCategoriesForClass(cls))) {
1577 chained_property_list *newproperties;
1578 const protocol_list_t **newprotos;
1580 if (PrintConnecting) {
1581 _objc_inform("CLASS: attaching categories to class '%s' %s",
1582 getName(cls), isMeta ? "(meta)" : "");
1585 // Update methods, properties, protocols
1587 BOOL vtableAffected = NO;
1588 attachCategoryMethods(cls, cats, &vtableAffected);
1590 newproperties = buildPropertyList(NULL, cats, isMeta);
1591 if (newproperties) {
1592 newproperties->next = cls->data()->properties;
1593 cls->data()->properties = newproperties;
1596 newprotos = buildProtocolList(cats, NULL, cls->data()->protocols);
1597 if (cls->data()->protocols && cls->data()->protocols != newprotos) {
1598 _free_internal(cls->data()->protocols);
1600 cls->data()->protocols = newprotos;
1602 _free_internal(cats);
1604 // Update method caches and vtables
1606 if (vtableAffected) flushVtables(cls);
1611 /***********************************************************************
1613 * Atomically sets and clears some bits in cls's info field.
1614 * set and clear must not overlap.
1615 **********************************************************************/
1616 static void changeInfo(class_t *cls, unsigned int set, unsigned int clear)
1618 uint32_t oldf, newf;
1620 assert(isFuture(cls) || isRealized(cls));
1623 oldf = cls->data()->flags;
1624 newf = (oldf | set) & ~clear;
1625 } while (!OSAtomicCompareAndSwap32Barrier(oldf, newf, (volatile int32_t *)&cls->data()->flags));
1629 /***********************************************************************
1631 * Returns the classname => class map of all non-meta classes.
1632 * Locking: runtimeLock must be read- or write-locked by the caller
1633 **********************************************************************/
1635 NXMapTable *gdb_objc_realized_classes; // exported for debuggers in objc-gdb.h
1637 static NXMapTable *namedClasses(void)
1639 rwlock_assert_locked(&runtimeLock);
1641 // allocated in _read_images
1642 assert(gdb_objc_realized_classes);
1644 return gdb_objc_realized_classes;
1648 /***********************************************************************
1650 * Adds name => cls to the named non-meta class map.
1651 * Warns about duplicate class names and keeps the old mapping.
1652 * Locking: runtimeLock must be held by the caller
1653 **********************************************************************/
1654 static void addNamedClass(class_t *cls, const char *name)
1656 rwlock_assert_writing(&runtimeLock);
1658 if ((old = (class_t *)NXMapGet(namedClasses(), name))) {
1659 inform_duplicate(name, (Class)old, (Class)cls);
1661 NXMapInsert(namedClasses(), name, cls);
1663 assert(!(cls->data()->flags & RO_META));
1665 // wrong: constructed classes are already realized when they get here
1666 // assert(!isRealized(cls));
1670 /***********************************************************************
1672 * Removes cls from the name => cls map.
1673 * Locking: runtimeLock must be held by the caller
1674 **********************************************************************/
1675 static void removeNamedClass(class_t *cls, const char *name)
1677 rwlock_assert_writing(&runtimeLock);
1678 assert(!(cls->data()->flags & RO_META));
1679 if (cls == NXMapGet(namedClasses(), name)) {
1680 NXMapRemove(namedClasses(), name);
1682 // cls has a name collision with another class - don't remove the other
1687 /***********************************************************************
1689 * Returns the class list for realized non-meta classes.
1690 * Locking: runtimeLock must be read- or write-locked by the caller
1691 **********************************************************************/
1692 static NXHashTable *realized_class_hash = NULL;
1694 static NXHashTable *realizedClasses(void)
1696 rwlock_assert_locked(&runtimeLock);
1698 // allocated in _read_images
1699 assert(realized_class_hash);
1701 return realized_class_hash;
1705 /***********************************************************************
1706 * realizedMetaclasses
1707 * Returns the class list for realized metaclasses.
1708 * Locking: runtimeLock must be read- or write-locked by the caller
1709 **********************************************************************/
1710 static NXHashTable *realized_metaclass_hash = NULL;
1711 static NXHashTable *realizedMetaclasses(void)
1713 rwlock_assert_locked(&runtimeLock);
1715 // allocated in _read_images
1716 assert(realized_metaclass_hash);
1718 return realized_metaclass_hash;
1722 /***********************************************************************
1724 * Adds cls to the realized non-meta class hash.
1725 * Locking: runtimeLock must be held by the caller
1726 **********************************************************************/
1727 static void addRealizedClass(class_t *cls)
1729 rwlock_assert_writing(&runtimeLock);
1731 old = NXHashInsert(realizedClasses(), cls);
1732 objc_addRegisteredClass((Class)cls);
1733 assert(!isMetaClass(cls));
1738 /***********************************************************************
1739 * removeRealizedClass
1740 * Removes cls from the realized non-meta class hash.
1741 * Locking: runtimeLock must be held by the caller
1742 **********************************************************************/
1743 static void removeRealizedClass(class_t *cls)
1745 rwlock_assert_writing(&runtimeLock);
1746 if (isRealized(cls)) {
1747 assert(!isMetaClass(cls));
1748 NXHashRemove(realizedClasses(), cls);
1749 objc_removeRegisteredClass((Class)cls);
1754 /***********************************************************************
1755 * addRealizedMetaclass
1756 * Adds cls to the realized metaclass hash.
1757 * Locking: runtimeLock must be held by the caller
1758 **********************************************************************/
1759 static void addRealizedMetaclass(class_t *cls)
1761 rwlock_assert_writing(&runtimeLock);
1763 old = NXHashInsert(realizedMetaclasses(), cls);
1764 assert(isMetaClass(cls));
1769 /***********************************************************************
1770 * removeRealizedMetaclass
1771 * Removes cls from the realized metaclass hash.
1772 * Locking: runtimeLock must be held by the caller
1773 **********************************************************************/
1774 static void removeRealizedMetaclass(class_t *cls)
1776 rwlock_assert_writing(&runtimeLock);
1777 if (isRealized(cls)) {
1778 assert(isMetaClass(cls));
1779 NXHashRemove(realizedMetaclasses(), cls);
1784 /***********************************************************************
1785 * uninitializedClasses
1786 * Returns the metaclass => class map for un-+initialized classes
1787 * Replaces the 32-bit cls = objc_getName(metacls) during +initialize.
1788 * Locking: runtimeLock must be read- or write-locked by the caller
1789 **********************************************************************/
1790 static NXMapTable *uninitialized_class_map = NULL;
1791 static NXMapTable *uninitializedClasses(void)
1793 rwlock_assert_locked(&runtimeLock);
1795 // allocated in _read_images
1796 assert(uninitialized_class_map);
1798 return uninitialized_class_map;
1802 /***********************************************************************
1803 * addUninitializedClass
1804 * Adds metacls => cls to the un-+initialized class map
1805 * Locking: runtimeLock must be held by the caller
1806 **********************************************************************/
1807 static void addUninitializedClass(class_t *cls, class_t *metacls)
1809 rwlock_assert_writing(&runtimeLock);
1811 old = NXMapInsert(uninitializedClasses(), metacls, cls);
1812 assert(isRealized(metacls) ? isMetaClass(metacls) : metacls->data()->flags & RO_META);
1813 assert(! (isRealized(cls) ? isMetaClass(cls) : cls->data()->flags & RO_META));
1818 static void removeUninitializedClass(class_t *cls)
1820 rwlock_assert_writing(&runtimeLock);
1821 NXMapRemove(uninitializedClasses(), cls->isa);
1825 /***********************************************************************
1827 * Return the ordinary class for this class or metaclass.
1828 * Used by +initialize.
1829 * Locking: runtimeLock must be read- or write-locked by the caller
1830 **********************************************************************/
1831 static class_t *getNonMetaClass(class_t *cls)
1833 rwlock_assert_locked(&runtimeLock);
1834 if (isMetaClass(cls)) {
1835 cls = (class_t *)NXMapGet(uninitializedClasses(), cls);
1841 /***********************************************************************
1842 * _class_getNonMetaClass
1843 * Return the ordinary class for this class or metaclass.
1844 * Used by +initialize.
1845 * Locking: acquires runtimeLock
1846 **********************************************************************/
1847 PRIVATE_EXTERN Class _class_getNonMetaClass(Class cls_gen)
1849 class_t *cls = newcls(cls_gen);
1850 rwlock_write(&runtimeLock);
1851 cls = getNonMetaClass(cls);
1853 rwlock_unlock_write(&runtimeLock);
1860 /***********************************************************************
1862 * Returns the classname => future class map for unrealized future classes.
1863 * Locking: runtimeLock must be held by the caller
1864 **********************************************************************/
1865 static NXMapTable *futureClasses(void)
1867 rwlock_assert_writing(&runtimeLock);
1869 static NXMapTable *future_class_map = NULL;
1871 if (future_class_map) return future_class_map;
1873 // future_class_map is big enough to hold CF's classes and a few others
1874 future_class_map = NXCreateMapTableFromZone(NXStrValueMapPrototype, 32,
1875 _objc_internal_zone());
1877 return future_class_map;
1881 /***********************************************************************
1883 * Installs cls as the class structure to use for the named class if it appears.
1884 * Locking: runtimeLock must be held by the caller
1885 **********************************************************************/
1886 static void addFutureClass(const char *name, class_t *cls)
1890 rwlock_assert_writing(&runtimeLock);
1893 _objc_inform("FUTURE: reserving %p for %s", cls, name);
1896 cls->setData((class_rw_t *)_calloc_internal(sizeof(*cls->data()), 1));
1897 cls->data()->flags = RO_FUTURE;
1899 old = NXMapKeyCopyingInsert(futureClasses(), name, cls);
1904 /***********************************************************************
1906 * Removes the named class from the unrealized future class list,
1907 * because it has been realized.
1908 * Locking: runtimeLock must be held by the caller
1909 **********************************************************************/
1910 static void removeFutureClass(const char *name)
1912 rwlock_assert_writing(&runtimeLock);
1914 NXMapKeyFreeingRemove(futureClasses(), name);
1918 /***********************************************************************
1920 * Returns the oldClass => newClass map for realized future classes.
1921 * Returns the oldClass => NULL map for ignored weak-linked classes.
1922 * Locking: runtimeLock must be read- or write-locked by the caller
1923 **********************************************************************/
1924 static NXMapTable *remappedClasses(BOOL create)
1926 static NXMapTable *remapped_class_map = NULL;
1928 rwlock_assert_locked(&runtimeLock);
1930 if (remapped_class_map) return remapped_class_map;
1931 if (!create) return NULL;
1933 // remapped_class_map is big enough to hold CF's classes and a few others
1934 INIT_ONCE_PTR(remapped_class_map,
1935 NXCreateMapTableFromZone(NXPtrValueMapPrototype, 32,
1936 _objc_internal_zone()),
1939 return remapped_class_map;
1943 /***********************************************************************
1945 * Returns YES if no classes have been remapped
1946 * Locking: runtimeLock must be read- or write-locked by the caller
1947 **********************************************************************/
1948 static BOOL noClassesRemapped(void)
1950 rwlock_assert_locked(&runtimeLock);
1952 BOOL result = (remappedClasses(NO) == NULL);
1957 /***********************************************************************
1959 * newcls is a realized future class, replacing oldcls.
1960 * OR newcls is NULL, replacing ignored weak-linked class oldcls.
1961 * Locking: runtimeLock must be write-locked by the caller
1962 **********************************************************************/
1963 static void addRemappedClass(class_t *oldcls, class_t *newcls)
1965 rwlock_assert_writing(&runtimeLock);
1968 _objc_inform("FUTURE: using %p instead of %p for %s",
1969 oldcls, newcls, getName(newcls));
1973 old = NXMapInsert(remappedClasses(YES), oldcls, newcls);
1978 /***********************************************************************
1980 * Returns the live class pointer for cls, which may be pointing to
1981 * a class struct that has been reallocated.
1982 * Returns NULL if cls is ignored because of weak linking.
1983 * Locking: runtimeLock must be read- or write-locked by the caller
1984 **********************************************************************/
1985 static class_t *remapClass(class_t *cls)
1987 rwlock_assert_locked(&runtimeLock);
1991 if (!cls) return NULL;
1993 if (NXMapMember(remappedClasses(YES), cls, (void**)&c2) == NX_MAPNOTAKEY) {
2001 /***********************************************************************
2003 * Fix up a class ref, in case the class referenced has been reallocated
2004 * or is an ignored weak-linked class.
2005 * Locking: runtimeLock must be read- or write-locked by the caller
2006 **********************************************************************/
2007 static void remapClassRef(class_t **clsref)
2009 rwlock_assert_locked(&runtimeLock);
2011 class_t *newcls = remapClass(*clsref);
2012 if (*clsref != newcls) *clsref = newcls;
2016 /***********************************************************************
2018 * Adds subcls as a subclass of supercls.
2019 * Locking: runtimeLock must be held by the caller.
2020 **********************************************************************/
2021 static void addSubclass(class_t *supercls, class_t *subcls)
2023 rwlock_assert_writing(&runtimeLock);
2025 if (supercls && subcls) {
2026 assert(isRealized(supercls));
2027 assert(isRealized(subcls));
2028 subcls->data()->nextSiblingClass = supercls->data()->firstSubclass;
2029 supercls->data()->firstSubclass = subcls;
2031 if (supercls->data()->flags & RW_HAS_CXX_STRUCTORS) {
2032 subcls->data()->flags |= RW_HAS_CXX_STRUCTORS;
2035 if (supercls->hasCustomRR()) {
2036 subcls->setHasCustomRR();
2042 /***********************************************************************
2044 * Removes subcls as a subclass of supercls.
2045 * Locking: runtimeLock must be held by the caller.
2046 **********************************************************************/
2047 static void removeSubclass(class_t *supercls, class_t *subcls)
2049 rwlock_assert_writing(&runtimeLock);
2050 assert(getSuperclass(subcls) == supercls);
2053 for (cp = &supercls->data()->firstSubclass;
2054 *cp && *cp != subcls;
2055 cp = &(*cp)->data()->nextSiblingClass)
2057 assert(*cp == subcls);
2058 *cp = subcls->data()->nextSiblingClass;
2063 /***********************************************************************
2065 * Returns the protocol name => protocol map for protocols.
2066 * Locking: runtimeLock must read- or write-locked by the caller
2067 **********************************************************************/
2068 static NXMapTable *protocols(void)
2070 static NXMapTable *protocol_map = NULL;
2072 rwlock_assert_locked(&runtimeLock);
2074 INIT_ONCE_PTR(protocol_map,
2075 NXCreateMapTableFromZone(NXStrValueMapPrototype, 16,
2076 _objc_internal_zone()),
2077 NXFreeMapTable(v) );
2079 return protocol_map;
2083 /***********************************************************************
2085 * Returns the live protocol pointer for proto, which may be pointing to
2086 * a protocol struct that has been reallocated.
2087 * Locking: runtimeLock must be read- or write-locked by the caller
2088 **********************************************************************/
2089 static protocol_t *remapProtocol(protocol_ref_t proto)
2091 rwlock_assert_locked(&runtimeLock);
2093 protocol_t *newproto = (protocol_t *)
2094 NXMapGet(protocols(), ((protocol_t *)proto)->name);
2095 return newproto ? newproto : (protocol_t *)proto;
2099 /***********************************************************************
2101 * Fix up a protocol ref, in case the protocol referenced has been reallocated.
2102 * Locking: runtimeLock must be read- or write-locked by the caller
2103 **********************************************************************/
2104 static void remapProtocolRef(protocol_t **protoref)
2106 rwlock_assert_locked(&runtimeLock);
2108 protocol_t *newproto = remapProtocol((protocol_ref_t)*protoref);
2109 if (*protoref != newproto) *protoref = newproto;
2113 /***********************************************************************
2115 * Slides a class's ivars to accommodate the given superclass size.
2116 * Also slides ivar and weak GC layouts if provided.
2117 * Ivars are NOT compacted to compensate for a superclass that shrunk.
2118 * Locking: runtimeLock must be held by the caller.
2119 **********************************************************************/
2120 static void moveIvars(class_ro_t *ro, uint32_t superSize,
2121 layout_bitmap *ivarBitmap, layout_bitmap *weakBitmap)
2123 rwlock_assert_writing(&runtimeLock);
2128 assert(superSize > ro->instanceStart);
2129 diff = superSize - ro->instanceStart;
2132 // Find maximum alignment in this class's ivars
2133 uint32_t maxAlignment = 1;
2134 for (i = 0; i < ro->ivars->count; i++) {
2135 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
2136 if (!ivar->offset) continue; // anonymous bitfield
2138 uint32_t alignment = ivar_alignment(ivar);
2139 if (alignment > maxAlignment) maxAlignment = alignment;
2142 // Compute a slide value that preserves that alignment
2143 uint32_t alignMask = maxAlignment - 1;
2144 if (diff & alignMask) diff = (diff + alignMask) & ~alignMask;
2146 // Slide all of this class's ivars en masse
2147 for (i = 0; i < ro->ivars->count; i++) {
2148 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
2149 if (!ivar->offset) continue; // anonymous bitfield
2151 uint32_t oldOffset = (uint32_t)*ivar->offset;
2152 uint32_t newOffset = oldOffset + diff;
2153 *ivar->offset = newOffset;
2156 _objc_inform("IVARS: offset %u -> %u for %s (size %u, align %u)",
2157 oldOffset, newOffset, ivar->name,
2158 ivar->size, ivar_alignment(ivar));
2163 uint32_t oldOffset = ro->instanceStart;
2164 uint32_t newOffset = ro->instanceStart + diff;
2167 layout_bitmap_slide(ivarBitmap,
2168 oldOffset >> WORD_SHIFT,
2169 newOffset >> WORD_SHIFT);
2172 layout_bitmap_slide(weakBitmap,
2173 oldOffset >> WORD_SHIFT,
2174 newOffset >> WORD_SHIFT);
2178 *(uint32_t *)&ro->instanceStart += diff;
2179 *(uint32_t *)&ro->instanceSize += diff;
2182 // No ivars slid, but superclass changed size.
2183 // Expand bitmap in preparation for layout_bitmap_splat().
2184 if (ivarBitmap) layout_bitmap_grow(ivarBitmap, ro->instanceSize >> WORD_SHIFT);
2185 if (weakBitmap) layout_bitmap_grow(weakBitmap, ro->instanceSize >> WORD_SHIFT);
2190 /***********************************************************************
2192 * Look up an ivar by name.
2193 * Locking: runtimeLock must be read- or write-locked by the caller.
2194 **********************************************************************/
2195 static ivar_t *getIvar(class_t *cls, const char *name)
2197 rwlock_assert_locked(&runtimeLock);
2199 const ivar_list_t *ivars;
2200 assert(isRealized(cls));
2201 if ((ivars = cls->data()->ro->ivars)) {
2203 for (i = 0; i < ivars->count; i++) {
2204 ivar_t *ivar = ivar_list_nth(ivars, i);
2205 if (!ivar->offset) continue; // anonymous bitfield
2207 // ivar->name may be NULL for anonymous bitfields etc.
2208 if (ivar->name && 0 == strcmp(name, ivar->name)) {
2217 static void reconcileInstanceVariables(class_t *cls, class_t *supercls) {
2218 class_rw_t *rw = cls->data();
2219 const class_ro_t *ro = rw->ro;
2222 // Non-fragile ivars - reconcile this class with its superclass
2223 // Does this really need to happen for the isMETA case?
2224 layout_bitmap ivarBitmap;
2225 layout_bitmap weakBitmap;
2226 BOOL layoutsChanged = NO;
2227 BOOL mergeLayouts = UseGC;
2228 const class_ro_t *super_ro = supercls->data()->ro;
2230 if (DebugNonFragileIvars) {
2231 // Debugging: Force non-fragile ivars to slide.
2232 // Intended to find compiler, runtime, and program bugs.
2233 // If it fails with this and works without, you have a problem.
2235 // Operation: Reset everything to 0 + misalignment.
2236 // Then force the normal sliding logic to push everything back.
2238 // Exceptions: root classes, metaclasses, *NSCF* classes,
2239 // __CF* classes, NSConstantString, NSSimpleCString
2241 // (already know it's not root because supercls != nil)
2242 if (!strstr(getName(cls), "NSCF") &&
2243 0 != strncmp(getName(cls), "__CF", 4) &&
2244 0 != strcmp(getName(cls), "NSConstantString") &&
2245 0 != strcmp(getName(cls), "NSSimpleCString"))
2247 uint32_t oldStart = ro->instanceStart;
2248 uint32_t oldSize = ro->instanceSize;
2249 class_ro_t *ro_w = make_ro_writeable(rw);
2252 // Find max ivar alignment in class.
2253 // default to word size to simplify ivar update
2254 uint32_t alignment = 1<<WORD_SHIFT;
2257 for (i = 0; i < ro->ivars->count; i++) {
2258 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
2259 if (ivar_alignment(ivar) > alignment) {
2260 alignment = ivar_alignment(ivar);
2264 uint32_t misalignment = ro->instanceStart % alignment;
2265 uint32_t delta = ro->instanceStart - misalignment;
2266 ro_w->instanceStart = misalignment;
2267 ro_w->instanceSize -= delta;
2270 _objc_inform("IVARS: DEBUG: forcing ivars for class '%s' "
2271 "to slide (instanceStart %zu -> %zu)",
2272 getName(cls), (size_t)oldStart,
2273 (size_t)ro->instanceStart);
2278 for (i = 0; i < ro->ivars->count; i++) {
2279 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
2280 if (!ivar->offset) continue; // anonymous bitfield
2281 *ivar->offset -= delta;
2286 layout_bitmap layout;
2287 if (ro->ivarLayout) {
2288 layout = layout_bitmap_create(ro->ivarLayout,
2289 oldSize, oldSize, NO);
2290 layout_bitmap_slide_anywhere(&layout,
2291 delta >> WORD_SHIFT, 0);
2292 ro_w->ivarLayout = layout_string_create(layout);
2293 layout_bitmap_free(layout);
2295 if (ro->weakIvarLayout) {
2296 layout = layout_bitmap_create(ro->weakIvarLayout,
2297 oldSize, oldSize, YES);
2298 layout_bitmap_slide_anywhere(&layout,
2299 delta >> WORD_SHIFT, 0);
2300 ro_w->weakIvarLayout = layout_string_create(layout);
2301 layout_bitmap_free(layout);
2307 // fixme can optimize for "class has no new ivars", etc
2308 // WARNING: gcc c++ sets instanceStart/Size=0 for classes with
2309 // no local ivars, but does provide a layout bitmap.
2310 // Handle that case specially so layout_bitmap_create doesn't die
2311 // The other ivar sliding code below still works fine, and
2312 // the final result is a good class.
2313 if (ro->instanceStart == 0 && ro->instanceSize == 0) {
2314 // We can't use ro->ivarLayout because we don't know
2315 // how long it is. Force a new layout to be created.
2317 _objc_inform("IVARS: instanceStart/Size==0 for class %s; "
2318 "disregarding ivar layout", ro->name);
2320 ivarBitmap = layout_bitmap_create_empty(super_ro->instanceSize, NO);
2321 weakBitmap = layout_bitmap_create_empty(super_ro->instanceSize, YES);
2322 layoutsChanged = YES;
2325 layout_bitmap_create(ro->ivarLayout,
2327 ro->instanceSize, NO);
2329 layout_bitmap_create(ro->weakIvarLayout,
2331 ro->instanceSize, YES);
2334 if (ro->instanceStart < super_ro->instanceSize) {
2335 // Superclass has changed size. This class's ivars must move.
2336 // Also slide layout bits in parallel.
2337 // This code is incapable of compacting the subclass to
2338 // compensate for a superclass that shrunk, so don't do that.
2340 _objc_inform("IVARS: sliding ivars for class %s "
2341 "(superclass was %u bytes, now %u)",
2342 ro->name, ro->instanceStart,
2343 super_ro->instanceSize);
2345 class_ro_t *ro_w = make_ro_writeable(rw);
2347 moveIvars(ro_w, super_ro->instanceSize,
2348 mergeLayouts ? &ivarBitmap : NULL, mergeLayouts ? &weakBitmap : NULL);
2349 gdb_objc_class_changed((Class)cls, OBJC_CLASS_IVARS_CHANGED, ro->name);
2350 layoutsChanged = mergeLayouts;
2354 // Check superclass's layout against this class's layout.
2355 // This needs to be done even if the superclass is not bigger.
2356 layout_bitmap superBitmap = layout_bitmap_create(super_ro->ivarLayout,
2357 super_ro->instanceSize,
2358 super_ro->instanceSize, NO);
2359 layoutsChanged |= layout_bitmap_splat(ivarBitmap, superBitmap,
2361 layout_bitmap_free(superBitmap);
2363 // check the superclass' weak layout.
2364 superBitmap = layout_bitmap_create(super_ro->weakIvarLayout,
2365 super_ro->instanceSize,
2366 super_ro->instanceSize, YES);
2367 layoutsChanged |= layout_bitmap_splat(weakBitmap, superBitmap,
2369 layout_bitmap_free(superBitmap);
2372 if (layoutsChanged) {
2373 // Rebuild layout strings.
2375 _objc_inform("IVARS: gc layout changed for class %s",
2378 class_ro_t *ro_w = make_ro_writeable(rw);
2380 if (DebugNonFragileIvars) {
2381 try_free(ro_w->ivarLayout);
2382 try_free(ro_w->weakIvarLayout);
2384 ro_w->ivarLayout = layout_string_create(ivarBitmap);
2385 ro_w->weakIvarLayout = layout_string_create(weakBitmap);
2388 layout_bitmap_free(ivarBitmap);
2389 layout_bitmap_free(weakBitmap);
2393 /***********************************************************************
2395 * Performs first-time initialization on class cls,
2396 * including allocating its read-write data.
2397 * Returns the real class structure for the class.
2398 * Locking: runtimeLock must be write-locked by the caller
2399 **********************************************************************/
2400 static class_t *realizeClass(class_t *cls)
2402 rwlock_assert_writing(&runtimeLock);
2404 const class_ro_t *ro;
2410 if (!cls) return NULL;
2411 if (isRealized(cls)) return cls;
2412 assert(cls == remapClass(cls));
2414 ro = (const class_ro_t *)cls->data();
2415 if (ro->flags & RO_FUTURE) {
2416 // This was a future class. rw data is already allocated.
2418 ro = cls->data()->ro;
2419 changeInfo(cls, RW_REALIZED, RW_FUTURE);
2421 // Normal class. Allocate writeable class data.
2422 rw = (class_rw_t *)_calloc_internal(sizeof(class_rw_t), 1);
2424 rw->flags = RW_REALIZED;
2428 isMeta = (ro->flags & RO_META) ? YES : NO;
2430 rw->version = isMeta ? 7 : 0; // old runtime went up to 6
2432 if (PrintConnecting) {
2433 _objc_inform("CLASS: realizing class '%s' %s %p %p",
2434 ro->name, isMeta ? "(meta)" : "", cls, ro);
2437 // Realize superclass and metaclass, if they aren't already.
2438 // This needs to be done after RW_REALIZED is set above, for root classes.
2439 supercls = realizeClass(remapClass(cls->superclass));
2440 metacls = realizeClass(remapClass(cls->isa));
2442 // Check for remapped superclass
2443 // fixme doesn't handle remapped metaclass
2444 assert(metacls == cls->isa);
2445 if (supercls != cls->superclass) {
2446 cls->superclass = supercls;
2449 /* debug: print them all
2452 for (i = 0; i < ro->ivars->count; i++) {
2453 ivar_t *ivar = ivar_list_nth(ro->ivars, i);
2454 if (!ivar->offset) continue; // anonymous bitfield
2456 _objc_inform("IVARS: %s.%s (offset %u, size %u, align %u)",
2457 ro->name, ivar->name,
2458 *ivar->offset, ivar->size, ivar_alignment(ivar));
2463 // Reconcile instance variable offsets / layout.
2464 if (!isMeta) reconcileInstanceVariables(cls, supercls);
2466 // Copy some flags from ro to rw
2467 if (ro->flags & RO_HAS_CXX_STRUCTORS) rw->flags |= RW_HAS_CXX_STRUCTORS;
2469 // Connect this class to its superclass's subclass lists
2471 addSubclass(supercls, cls);
2474 // Attach categories
2475 methodizeClass(cls);
2478 addRealizedClass(cls);
2480 addRealizedMetaclass(cls);
2487 /***********************************************************************
2489 * Looks up a class by name. The class MIGHT NOT be realized.
2490 * Locking: runtimeLock must be read- or write-locked by the caller.
2491 **********************************************************************/
2492 static class_t *getClass(const char *name)
2494 rwlock_assert_locked(&runtimeLock);
2496 return (class_t *)NXMapGet(namedClasses(), name);
2500 /***********************************************************************
2501 * missingWeakSuperclass
2502 * Return YES if some superclass of cls was weak-linked and is missing.
2503 **********************************************************************/
2505 missingWeakSuperclass(class_t *cls)
2507 assert(!isRealized(cls));
2509 if (!cls->superclass) {
2510 // superclass NULL. This is normal for root classes only.
2511 return (!(cls->data()->flags & RO_ROOT));
2513 // superclass not NULL. Check if a higher superclass is missing.
2514 class_t *supercls = remapClass(cls->superclass);
2515 if (!supercls) return YES;
2516 if (isRealized(supercls)) return NO;
2517 return missingWeakSuperclass(supercls);
2522 /***********************************************************************
2523 * realizeAllClassesInImage
2524 * Non-lazily realizes all unrealized classes in the given image.
2525 * Locking: runtimeLock must be held by the caller.
2526 **********************************************************************/
2527 static void realizeAllClassesInImage(header_info *hi)
2529 rwlock_assert_writing(&runtimeLock);
2532 class_t **classlist;
2534 if (hi->allClassesRealized) return;
2536 classlist = _getObjc2ClassList(hi, &count);
2538 for (i = 0; i < count; i++) {
2539 realizeClass(remapClass(classlist[i]));
2542 hi->allClassesRealized = YES;
2546 /***********************************************************************
2548 * Non-lazily realizes all unrealized classes in all known images.
2549 * Locking: runtimeLock must be held by the caller.
2550 **********************************************************************/
2551 static void realizeAllClasses(void)
2553 rwlock_assert_writing(&runtimeLock);
2556 for (hi = FirstHeader; hi; hi = hi->next) {
2557 realizeAllClassesInImage(hi);
2562 /***********************************************************************
2563 * _objc_allocateFutureClass
2564 * Allocate an unresolved future class for the given class name.
2565 * Returns any existing allocation if one was already made.
2566 * Assumes the named class doesn't exist yet.
2567 * Locking: acquires runtimeLock
2568 **********************************************************************/
2569 PRIVATE_EXTERN Class _objc_allocateFutureClass(const char *name)
2571 rwlock_write(&runtimeLock);
2574 NXMapTable *future_class_map = futureClasses();
2576 if ((cls = (class_t *)NXMapGet(future_class_map, name))) {
2577 // Already have a future class for this name.
2578 rwlock_unlock_write(&runtimeLock);
2582 cls = (class_t *)_calloc_class(sizeof(*cls));
2583 addFutureClass(name, cls);
2585 rwlock_unlock_write(&runtimeLock);
2590 /***********************************************************************
2592 **********************************************************************/
2593 void objc_setFutureClass(Class cls, const char *name)
2595 // fixme hack do nothing - NSCFString handled specially elsewhere
2599 /***********************************************************************
2601 * Rebuilds vtables for cls and its realized subclasses.
2602 * If cls is Nil, all realized classes and metaclasses are touched.
2603 * Locking: runtimeLock must be held by the caller.
2604 **********************************************************************/
2605 static void flushVtables(class_t *cls)
2607 rwlock_assert_writing(&runtimeLock);
2609 if (PrintVtables && !cls) {
2610 _objc_inform("VTABLES: ### EXPENSIVE ### global vtable flush!");
2613 FOREACH_REALIZED_CLASS_AND_SUBCLASS(c, cls, {
2614 updateVtable(c, NO);
2619 /***********************************************************************
2621 * Flushes caches for cls and its realized subclasses.
2622 * Does not update vtables.
2623 * If cls is Nil, all realized and metaclasses classes are touched.
2624 * Locking: runtimeLock must be held by the caller.
2625 **********************************************************************/
2626 static void flushCaches(class_t *cls)
2628 rwlock_assert_writing(&runtimeLock);
2630 FOREACH_REALIZED_CLASS_AND_SUBCLASS(c, cls, {
2631 flush_cache((Class)c);
2636 /***********************************************************************
2638 * Flushes caches and rebuilds vtables for cls, its subclasses,
2639 * and optionally its metaclass.
2640 * Locking: acquires runtimeLock
2641 **********************************************************************/
2642 PRIVATE_EXTERN void flush_caches(Class cls_gen, BOOL flush_meta)
2644 class_t *cls = newcls(cls_gen);
2645 rwlock_write(&runtimeLock);
2646 // fixme optimize vtable flushing? (only needed for vtable'd selectors)
2649 // don't flush root class's metaclass twice (it's a subclass of the root)
2650 if (flush_meta && getSuperclass(cls)) {
2651 flushCaches(cls->isa);
2652 flushVtables(cls->isa);
2654 rwlock_unlock_write(&runtimeLock);
2658 /***********************************************************************
2660 * Process the given images which are being mapped in by dyld.
2661 * Calls ABI-agnostic code after taking ABI-specific locks.
2663 * Locking: write-locks runtimeLock
2664 **********************************************************************/
2665 PRIVATE_EXTERN const char *
2666 map_images(enum dyld_image_states state, uint32_t infoCount,
2667 const struct dyld_image_info infoList[])
2671 rwlock_write(&runtimeLock);
2672 err = map_images_nolock(state, infoCount, infoList);
2673 rwlock_unlock_write(&runtimeLock);
2678 /***********************************************************************
2680 * Process +load in the given images which are being mapped in by dyld.
2681 * Calls ABI-agnostic code after taking ABI-specific locks.
2683 * Locking: write-locks runtimeLock and loadMethodLock
2684 **********************************************************************/
2685 PRIVATE_EXTERN const char *
2686 load_images(enum dyld_image_states state, uint32_t infoCount,
2687 const struct dyld_image_info infoList[])
2691 recursive_mutex_lock(&loadMethodLock);
2693 // Discover load methods
2694 rwlock_write(&runtimeLock);
2695 found = load_images_nolock(state, infoCount, infoList);
2696 rwlock_unlock_write(&runtimeLock);
2698 // Call +load methods (without runtimeLock - re-entrant)
2700 call_load_methods();
2703 recursive_mutex_unlock(&loadMethodLock);
2709 /***********************************************************************
2711 * Process the given image which is about to be unmapped by dyld.
2712 * mh is mach_header instead of headerType because that's what
2713 * dyld_priv.h says even for 64-bit.
2715 * Locking: write-locks runtimeLock and loadMethodLock
2716 **********************************************************************/
2718 unmap_image(const struct mach_header *mh, intptr_t vmaddr_slide)
2720 recursive_mutex_lock(&loadMethodLock);
2721 rwlock_write(&runtimeLock);
2723 unmap_image_nolock(mh);
2725 rwlock_unlock_write(&runtimeLock);
2726 recursive_mutex_unlock(&loadMethodLock);
2731 /***********************************************************************
2733 * Perform initial processing of the headers in the linked
2734 * list beginning with headerList.
2736 * Called by: map_images_nolock
2738 * Locking: runtimeLock acquired by map_images
2739 **********************************************************************/
2740 PRIVATE_EXTERN void _read_images(header_info **hList, uint32_t hCount)
2746 class_t **resolvedFutureClasses = NULL;
2747 size_t resolvedFutureClassCount = 0;
2748 static BOOL doneOnce;
2750 rwlock_assert_writing(&runtimeLock);
2752 #define EACH_HEADER \
2754 crashlog_header_name(NULL) && hIndex < hCount && (hi = hList[hIndex]) && crashlog_header_name(hi); \
2761 // Count classes. Size various table based on the total.
2762 unsigned int total = 0;
2764 if (_getObjc2ClassList(hi, &count)) {
2765 total += (unsigned int)count;
2769 if (PrintConnecting) {
2770 _objc_inform("CLASS: found %u classes during launch", total);
2773 // namedClasses (NOT realizedClasses)
2774 // 4/3 is NXMapTable's load factor
2775 gdb_objc_realized_classes =
2776 NXCreateMapTableFromZone(NXStrValueMapPrototype, total*4/3,
2777 _objc_internal_zone());
2779 // uninitializedClasses
2780 // 4/3 is NXMapTable's load factor
2781 uninitialized_class_map =
2782 NXCreateMapTableFromZone(NXPtrValueMapPrototype, total*4/3,
2783 _objc_internal_zone());
2785 // realizedClasses and realizedMetaclasses - less than the full total
2786 realized_class_hash =
2787 NXCreateHashTableFromZone(NXPtrPrototype, total / 8, NULL,
2788 _objc_internal_zone());
2789 realized_metaclass_hash =
2790 NXCreateHashTableFromZone(NXPtrPrototype, total / 8, NULL,
2791 _objc_internal_zone());
2795 // Discover classes. Fix up unresolved future classes. Mark bundle classes.
2796 NXMapTable *future_class_map = futureClasses();
2798 class_t **classlist = _getObjc2ClassList(hi, &count);
2799 for (i = 0; i < count; i++) {
2800 const char *name = getName(classlist[i]);
2802 if (missingWeakSuperclass(classlist[i])) {
2803 // No superclass (probably weak-linked).
2804 // Disavow any knowledge of this subclass.
2805 if (PrintConnecting) {
2806 _objc_inform("CLASS: IGNORING class '%s' with "
2807 "missing weak-linked superclass", name);
2809 addRemappedClass(classlist[i], NULL);
2810 classlist[i]->superclass = NULL;
2811 classlist[i] = NULL;
2815 if (NXCountMapTable(future_class_map) > 0) {
2816 class_t *newCls = (class_t *)NXMapGet(future_class_map, name);
2818 // Copy class_t to future class's struct.
2819 // Preserve future's rw data block.
2820 class_rw_t *rw = newCls->data();
2821 memcpy(newCls, classlist[i], sizeof(class_t));
2822 rw->ro = (class_ro_t *)newCls->data();
2823 newCls->setData(rw);
2825 removeFutureClass(name);
2826 addRemappedClass(classlist[i], newCls);
2827 classlist[i] = newCls;
2828 // Non-lazily realize the class below.
2829 resolvedFutureClasses = (class_t **)
2830 _realloc_internal(resolvedFutureClasses,
2831 (resolvedFutureClassCount+1)
2832 * sizeof(class_t *));
2833 resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
2836 addNamedClass(classlist[i], name);
2837 addUninitializedClass(classlist[i], classlist[i]->isa);
2838 if (hi->mhdr->filetype == MH_BUNDLE) {
2839 classlist[i]->data()->flags |= RO_FROM_BUNDLE;
2840 classlist[i]->isa->data()->flags |= RO_FROM_BUNDLE;
2845 // Fix up remapped classes
2846 // classlist is up to date, but classrefs may not be
2848 if (!noClassesRemapped()) {
2850 class_t **classrefs = _getObjc2ClassRefs(hi, &count);
2851 for (i = 0; i < count; i++) {
2852 remapClassRef(&classrefs[i]);
2854 // fixme why doesn't test future1 catch the absence of this?
2855 classrefs = _getObjc2SuperRefs(hi, &count);
2856 for (i = 0; i < count; i++) {
2857 remapClassRef(&classrefs[i]);
2863 // Fix up @selector references
2867 if (sel_preoptimizationValid(hi)) {
2868 _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors in %s",
2869 _nameForHeader(hi->mhdr));
2871 else if (_objcHeaderOptimizedByDyld(hi)) {
2872 _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors in %s",
2873 _nameForHeader(hi->mhdr));
2877 if (sel_preoptimizationValid(hi)) continue;
2879 SEL *sels = _getObjc2SelectorRefs(hi, &count);
2880 BOOL isBundle = hi->mhdr->filetype == MH_BUNDLE;
2881 for (i = 0; i < count; i++) {
2882 sels[i] = sel_registerNameNoLock((const char *)sels[i], isBundle);
2887 // Discover protocols. Fix up protocol refs.
2888 NXMapTable *protocol_map = protocols();
2890 extern class_t OBJC_CLASS_$_Protocol;
2891 Class cls = (Class)&OBJC_CLASS_$_Protocol;
2893 protocol_t **protocols = _getObjc2ProtocolList(hi, &count);
2894 // fixme duplicate protocol from bundle
2895 for (i = 0; i < count; i++) {
2896 if (!NXMapGet(protocol_map, protocols[i]->name)) {
2897 protocols[i]->isa = cls;
2898 NXMapKeyCopyingInsert(protocol_map,
2899 protocols[i]->name, protocols[i]);
2900 if (PrintProtocols) {
2901 _objc_inform("PROTOCOLS: protocol at %p is %s",
2902 protocols[i], protocols[i]->name);
2905 if (PrintProtocols) {
2906 _objc_inform("PROTOCOLS: protocol at %p is %s (duplicate)",
2907 protocols[i], protocols[i]->name);
2913 protocol_t **protocols;
2914 protocols = _getObjc2ProtocolRefs(hi, &count);
2915 for (i = 0; i < count; i++) {
2916 remapProtocolRef(&protocols[i]);
2920 // Realize non-lazy classes (for +load methods and static instances)
2922 class_t **classlist =
2923 _getObjc2NonlazyClassList(hi, &count);
2924 for (i = 0; i < count; i++) {
2925 realizeClass(remapClass(classlist[i]));
2929 // Realize newly-resolved future classes, in case CF manipulates them
2930 if (resolvedFutureClasses) {
2931 for (i = 0; i < resolvedFutureClassCount; i++) {
2932 realizeClass(resolvedFutureClasses[i]);
2934 _free_internal(resolvedFutureClasses);
2937 // Discover categories.
2939 category_t **catlist =
2940 _getObjc2CategoryList(hi, &count);
2941 for (i = 0; i < count; i++) {
2942 category_t *cat = catlist[i];
2943 // Do NOT use cat->cls! It may have been remapped.
2944 class_t *cls = remapClass(cat->cls);
2947 // Category's target class is missing (probably weak-linked).
2948 // Disavow any knowledge of this category.
2950 if (PrintConnecting) {
2951 _objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with "
2952 "missing weak-linked target class",
2958 // Process this category.
2959 // First, register the category with its target class.
2960 // Then, rebuild the class's method lists (etc) if
2961 // the class is realized.
2962 BOOL classExists = NO;
2963 if (cat->instanceMethods || cat->protocols
2964 || cat->instanceProperties)
2966 addUnattachedCategoryForClass(cat, cls, hi);
2967 if (isRealized(cls)) {
2968 remethodizeClass(cls);
2971 if (PrintConnecting) {
2972 _objc_inform("CLASS: found category -%s(%s) %s",
2973 getName(cls), cat->name,
2974 classExists ? "on existing class" : "");
2978 if (cat->classMethods || cat->protocols
2979 /* || cat->classProperties */)
2981 addUnattachedCategoryForClass(cat, cls->isa, hi);
2982 if (isRealized(cls->isa)) {
2983 remethodizeClass(cls->isa);
2985 if (PrintConnecting) {
2986 _objc_inform("CLASS: found category +%s(%s)",
2987 getName(cls), cat->name);
2993 // Category discovery MUST BE LAST to avoid potential races
2994 // when other threads call the new category code before
2995 // this thread finishes its fixups.
2997 // +load handled by prepare_load_methods()
2999 if (DebugNonFragileIvars) {
3000 realizeAllClasses();
3007 /***********************************************************************
3008 * prepare_load_methods
3009 * Schedule +load for classes in this image, any un-+load-ed
3010 * superclasses in other images, and any categories in this image.
3011 **********************************************************************/
3012 // Recursively schedule +load for cls and any un-+load-ed superclasses.
3013 // cls must already be connected.
3014 static void schedule_class_load(class_t *cls)
3017 assert(isRealized(cls)); // _read_images should realize
3019 if (cls->data()->flags & RW_LOADED) return;
3021 // Ensure superclass-first ordering
3022 schedule_class_load(getSuperclass(cls));
3024 add_class_to_loadable_list((Class)cls);
3025 changeInfo(cls, RW_LOADED, 0);
3028 PRIVATE_EXTERN void prepare_load_methods(header_info *hi)
3032 rwlock_assert_writing(&runtimeLock);
3034 class_t **classlist =
3035 _getObjc2NonlazyClassList(hi, &count);
3036 for (i = 0; i < count; i++) {
3037 schedule_class_load(remapClass(classlist[i]));
3040 category_t **categorylist = _getObjc2NonlazyCategoryList(hi, &count);
3041 for (i = 0; i < count; i++) {
3042 category_t *cat = categorylist[i];
3043 // Do NOT use cat->cls! It may have been remapped.
3044 class_t *cls = remapClass(cat->cls);
3045 if (!cls) continue; // category for ignored weak-linked class
3047 assert(isRealized(cls->isa));
3048 add_category_to_loadable_list((Category)cat);
3053 /***********************************************************************
3055 * Only handles MH_BUNDLE for now.
3056 * Locking: write-lock and loadMethodLock acquired by unmap_image
3057 **********************************************************************/
3058 PRIVATE_EXTERN void _unload_image(header_info *hi)
3062 recursive_mutex_assert_locked(&loadMethodLock);
3063 rwlock_assert_writing(&runtimeLock);
3065 // Unload unattached categories and categories waiting for +load.
3067 category_t **catlist = _getObjc2CategoryList(hi, &count);
3068 for (i = 0; i < count; i++) {
3069 category_t *cat = catlist[i];
3070 if (!cat) continue; // category for ignored weak-linked class
3071 class_t *cls = remapClass(cat->cls);
3072 assert(cls); // shouldn't have live category for dead class
3074 // fixme for MH_DYLIB cat's class may have been unloaded already
3077 removeUnattachedCategoryForClass(cat, cls);
3080 remove_category_from_loadable_list((Category)cat);
3085 class_t **classlist = _getObjc2ClassList(hi, &count);
3086 for (i = 0; i < count; i++) {
3087 class_t *cls = classlist[i];
3088 // fixme remapped classes?
3089 // fixme ignored weak-linked classes
3091 remove_class_from_loadable_list((Class)cls);
3092 unload_class(cls->isa, YES);
3093 unload_class(cls, NO);
3097 // XXX FIXME -- Clean up protocols:
3098 // <rdar://problem/9033191> Support unloading protocols at dylib/image unload time
3100 // fixme DebugUnload
3104 /***********************************************************************
3105 * method_getDescription
3106 * Returns a pointer to this method's objc_method_description.
3108 **********************************************************************/
3109 struct objc_method_description *
3110 method_getDescription(Method m)
3112 if (!m) return NULL;
3113 return (struct objc_method_description *)newmethod(m);
3117 /***********************************************************************
3118 * method_getImplementation
3119 * Returns this method's IMP.
3121 **********************************************************************/
3123 _method_getImplementation(method_t *m)
3125 if (!m) return NULL;
3130 method_getImplementation(Method m)
3132 return _method_getImplementation(newmethod(m));
3136 /***********************************************************************
3138 * Returns this method's selector.
3139 * The method must not be NULL.
3140 * The method must already have been fixed-up.
3142 **********************************************************************/
3144 method_getName(Method m_gen)
3146 method_t *m = newmethod(m_gen);
3147 if (!m) return NULL;
3149 assert((SEL)m->name == sel_registerName((char *)m->name));
3150 return (SEL)m->name;
3154 /***********************************************************************
3155 * method_getTypeEncoding
3156 * Returns this method's old-style type encoding string.
3157 * The method must not be NULL.
3159 **********************************************************************/
3161 method_getTypeEncoding(Method m)
3163 if (!m) return NULL;
3164 return newmethod(m)->types;
3168 /***********************************************************************
3169 * method_setImplementation
3170 * Sets this method's implementation to imp.
3171 * The previous implementation is returned.
3172 **********************************************************************/
3174 _method_setImplementation(class_t *cls, method_t *m, IMP imp)
3176 rwlock_assert_writing(&runtimeLock);
3178 if (!m) return NULL;
3179 if (!imp) return NULL;
3181 if (ignoreSelector(m->name)) {
3182 // Ignored methods stay ignored
3186 IMP old = _method_getImplementation(m);
3189 // No cache flushing needed - cache contains Methods not IMPs.
3191 if (vtable_containsSelector(newmethod(m)->name)) {
3192 // Will be slow if cls is NULL (i.e. unknown)
3193 // fixme build list of classes whose Methods are known externally?
3197 // fixme catch NSObject changing to custom RR
3198 // cls->setCustomRR();
3200 // fixme update monomorphism if necessary
3206 method_setImplementation(Method m, IMP imp)
3208 // Don't know the class - will be slow if vtables are affected
3209 // fixme build list of classes whose Methods are known externally?
3211 rwlock_write(&runtimeLock);
3212 result = _method_setImplementation(Nil, newmethod(m), imp);
3213 rwlock_unlock_write(&runtimeLock);
3218 void method_exchangeImplementations(Method m1_gen, Method m2_gen)
3220 method_t *m1 = newmethod(m1_gen);
3221 method_t *m2 = newmethod(m2_gen);
3222 if (!m1 || !m2) return;
3224 rwlock_write(&runtimeLock);
3226 if (ignoreSelector(m1->name) || ignoreSelector(m2->name)) {
3227 // Ignored methods stay ignored. Now they're both ignored.
3228 m1->imp = (IMP)&_objc_ignored_method;
3229 m2->imp = (IMP)&_objc_ignored_method;
3230 rwlock_unlock_write(&runtimeLock);
3234 IMP m1_imp = m1->imp;
3238 if (vtable_containsSelector(m1->name) ||
3239 vtable_containsSelector(m2->name))
3241 // Don't know the class - will be slow if vtables are affected
3242 // fixme build list of classes whose Methods are known externally?
3246 // fixme catch NSObject changing to custom RR
3247 // cls->setCustomRR();
3249 // fixme update monomorphism if necessary
3251 rwlock_unlock_write(&runtimeLock);
3255 /***********************************************************************
3259 **********************************************************************/
3261 ivar_getOffset(Ivar ivar)
3263 if (!ivar) return 0;
3264 return *newivar(ivar)->offset;
3268 /***********************************************************************
3272 **********************************************************************/
3274 ivar_getName(Ivar ivar)
3276 if (!ivar) return NULL;
3277 return newivar(ivar)->name;
3281 /***********************************************************************
3282 * ivar_getTypeEncoding
3285 **********************************************************************/
3287 ivar_getTypeEncoding(Ivar ivar)
3289 if (!ivar) return NULL;
3290 return newivar(ivar)->type;
3295 const char *property_getName(objc_property_t prop)
3297 return newproperty(prop)->name;
3300 const char *property_getAttributes(objc_property_t prop)
3302 return newproperty(prop)->attributes;
3305 objc_property_attribute_t *property_copyAttributeList(objc_property_t prop,
3306 unsigned int *outCount)
3309 if (outCount) *outCount = 0;
3313 objc_property_attribute_t *result;
3314 rwlock_read(&runtimeLock);
3315 result = copyPropertyAttributeList(newproperty(prop)->attributes,outCount);
3316 rwlock_unlock_read(&runtimeLock);
3320 char * property_copyAttributeValue(objc_property_t prop, const char *name)
3322 if (!prop || !name || *name == '\0') return NULL;
3325 rwlock_read(&runtimeLock);
3326 result = copyPropertyAttributeValue(newproperty(prop)->attributes, name);
3327 rwlock_unlock_read(&runtimeLock);
3332 /***********************************************************************
3333 * _protocol_getMethod_nolock
3334 * Locking: runtimeLock must be write-locked by the caller
3335 **********************************************************************/
3337 _protocol_getMethod_nolock(protocol_t *proto, SEL sel,
3338 BOOL isRequiredMethod, BOOL isInstanceMethod)
3340 rwlock_assert_writing(&runtimeLock);
3343 if (!proto || !sel) return NULL;
3345 method_list_t **mlistp = NULL;
3347 if (isRequiredMethod) {
3348 if (isInstanceMethod) {
3349 mlistp = &proto->instanceMethods;
3351 mlistp = &proto->classMethods;
3354 if (isInstanceMethod) {
3355 mlistp = &proto->optionalInstanceMethods;
3357 mlistp = &proto->optionalClassMethods;
3362 method_list_t *mlist = *mlistp;
3363 if (!isMethodListFixedUp(mlist)) {
3364 mlist = fixupMethodList(mlist, YES/*always copy for simplicity*/);
3367 for (i = 0; i < mlist->count; i++) {
3368 method_t *m = method_list_nth(mlist, i);
3369 if (sel == m->name) return (Method)m;
3373 if (proto->protocols) {
3375 for (i = 0; i < proto->protocols->count; i++) {
3376 protocol_t *realProto = remapProtocol(proto->protocols->list[i]);
3377 m = _protocol_getMethod_nolock(realProto, sel,
3378 isRequiredMethod, isInstanceMethod);
3387 /***********************************************************************
3388 * _protocol_getMethod
3390 * Locking: write-locks runtimeLock
3391 **********************************************************************/
3392 PRIVATE_EXTERN Method
3393 _protocol_getMethod(Protocol *p, SEL sel, BOOL isRequiredMethod, BOOL isInstanceMethod)
3395 rwlock_write(&runtimeLock);
3396 Method result = _protocol_getMethod_nolock(newprotocol(p), sel,
3399 rwlock_unlock_write(&runtimeLock);
3404 /***********************************************************************
3406 * Returns the name of the given protocol.
3407 * Locking: runtimeLock must not be held by the caller
3408 **********************************************************************/
3410 protocol_getName(Protocol *proto)
3412 return newprotocol(proto)->name;
3416 /***********************************************************************
3417 * protocol_getInstanceMethodDescription
3418 * Returns the description of a named instance method.
3419 * Locking: runtimeLock must not be held by the caller
3420 **********************************************************************/
3421 struct objc_method_description
3422 protocol_getMethodDescription(Protocol *p, SEL aSel,
3423 BOOL isRequiredMethod, BOOL isInstanceMethod)
3426 _protocol_getMethod(p, aSel, isRequiredMethod, isInstanceMethod);
3427 if (m) return *method_getDescription(m);
3428 else return (struct objc_method_description){NULL, NULL};
3432 /***********************************************************************
3433 * _protocol_conformsToProtocol_nolock
3434 * Returns YES if self conforms to other.
3435 * Locking: runtimeLock must be held by the caller.
3436 **********************************************************************/
3437 static BOOL _protocol_conformsToProtocol_nolock(protocol_t *self, protocol_t *other)
3439 if (!self || !other) {
3443 if (0 == strcmp(self->name, other->name)) {
3447 if (self->protocols) {
3449 for (i = 0; i < self->protocols->count; i++) {
3450 protocol_t *proto = remapProtocol(self->protocols->list[i]);
3451 if (0 == strcmp(other->name, proto->name)) {
3454 if (_protocol_conformsToProtocol_nolock(proto, other)) {
3464 /***********************************************************************
3465 * protocol_conformsToProtocol
3466 * Returns YES if self conforms to other.
3467 * Locking: acquires runtimeLock
3468 **********************************************************************/
3469 BOOL protocol_conformsToProtocol(Protocol *self, Protocol *other)
3472 rwlock_read(&runtimeLock);
3473 result = _protocol_conformsToProtocol_nolock(newprotocol(self),
3474 newprotocol(other));
3475 rwlock_unlock_read(&runtimeLock);
3480 /***********************************************************************
3482 * Return YES if two protocols are equal (i.e. conform to each other)
3483 * Locking: acquires runtimeLock
3484 **********************************************************************/
3485 BOOL protocol_isEqual(Protocol *self, Protocol *other)
3487 if (self == other) return YES;
3488 if (!self || !other) return NO;
3490 if (!protocol_conformsToProtocol(self, other)) return NO;
3491 if (!protocol_conformsToProtocol(other, self)) return NO;
3497 /***********************************************************************
3498 * protocol_copyMethodDescriptionList
3499 * Returns descriptions of a protocol's methods.
3500 * Locking: acquires runtimeLock
3501 **********************************************************************/
3502 struct objc_method_description *
3503 protocol_copyMethodDescriptionList(Protocol *p,
3504 BOOL isRequiredMethod,BOOL isInstanceMethod,
3505 unsigned int *outCount)
3507 protocol_t *proto = newprotocol(p);
3508 struct objc_method_description *result = NULL;
3509 unsigned int count = 0;
3512 if (outCount) *outCount = 0;
3516 rwlock_read(&runtimeLock);
3518 method_list_t *mlist = NULL;
3520 if (isRequiredMethod) {
3521 if (isInstanceMethod) {
3522 mlist = proto->instanceMethods;
3524 mlist = proto->classMethods;
3527 if (isInstanceMethod) {
3528 mlist = proto->optionalInstanceMethods;
3530 mlist = proto->optionalClassMethods;
3536 count = mlist->count;
3537 result = (struct objc_method_description *)
3538 calloc(count + 1, sizeof(struct objc_method_description));
3539 for (i = 0; i < count; i++) {
3540 method_t *m = method_list_nth(mlist, i);
3541 result[i].name = sel_registerName((const char *)m->name);
3542 result[i].types = (char *)m->types;
3546 rwlock_unlock_read(&runtimeLock);
3548 if (outCount) *outCount = count;
3553 /***********************************************************************
3554 * protocol_getProperty
3556 * Locking: acquires runtimeLock
3557 **********************************************************************/
3559 _protocol_getProperty_nolock(protocol_t *proto, const char *name,
3560 BOOL isRequiredProperty, BOOL isInstanceProperty)
3562 if (!isRequiredProperty || !isInstanceProperty) {
3563 // Only required instance properties are currently supported
3567 property_list_t *plist;
3568 if ((plist = proto->instanceProperties)) {
3570 for (i = 0; i < plist->count; i++) {
3571 property_t *prop = property_list_nth(plist, i);
3572 if (0 == strcmp(name, prop->name)) {
3578 if (proto->protocols) {
3580 for (i = 0; i < proto->protocols->count; i++) {
3581 protocol_t *p = remapProtocol(proto->protocols->list[i]);
3583 _protocol_getProperty_nolock(p, name,
3585 isInstanceProperty);
3586 if (prop) return prop;
3593 objc_property_t protocol_getProperty(Protocol *p, const char *name,
3594 BOOL isRequiredProperty, BOOL isInstanceProperty)
3598 if (!p || !name) return NULL;
3600 rwlock_read(&runtimeLock);
3601 result = _protocol_getProperty_nolock(newprotocol(p), name,
3603 isInstanceProperty);
3604 rwlock_unlock_read(&runtimeLock);
3606 return (objc_property_t)result;
3610 /***********************************************************************
3611 * protocol_copyPropertyList
3613 * Locking: acquires runtimeLock
3614 **********************************************************************/
3615 static property_t **
3616 copyPropertyList(property_list_t *plist, unsigned int *outCount)
3618 property_t **result = NULL;
3619 unsigned int count = 0;
3622 count = plist->count;
3627 result = (property_t **)malloc((count+1) * sizeof(property_t *));
3629 for (i = 0; i < count; i++) {
3630 result[i] = property_list_nth(plist, i);
3635 if (outCount) *outCount = count;
3639 objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)
3641 property_t **result = NULL;
3644 if (outCount) *outCount = 0;
3648 rwlock_read(&runtimeLock);
3650 property_list_t *plist = newprotocol(proto)->instanceProperties;
3651 result = copyPropertyList(plist, outCount);
3653 rwlock_unlock_read(&runtimeLock);
3655 return (objc_property_t *)result;
3659 /***********************************************************************
3660 * protocol_copyProtocolList
3661 * Copies this protocol's incorporated protocols.
3662 * Does not copy those protocol's incorporated protocols in turn.
3663 * Locking: acquires runtimeLock
3664 **********************************************************************/
3665 Protocol * __unsafe_unretained *
3666 protocol_copyProtocolList(Protocol *p, unsigned int *outCount)
3668 unsigned int count = 0;
3669 Protocol **result = NULL;
3670 protocol_t *proto = newprotocol(p);
3673 if (outCount) *outCount = 0;
3677 rwlock_read(&runtimeLock);
3679 if (proto->protocols) {
3680 count = (unsigned int)proto->protocols->count;
3683 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
3686 for (i = 0; i < count; i++) {
3687 result[i] = (Protocol *)remapProtocol(proto->protocols->list[i]);
3692 rwlock_unlock_read(&runtimeLock);
3694 if (outCount) *outCount = count;
3699 /***********************************************************************
3700 * objc_allocateProtocol
3701 * Creates a new protocol. The protocol may not be used until
3702 * objc_registerProtocol() is called.
3703 * Returns NULL if a protocol with the same name already exists.
3704 * Locking: acquires runtimeLock
3705 **********************************************************************/
3707 objc_allocateProtocol(const char *name)
3709 rwlock_write(&runtimeLock);
3711 if (NXMapGet(protocols(), name)) {
3712 rwlock_unlock_write(&runtimeLock);
3716 protocol_t *result = (protocol_t *)_calloc_internal(sizeof(protocol_t), 1);
3718 extern class_t OBJC_CLASS_$___IncompleteProtocol;
3719 Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
3721 result->name = _strdup_internal(name);
3723 // fixme reserve name without installing
3725 rwlock_unlock_write(&runtimeLock);
3727 return (Protocol *)result;
3731 /***********************************************************************
3732 * objc_registerProtocol
3733 * Registers a newly-constructed protocol. The protocol is now
3734 * ready for use and immutable.
3735 * Locking: acquires runtimeLock
3736 **********************************************************************/
3737 void objc_registerProtocol(Protocol *proto_gen)
3739 protocol_t *proto = newprotocol(proto_gen);
3741 rwlock_write(&runtimeLock);
3743 extern class_t OBJC_CLASS_$___IncompleteProtocol;
3744 Class oldcls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
3745 extern class_t OBJC_CLASS_$_Protocol;
3746 Class cls = (Class)&OBJC_CLASS_$_Protocol;
3748 if (proto->isa == cls) {
3749 _objc_inform("objc_registerProtocol: protocol '%s' was already "
3750 "registered!", proto->name);
3751 rwlock_unlock_write(&runtimeLock);
3754 if (proto->isa != oldcls) {
3755 _objc_inform("objc_registerProtocol: protocol '%s' was not allocated "
3756 "with objc_allocateProtocol!", proto->name);
3757 rwlock_unlock_write(&runtimeLock);
3763 NXMapKeyCopyingInsert(protocols(), proto->name, proto);
3765 rwlock_unlock_write(&runtimeLock);
3769 /***********************************************************************
3770 * protocol_addProtocol
3771 * Adds an incorporated protocol to another protocol.
3772 * No method enforcement is performed.
3773 * `proto` must be under construction. `addition` must not.
3774 * Locking: acquires runtimeLock
3775 **********************************************************************/
3777 protocol_addProtocol(Protocol *proto_gen, Protocol *addition_gen)
3779 protocol_t *proto = newprotocol(proto_gen);
3780 protocol_t *addition = newprotocol(addition_gen);
3782 extern class_t OBJC_CLASS_$___IncompleteProtocol;
3783 Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
3785 if (!proto_gen) return;
3786 if (!addition_gen) return;
3788 rwlock_write(&runtimeLock);
3790 if (proto->isa != cls) {
3791 _objc_inform("protocol_addProtocol: modified protocol '%s' is not "
3792 "under construction!", proto->name);
3793 rwlock_unlock_write(&runtimeLock);
3796 if (addition->isa == cls) {
3797 _objc_inform("protocol_addProtocol: added protocol '%s' is still "
3798 "under construction!", addition->name);
3799 rwlock_unlock_write(&runtimeLock);
3803 protocol_list_t *protolist = proto->protocols;
3805 protolist = (protocol_list_t *)
3806 _calloc_internal(1, sizeof(protocol_list_t)
3807 + sizeof(protolist->list[0]));
3809 protolist = (protocol_list_t *)
3810 _realloc_internal(protolist, protocol_list_size(protolist)
3811 + sizeof(protolist->list[0]));
3814 protolist->list[protolist->count++] = (protocol_ref_t)addition;
3815 proto->protocols = protolist;
3817 rwlock_unlock_write(&runtimeLock);
3821 /***********************************************************************
3822 * protocol_addMethodDescription
3823 * Adds a method to a protocol. The protocol must be under construction.
3824 * Locking: acquires runtimeLock
3825 **********************************************************************/
3827 _protocol_addMethod(method_list_t **list, SEL name, const char *types)
3830 *list = (method_list_t *)
3831 _calloc_internal(sizeof(method_list_t), 1);
3832 (*list)->entsize_NEVER_USE = sizeof((*list)->first);
3833 setMethodListFixedUp(*list);
3835 size_t size = method_list_size(*list) + method_list_entsize(*list);
3836 *list = (method_list_t *)
3837 _realloc_internal(*list, size);
3840 method_t *meth = method_list_nth(*list, (*list)->count++);
3842 meth->types = _strdup_internal(types ? types : "");
3847 protocol_addMethodDescription(Protocol *proto_gen, SEL name, const char *types,
3848 BOOL isRequiredMethod, BOOL isInstanceMethod)
3850 protocol_t *proto = newprotocol(proto_gen);
3852 extern class_t OBJC_CLASS_$___IncompleteProtocol;
3853 Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
3855 if (!proto_gen) return;
3857 rwlock_write(&runtimeLock);
3859 if (proto->isa != cls) {
3860 _objc_inform("protocol_addMethodDescription: protocol '%s' is not "
3861 "under construction!", proto->name);
3862 rwlock_unlock_write(&runtimeLock);
3866 if (isRequiredMethod && isInstanceMethod) {
3867 _protocol_addMethod(&proto->instanceMethods, name, types);
3868 } else if (isRequiredMethod && !isInstanceMethod) {
3869 _protocol_addMethod(&proto->classMethods, name, types);
3870 } else if (!isRequiredMethod && isInstanceMethod) {
3871 _protocol_addMethod(&proto->optionalInstanceMethods, name, types);
3872 } else /* !isRequiredMethod && !isInstanceMethod) */ {
3873 _protocol_addMethod(&proto->optionalClassMethods, name, types);
3876 rwlock_unlock_write(&runtimeLock);
3880 /***********************************************************************
3881 * protocol_addProperty
3882 * Adds a property to a protocol. The protocol must be under construction.
3883 * Locking: acquires runtimeLock
3884 **********************************************************************/
3886 _protocol_addProperty(property_list_t **plist, const char *name,
3887 const objc_property_attribute_t *attrs,
3891 *plist = (property_list_t *)
3892 _calloc_internal(sizeof(property_list_t), 1);
3893 (*plist)->entsize = sizeof(property_t);
3895 *plist = (property_list_t *)
3896 _realloc_internal(*plist, sizeof(property_list_t)
3897 + (*plist)->count * (*plist)->entsize);
3900 property_t *prop = property_list_nth(*plist, (*plist)->count++);
3901 prop->name = _strdup_internal(name);
3902 prop->attributes = copyPropertyAttributeString(attrs, count);
3906 protocol_addProperty(Protocol *proto_gen, const char *name,
3907 const objc_property_attribute_t *attrs,
3909 BOOL isRequiredProperty, BOOL isInstanceProperty)
3911 protocol_t *proto = newprotocol(proto_gen);
3913 extern class_t OBJC_CLASS_$___IncompleteProtocol;
3914 Class cls = (Class)&OBJC_CLASS_$___IncompleteProtocol;
3919 rwlock_write(&runtimeLock);
3921 if (proto->isa != cls) {
3922 _objc_inform("protocol_addProperty: protocol '%s' is not "
3923 "under construction!", proto->name);
3924 rwlock_unlock_write(&runtimeLock);
3928 if (isRequiredProperty && isInstanceProperty) {
3929 _protocol_addProperty(&proto->instanceProperties, name, attrs, count);
3931 //else if (isRequiredProperty && !isInstanceProperty) {
3932 // _protocol_addProperty(&proto->classProperties, name, attrs, count);
3933 //} else if (!isRequiredProperty && isInstanceProperty) {
3934 // _protocol_addProperty(&proto->optionalInstanceProperties, name, attrs, count);
3935 //} else /* !isRequiredProperty && !isInstanceProperty) */ {
3936 // _protocol_addProperty(&proto->optionalClassProperties, name, attrs, count);
3939 rwlock_unlock_write(&runtimeLock);
3943 /***********************************************************************
3945 * Returns pointers to all classes.
3946 * This requires all classes be realized, which is regretfully non-lazy.
3947 * Locking: acquires runtimeLock
3948 **********************************************************************/
3950 objc_getClassList(Class *buffer, int bufferLen)
3952 rwlock_write(&runtimeLock);
3954 realizeAllClasses();
3959 NXHashTable *classes = realizedClasses();
3960 int allCount = NXCountHashTable(classes);
3963 rwlock_unlock_write(&runtimeLock);
3968 state = NXInitHashState(classes);
3969 while (count < bufferLen &&
3970 NXNextHashState(classes, &state, (void **)&cls))
3972 buffer[count++] = (Class)cls;
3975 rwlock_unlock_write(&runtimeLock);
3981 /***********************************************************************
3982 * objc_copyClassList
3983 * Returns pointers to all classes.
3984 * This requires all classes be realized, which is regretfully non-lazy.
3986 * outCount may be NULL. *outCount is the number of classes returned.
3987 * If the returned array is not NULL, it is NULL-terminated and must be
3988 * freed with free().
3989 * Locking: write-locks runtimeLock
3990 **********************************************************************/
3992 objc_copyClassList(unsigned int *outCount)
3994 rwlock_write(&runtimeLock);
3996 realizeAllClasses();
3998 Class *result = NULL;
3999 NXHashTable *classes = realizedClasses();
4000 unsigned int count = NXCountHashTable(classes);
4004 NXHashState state = NXInitHashState(classes);
4005 result = (Class *)malloc((1+count) * sizeof(Class));
4007 while (NXNextHashState(classes, &state, (void **)&cls)) {
4008 result[count++] = (Class)cls;
4010 result[count] = NULL;
4013 rwlock_unlock_write(&runtimeLock);
4015 if (outCount) *outCount = count;
4020 /***********************************************************************
4021 * objc_copyProtocolList
4022 * Returns pointers to all protocols.
4023 * Locking: read-locks runtimeLock
4024 **********************************************************************/
4025 Protocol * __unsafe_unretained *
4026 objc_copyProtocolList(unsigned int *outCount)
4028 rwlock_read(&runtimeLock);
4030 unsigned int count, i;
4034 NXMapTable *protocol_map = protocols();
4037 count = NXCountMapTable(protocol_map);
4039 rwlock_unlock_read(&runtimeLock);
4040 if (outCount) *outCount = 0;
4044 result = (Protocol **)calloc(1 + count, sizeof(Protocol *));
4047 state = NXInitMapState(protocol_map);
4048 while (NXNextMapState(protocol_map, &state,
4049 (const void **)&name, (const void **)&proto))
4051 result[i++] = proto;
4055 assert(i == count+1);
4057 rwlock_unlock_read(&runtimeLock);
4059 if (outCount) *outCount = count;
4064 /***********************************************************************
4066 * Get a protocol by name, or return NULL
4067 * Locking: read-locks runtimeLock
4068 **********************************************************************/
4069 Protocol *objc_getProtocol(const char *name)
4071 rwlock_read(&runtimeLock);
4072 Protocol *result = (Protocol *)NXMapGet(protocols(), name);
4073 rwlock_unlock_read(&runtimeLock);
4078 /***********************************************************************
4079 * class_copyMethodList
4081 * Locking: read-locks runtimeLock
4082 **********************************************************************/
4084 class_copyMethodList(Class cls_gen, unsigned int *outCount)
4086 class_t *cls = newcls(cls_gen);
4087 unsigned int count = 0;
4088 Method *result = NULL;
4091 if (outCount) *outCount = 0;
4095 rwlock_read(&runtimeLock);
4097 assert(isRealized(cls));
4099 FOREACH_METHOD_LIST(mlist, cls, {
4100 count += mlist->count;
4105 result = (Method *)malloc((count + 1) * sizeof(Method));
4108 FOREACH_METHOD_LIST(mlist, cls, {
4110 for (i = 0; i < mlist->count; i++) {
4111 Method aMethod = (Method)method_list_nth(mlist, i);
4112 if (ignoreSelector(method_getName(aMethod))) {
4116 result[m++] = aMethod;
4122 rwlock_unlock_read(&runtimeLock);
4124 if (outCount) *outCount = count;
4129 /***********************************************************************
4130 * class_copyIvarList
4132 * Locking: read-locks runtimeLock
4133 **********************************************************************/
4135 class_copyIvarList(Class cls_gen, unsigned int *outCount)
4137 class_t *cls = newcls(cls_gen);
4138 const ivar_list_t *ivars;
4139 Ivar *result = NULL;
4140 unsigned int count = 0;
4144 if (outCount) *outCount = 0;
4148 rwlock_read(&runtimeLock);
4150 assert(isRealized(cls));
4152 if ((ivars = cls->data()->ro->ivars) && ivars->count) {
4153 result = (Ivar *)malloc((ivars->count+1) * sizeof(Ivar));
4155 for (i = 0; i < ivars->count; i++) {
4156 ivar_t *ivar = ivar_list_nth(ivars, i);
4157 if (!ivar->offset) continue; // anonymous bitfield
4158 result[count++] = (Ivar)ivar;
4160 result[count] = NULL;
4163 rwlock_unlock_read(&runtimeLock);
4165 if (outCount) *outCount = count;
4170 /***********************************************************************
4171 * class_copyPropertyList. Returns a heap block containing the
4172 * properties declared in the class, or NULL if the class
4173 * declares no properties. Caller must free the block.
4174 * Does not copy any superclass's properties.
4175 * Locking: read-locks runtimeLock
4176 **********************************************************************/
4178 class_copyPropertyList(Class cls_gen, unsigned int *outCount)
4180 class_t *cls = newcls(cls_gen);
4181 chained_property_list *plist;
4182 unsigned int count = 0;
4183 property_t **result = NULL;
4186 if (outCount) *outCount = 0;
4190 rwlock_read(&runtimeLock);
4192 assert(isRealized(cls));
4194 for (plist = cls->data()->properties; plist; plist = plist->next) {
4195 count += plist->count;
4200 result = (property_t **)malloc((count + 1) * sizeof(property_t *));
4203 for (plist = cls->data()->properties; plist; plist = plist->next) {
4205 for (i = 0; i < plist->count; i++) {
4206 result[p++] = &plist->list[i];
4212 rwlock_unlock_read(&runtimeLock);
4214 if (outCount) *outCount = count;
4215 return (objc_property_t *)result;
4219 /***********************************************************************
4220 * _class_getLoadMethod
4222 * Called only from add_class_to_loadable_list.
4223 * Locking: runtimeLock must be read- or write-locked by the caller.
4224 **********************************************************************/
4226 _class_getLoadMethod(Class cls_gen)
4228 rwlock_assert_locked(&runtimeLock);
4230 class_t *cls = newcls(cls_gen);
4231 const method_list_t *mlist;
4234 assert(isRealized(cls));
4235 assert(isRealized(cls->isa));
4236 assert(!isMetaClass(cls));
4237 assert(isMetaClass(cls->isa));
4239 mlist = cls->isa->data()->ro->baseMethods;
4240 if (mlist) for (i = 0; i < mlist->count; i++) {
4241 method_t *m = method_list_nth(mlist, i);
4242 if (0 == strcmp((const char *)m->name, "load")) {
4251 /***********************************************************************
4253 * Returns a category's name.
4255 **********************************************************************/
4256 PRIVATE_EXTERN const char *
4257 _category_getName(Category cat)
4259 return newcategory(cat)->name;
4263 /***********************************************************************
4264 * _category_getClassName
4265 * Returns a category's class's name
4266 * Called only from add_category_to_loadable_list and
4267 * remove_category_from_loadable_list.
4268 * Locking: runtimeLock must be read- or write-locked by the caller
4269 **********************************************************************/
4270 PRIVATE_EXTERN const char *
4271 _category_getClassName(Category cat)
4273 rwlock_assert_locked(&runtimeLock);
4274 // cat->cls may have been remapped
4275 return getName(remapClass(newcategory(cat)->cls));
4279 /***********************************************************************
4280 * _category_getClass
4281 * Returns a category's class
4282 * Called only by call_category_loads.
4283 * Locking: read-locks runtimeLock
4284 **********************************************************************/
4285 PRIVATE_EXTERN Class
4286 _category_getClass(Category cat)
4288 rwlock_read(&runtimeLock);
4289 // cat->cls may have been remapped
4290 class_t *result = remapClass(newcategory(cat)->cls);
4291 assert(isRealized(result)); // ok for call_category_loads' usage
4292 rwlock_unlock_read(&runtimeLock);
4293 return (Class)result;
4297 /***********************************************************************
4298 * _category_getLoadMethod
4300 * Called only from add_category_to_loadable_list
4301 * Locking: runtimeLock must be read- or write-locked by the caller
4302 **********************************************************************/
4304 _category_getLoadMethod(Category cat)
4306 rwlock_assert_locked(&runtimeLock);
4308 const method_list_t *mlist;
4311 mlist = newcategory(cat)->classMethods;
4312 if (mlist) for (i = 0; i < mlist->count; i++) {
4313 method_t *m = method_list_nth(mlist, i);
4314 if (0 == strcmp((const char *)m->name, "load")) {
4323 /***********************************************************************
4324 * class_copyProtocolList
4326 * Locking: read-locks runtimeLock
4327 **********************************************************************/
4328 Protocol * __unsafe_unretained *
4329 class_copyProtocolList(Class cls_gen, unsigned int *outCount)
4331 class_t *cls = newcls(cls_gen);
4333 const protocol_list_t **p;
4334 unsigned int count = 0;
4336 Protocol **result = NULL;
4339 if (outCount) *outCount = 0;
4343 rwlock_read(&runtimeLock);
4345 assert(isRealized(cls));
4347 for (p = cls->data()->protocols; p && *p; p++) {
4348 count += (uint32_t)(*p)->count;
4352 result = (Protocol **)malloc((count+1) * sizeof(Protocol *));
4354 for (p = cls->data()->protocols; p && *p; p++) {
4355 for (i = 0; i < (*p)->count; i++) {
4356 *r++ = (Protocol *)remapProtocol((*p)->list[i]);
4362 rwlock_unlock_read(&runtimeLock);
4364 if (outCount) *outCount = count;
4369 /***********************************************************************
4370 * _objc_copyClassNamesForImage
4372 * Locking: read-locks runtimeLock
4373 **********************************************************************/
4374 PRIVATE_EXTERN const char **
4375 _objc_copyClassNamesForImage(header_info *hi, unsigned int *outCount)
4377 size_t count, i, shift;
4378 class_t **classlist;
4381 rwlock_read(&runtimeLock);
4383 classlist = _getObjc2ClassList(hi, &count);
4384 names = (const char **)malloc((count+1) * sizeof(const char *));
4387 for (i = 0; i < count; i++) {
4388 class_t *cls = remapClass(classlist[i]);
4390 names[i-shift] = getName(classlist[i]);
4392 shift++; // ignored weak-linked class
4396 names[count] = NULL;
4398 rwlock_unlock_read(&runtimeLock);
4400 if (outCount) *outCount = (unsigned int)count;
4405 /***********************************************************************
4409 **********************************************************************/
4410 PRIVATE_EXTERN Cache
4411 _class_getCache(Class cls)
4413 return newcls(cls)->cache;
4417 /***********************************************************************
4418 * _class_getInstanceSize
4419 * Uses alignedInstanceSize() to ensure that
4420 * obj + class_getInstanceSize(obj->isa) == object_getIndexedIvars(obj)
4422 **********************************************************************/
4423 PRIVATE_EXTERN size_t
4424 _class_getInstanceSize(Class cls)
4427 return alignedInstanceSize(newcls(cls));
4431 unalignedInstanceSize(class_t *cls)
4434 assert(isRealized(cls));
4435 return (uint32_t)cls->data()->ro->instanceSize;
4439 alignedInstanceSize(class_t *cls)
4442 assert(isRealized(cls));
4443 // fixme rdar://5278267
4444 return (uint32_t)((unalignedInstanceSize(cls) + WORD_MASK) & ~WORD_MASK);
4447 /***********************************************************************
4448 * _class_getInstanceStart
4449 * Uses alignedInstanceStart() to ensure that ARR layout strings are
4450 * interpreted relative to the first word aligned ivar of an object.
4452 **********************************************************************/
4455 alignedInstanceStart(class_t *cls)
4458 assert(isRealized(cls));
4459 return (uint32_t)((cls->data()->ro->instanceStart + WORD_MASK) & ~WORD_MASK);
4463 uint32_t _class_getInstanceStart(Class cls_gen) {
4464 class_t *cls = newcls(cls_gen);
4465 return alignedInstanceStart(cls);
4469 /***********************************************************************
4473 **********************************************************************/
4475 class_getVersion(Class cls)
4478 assert(isRealized(newcls(cls)));
4479 return newcls(cls)->data()->version;
4483 /***********************************************************************
4487 **********************************************************************/
4489 _class_setCache(Class cls, Cache cache)
4491 newcls(cls)->cache = cache;
4495 /***********************************************************************
4499 **********************************************************************/
4501 class_setVersion(Class cls, int version)
4504 assert(isRealized(newcls(cls)));
4505 newcls(cls)->data()->version = version;
4509 /***********************************************************************
4512 * Locking: acquires runtimeLock
4513 **********************************************************************/
4514 PRIVATE_EXTERN const char *_class_getName(Class cls)
4516 if (!cls) return "nil";
4517 // fixme hack rwlock_write(&runtimeLock);
4518 const char *name = getName(newcls(cls));
4519 // rwlock_unlock_write(&runtimeLock);
4524 /***********************************************************************
4527 * Locking: runtimeLock must be held by the caller
4528 **********************************************************************/
4530 getName(class_t *cls)
4532 // fixme hack rwlock_assert_writing(&runtimeLock);
4535 if (isRealized(cls)) {
4536 return cls->data()->ro->name;
4538 return ((const class_ro_t *)cls->data())->name;
4542 static method_t *findMethodInSortedMethodList(SEL key, const method_list_t *list)
4544 const method_t * const first = &list->first;
4545 const method_t *base = first;
4546 const method_t *probe;
4547 uintptr_t keyValue = (uintptr_t)key;
4550 for (count = list->count; count != 0; count >>= 1) {
4551 probe = base + (count >> 1);
4553 uintptr_t probeValue = (uintptr_t)probe->name;
4555 if (keyValue == probeValue) {
4556 // `probe` is a match.
4557 // Rewind looking for the *first* occurrence of this value.
4558 // This is required for correct category overrides.
4559 while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
4562 return (method_t *)probe;
4565 if (keyValue > probeValue) {
4574 /***********************************************************************
4575 * getMethodNoSuper_nolock
4577 * Locking: runtimeLock must be read- or write-locked by the caller
4578 **********************************************************************/
4579 static method_t *search_method_list(const method_list_t *mlist, SEL sel)
4581 int methodListIsFixedUp = isMethodListFixedUp(mlist);
4582 int methodListHasExpectedSize = mlist->getEntsize() == sizeof(method_t);
4584 if (__builtin_expect(methodListIsFixedUp && methodListHasExpectedSize, 1)) {
4585 return findMethodInSortedMethodList(sel, mlist);
4587 // Linear search of unsorted method list
4588 method_list_t::method_iterator iter = mlist->begin();
4589 method_list_t::method_iterator end = mlist->end();
4590 for ( ; iter != end; ++iter) {
4591 if (iter->name == sel) return &*iter;
4596 // sanity-check negative results
4597 if (isMethodListFixedUp(mlist)) {
4598 method_list_t::method_iterator iter = mlist->begin();
4599 method_list_t::method_iterator end = mlist->end();
4600 for ( ; iter != end; ++iter) {
4601 if (iter->name == sel) {
4602 _objc_fatal("linear search worked when binary search did not");
4612 getMethodNoSuper_nolock(class_t *cls, SEL sel)
4614 rwlock_assert_locked(&runtimeLock);
4616 assert(isRealized(cls));
4620 FOREACH_METHOD_LIST(mlist, cls, {
4621 method_t *m = search_method_list(mlist, sel);
4629 /***********************************************************************
4630 * _class_getMethodNoSuper
4632 * Locking: read-locks runtimeLock
4633 **********************************************************************/
4634 PRIVATE_EXTERN Method
4635 _class_getMethodNoSuper(Class cls, SEL sel)
4637 rwlock_read(&runtimeLock);
4638 Method result = (Method)getMethodNoSuper_nolock(newcls(cls), sel);
4639 rwlock_unlock_read(&runtimeLock);
4643 /***********************************************************************
4644 * _class_getMethodNoSuper
4645 * For use inside lockForMethodLookup() only.
4646 * Locking: read-locks runtimeLock
4647 **********************************************************************/
4648 PRIVATE_EXTERN Method
4649 _class_getMethodNoSuper_nolock(Class cls, SEL sel)
4651 return (Method)getMethodNoSuper_nolock(newcls(cls), sel);
4655 /***********************************************************************
4658 * Locking: runtimeLock must be read- or write-locked by the caller
4659 **********************************************************************/
4661 getMethod_nolock(class_t *cls, SEL sel)
4665 rwlock_assert_locked(&runtimeLock);
4670 assert(isRealized(cls));
4672 while (cls && ((m = getMethodNoSuper_nolock(cls, sel))) == NULL) {
4673 cls = getSuperclass(cls);
4680 /***********************************************************************
4683 * Locking: read-locks runtimeLock
4684 **********************************************************************/
4685 PRIVATE_EXTERN Method _class_getMethod(Class cls, SEL sel)
4688 rwlock_read(&runtimeLock);
4689 m = (Method)getMethod_nolock(newcls(cls), sel);
4690 rwlock_unlock_read(&runtimeLock);
4695 /***********************************************************************
4696 * ABI-specific lookUpMethod helpers.
4697 * Locking: read- and write-locks runtimeLock.
4698 **********************************************************************/
4699 PRIVATE_EXTERN void lockForMethodLookup(void)
4701 rwlock_read(&runtimeLock);
4703 PRIVATE_EXTERN void unlockForMethodLookup(void)
4705 rwlock_unlock_read(&runtimeLock);
4708 PRIVATE_EXTERN IMP prepareForMethodLookup(Class cls, SEL sel, BOOL init)
4710 rwlock_assert_unlocked(&runtimeLock);
4712 if (!isRealized(newcls(cls))) {
4713 rwlock_write(&runtimeLock);
4714 realizeClass(newcls(cls));
4715 rwlock_unlock_write(&runtimeLock);
4718 if (init && !_class_isInitialized(cls)) {
4719 _class_initialize (cls);
4720 // If sel == initialize, _class_initialize will send +initialize and
4721 // then the messenger will send +initialize again after this
4722 // procedure finishes. Of course, if this is not being called
4723 // from the messenger then it won't happen. 2778172
4730 /***********************************************************************
4733 * Locking: read-locks runtimeLock
4734 **********************************************************************/
4735 objc_property_t class_getProperty(Class cls_gen, const char *name)
4737 property_t *result = NULL;
4738 chained_property_list *plist;
4739 class_t *cls = newcls(cls_gen);
4741 if (!cls || !name) return NULL;
4743 rwlock_read(&runtimeLock);
4745 assert(isRealized(cls));
4747 for ( ; cls; cls = getSuperclass(cls)) {
4748 for (plist = cls->data()->properties; plist; plist = plist->next) {
4750 for (i = 0; i < plist->count; i++) {
4751 if (0 == strcmp(name, plist->list[i].name)) {
4752 result = &plist->list[i];
4760 rwlock_unlock_read(&runtimeLock);
4762 return (objc_property_t)result;
4766 /***********************************************************************
4768 **********************************************************************/
4769 PRIVATE_EXTERN BOOL _class_isMetaClass(Class cls)
4771 if (!cls) return NO;
4772 return isMetaClass(newcls(cls));
4776 isMetaClass(class_t *cls)
4779 assert(isRealized(cls));
4780 return (cls->data()->ro->flags & RO_META) ? YES : NO;
4784 PRIVATE_EXTERN Class _class_getMeta(Class cls)
4787 if (isMetaClass(newcls(cls))) return cls;
4788 else return ((id)cls)->isa;
4791 Class gdb_class_getClass(Class cls)
4793 const char *className = getName(newcls(cls));
4794 if(!className || !strlen(className)) return Nil;
4795 Class rCls = look_up_class(className, NO, NO);
4799 Class gdb_object_getClass(id obj)
4801 Class cls = _object_getClass(obj);
4802 return gdb_class_getClass(cls);
4805 BOOL gdb_objc_isRuntimeLocked()
4807 if (rwlock_try_write(&runtimeLock)) {
4808 rwlock_unlock_write(&runtimeLock);
4812 if (mutex_try_lock(&cacheUpdateLock)) {
4813 mutex_unlock(&cacheUpdateLock);
4820 /***********************************************************************
4822 **********************************************************************/
4824 _class_isInitializing(Class cls_gen)
4826 class_t *cls = newcls(_class_getMeta(cls_gen));
4827 return (cls->data()->flags & RW_INITIALIZING) ? YES : NO;
4831 /***********************************************************************
4833 **********************************************************************/
4835 _class_isInitialized(Class cls_gen)
4837 class_t *cls = newcls(_class_getMeta(cls_gen));
4838 return (cls->data()->flags & RW_INITIALIZED) ? YES : NO;
4842 /***********************************************************************
4844 **********************************************************************/
4846 _class_setInitializing(Class cls_gen)
4848 class_t *cls = newcls(_class_getMeta(cls_gen));
4849 changeInfo(cls, RW_INITIALIZING, 0);
4853 /***********************************************************************
4854 * Locking: write-locks runtimeLock
4855 **********************************************************************/
4857 _class_setInitialized(Class cls_gen)
4863 rwlock_write(&runtimeLock);
4864 metacls = newcls(_class_getMeta(cls_gen));
4865 cls = getNonMetaClass(metacls);
4867 // Update vtables (initially postponed pending +initialize completion)
4868 // Do cls first because root metacls is a subclass of root cls
4869 updateVtable(cls, YES);
4870 updateVtable(metacls, YES);
4872 rwlock_unlock_write(&runtimeLock);
4874 changeInfo(metacls, RW_INITIALIZED, RW_INITIALIZING);
4878 /***********************************************************************
4880 **********************************************************************/
4882 _class_shouldGrowCache(Class cls)
4884 return YES; // fixme good or bad for memory use?
4888 /***********************************************************************
4890 **********************************************************************/
4892 _class_setGrowCache(Class cls, BOOL grow)
4894 // fixme good or bad for memory use?
4898 /***********************************************************************
4902 **********************************************************************/
4904 _class_isLoadable(Class cls)
4906 assert(isRealized(newcls(cls)));
4907 return YES; // any class registered for +load is definitely loadable
4911 /***********************************************************************
4913 **********************************************************************/
4915 hasCxxStructors(class_t *cls)
4917 // this DOES check superclasses too, because addSubclass()
4918 // propagates the flag from the superclass.
4919 assert(isRealized(cls));
4920 return (cls->data()->flags & RW_HAS_CXX_STRUCTORS) ? YES : NO;
4924 _class_hasCxxStructors(Class cls)
4926 return hasCxxStructors(newcls(cls));
4930 /***********************************************************************
4932 **********************************************************************/
4934 _class_shouldFinalizeOnMainThread(Class cls)
4936 assert(isRealized(newcls(cls)));
4937 return (newcls(cls)->data()->flags & RW_FINALIZE_ON_MAIN_THREAD) ? YES : NO;
4941 /***********************************************************************
4943 **********************************************************************/
4945 _class_setFinalizeOnMainThread(Class cls)
4947 assert(isRealized(newcls(cls)));
4948 changeInfo(newcls(cls), RW_FINALIZE_ON_MAIN_THREAD, 0);
4952 /***********************************************************************
4953 * _class_instancesHaveAssociatedObjects
4954 * May manipulate unrealized future classes in the CF-bridged case.
4955 **********************************************************************/
4957 _class_instancesHaveAssociatedObjects(Class cls_gen)
4959 class_t *cls = newcls(cls_gen);
4960 assert(isFuture(cls) || isRealized(cls));
4961 return (cls->data()->flags & RW_INSTANCES_HAVE_ASSOCIATED_OBJECTS) ? YES : NO;
4965 /***********************************************************************
4966 * _class_setInstancesHaveAssociatedObjects
4967 * May manipulate unrealized future classes in the CF-bridged case.
4968 **********************************************************************/
4970 _class_setInstancesHaveAssociatedObjects(Class cls_gen)
4972 class_t *cls = newcls(cls_gen);
4973 assert(isFuture(cls) || isRealized(cls));
4974 changeInfo(cls, RW_INSTANCES_HAVE_ASSOCIATED_OBJECTS, 0);
4978 /***********************************************************************
4979 * _class_usesAutomaticRetainRelease
4980 * Returns YES if class was compiled with -fobjc-arr
4981 **********************************************************************/
4982 BOOL _class_usesAutomaticRetainRelease(Class cls_gen)
4984 class_t *cls = newcls(cls_gen);
4985 return (cls->data()->ro->flags & RO_IS_ARR) ? YES : NO;
4989 /***********************************************************************
4990 * Return YES if sel is used by retain/release implementors
4991 **********************************************************************/
4992 static BOOL isRRSelector(SEL sel)
4994 return (sel == SEL_retain || sel == SEL_release ||
4995 sel == SEL_autorelease || sel == SEL_retainCount) ? YES : NO;
4999 /***********************************************************************
5000 * Mark this class and all of its subclasses as implementors or
5001 * inheritors of custom RR (retain/release/autorelease/retainCount)
5002 **********************************************************************/
5003 void class_t::setHasCustomRR()
5005 rwlock_assert_writing(&runtimeLock);
5007 if (hasCustomRR()) return;
5009 FOREACH_REALIZED_CLASS_AND_SUBCLASS(c, this, {
5010 // rdar://8955342 c->data_NEVER_USE |= 1UL;
5011 c->data()->flags |= RW_HAS_CUSTOM_RR;
5016 /***********************************************************************
5017 * Unmark custom RR. Not recursive. Almost never used.
5018 **********************************************************************/
5019 void class_t::unsetHasCustomRR()
5021 rwlock_assert_writing(&runtimeLock);
5023 this->data_NEVER_USE &= ~1UL;
5027 /***********************************************************************
5029 * fixme assert realized to get superclass remapping?
5030 **********************************************************************/
5031 PRIVATE_EXTERN Class
5032 _class_getSuperclass(Class cls)
5034 return (Class)getSuperclass(newcls(cls));
5038 getSuperclass(class_t *cls)
5040 if (!cls) return NULL;
5041 return cls->superclass;
5045 /***********************************************************************
5046 * class_getIvarLayout
5047 * Called by the garbage collector.
5048 * The class must be NULL or already realized.
5050 **********************************************************************/
5052 class_getIvarLayout(Class cls_gen)
5054 class_t *cls = newcls(cls_gen);
5055 if (cls) return cls->data()->ro->ivarLayout;
5060 /***********************************************************************
5061 * class_getWeakIvarLayout
5062 * Called by the garbage collector.
5063 * The class must be NULL or already realized.
5065 **********************************************************************/
5067 class_getWeakIvarLayout(Class cls_gen)
5069 class_t *cls = newcls(cls_gen);
5070 if (cls) return cls->data()->ro->weakIvarLayout;
5075 /***********************************************************************
5076 * class_setIvarLayout
5077 * Changes the class's GC scan layout.
5078 * NULL layout means no unscanned ivars
5079 * The class must be under construction.
5080 * fixme: sanity-check layout vs instance size?
5081 * fixme: sanity-check layout vs superclass?
5082 * Locking: acquires runtimeLock
5083 **********************************************************************/
5085 class_setIvarLayout(Class cls_gen, const uint8_t *layout)
5087 class_t *cls = newcls(cls_gen);
5090 rwlock_write(&runtimeLock);
5092 // Can only change layout of in-construction classes.
5093 // note: if modifications to post-construction classes were
5094 // allowed, there would be a race below (us vs. concurrent GC scan)
5095 if (!(cls->data()->flags & RW_CONSTRUCTING)) {
5096 _objc_inform("*** Can't set ivar layout for already-registered "
5097 "class '%s'", getName(cls));
5098 rwlock_unlock_write(&runtimeLock);
5102 class_ro_t *ro_w = make_ro_writeable(cls->data());
5104 try_free(ro_w->ivarLayout);
5105 ro_w->ivarLayout = _ustrdup_internal(layout);
5107 rwlock_unlock_write(&runtimeLock);
5110 // SPI: Instance-specific object layout.
5113 _class_setIvarLayoutAccessor(Class cls_gen, const uint8_t* (*accessor) (id object)) {
5114 class_t *cls = newcls(cls_gen);
5117 rwlock_write(&runtimeLock);
5119 class_ro_t *ro_w = make_ro_writeable(cls->data());
5121 // FIXME: this really isn't safe to free if there are instances of this class already.
5122 if (!(cls->data()->flags & RW_HAS_INSTANCE_SPECIFIC_LAYOUT)) try_free(ro_w->ivarLayout);
5123 ro_w->ivarLayout = (uint8_t *)accessor;
5124 changeInfo(cls, RW_HAS_INSTANCE_SPECIFIC_LAYOUT, 0);
5126 rwlock_unlock_write(&runtimeLock);
5130 _object_getIvarLayout(Class cls_gen, id object) {
5131 class_t *cls = newcls(cls_gen);
5133 const uint8_t* layout = cls->data()->ro->ivarLayout;
5134 if (cls->data()->flags & RW_HAS_INSTANCE_SPECIFIC_LAYOUT) {
5135 const uint8_t* (*accessor) (id object) = (const uint8_t* (*)(id))layout;
5136 layout = accessor(object);
5143 /***********************************************************************
5144 * class_setWeakIvarLayout
5145 * Changes the class's GC weak layout.
5146 * NULL layout means no weak ivars
5147 * The class must be under construction.
5148 * fixme: sanity-check layout vs instance size?
5149 * fixme: sanity-check layout vs superclass?
5150 * Locking: acquires runtimeLock
5151 **********************************************************************/
5153 class_setWeakIvarLayout(Class cls_gen, const uint8_t *layout)
5155 class_t *cls = newcls(cls_gen);
5158 rwlock_write(&runtimeLock);
5160 // Can only change layout of in-construction classes.
5161 // note: if modifications to post-construction classes were
5162 // allowed, there would be a race below (us vs. concurrent GC scan)
5163 if (!(cls->data()->flags & RW_CONSTRUCTING)) {
5164 _objc_inform("*** Can't set weak ivar layout for already-registered "
5165 "class '%s'", getName(cls));
5166 rwlock_unlock_write(&runtimeLock);
5170 class_ro_t *ro_w = make_ro_writeable(cls->data());
5172 try_free(ro_w->weakIvarLayout);
5173 ro_w->weakIvarLayout = _ustrdup_internal(layout);
5175 rwlock_unlock_write(&runtimeLock);
5179 /***********************************************************************
5180 * _class_getVariable
5182 * Locking: read-locks runtimeLock
5183 **********************************************************************/
5185 _class_getVariable(Class cls, const char *name, Class *memberOf)
5187 rwlock_read(&runtimeLock);
5189 for ( ; cls != Nil; cls = class_getSuperclass(cls)) {
5190 ivar_t *ivar = getIvar(newcls(cls), name);
5192 rwlock_unlock_read(&runtimeLock);
5193 if (memberOf) *memberOf = cls;
5198 rwlock_unlock_read(&runtimeLock);
5204 /***********************************************************************
5205 * class_conformsToProtocol
5207 * Locking: read-locks runtimeLock
5208 **********************************************************************/
5209 BOOL class_conformsToProtocol(Class cls_gen, Protocol *proto_gen)
5211 class_t *cls = newcls(cls_gen);
5212 protocol_t *proto = newprotocol(proto_gen);
5213 const protocol_list_t **plist;
5217 if (!cls_gen) return NO;
5218 if (!proto_gen) return NO;
5220 rwlock_read(&runtimeLock);
5222 assert(isRealized(cls));
5224 for (plist = cls->data()->protocols; plist && *plist; plist++) {
5225 for (i = 0; i < (*plist)->count; i++) {
5226 protocol_t *p = remapProtocol((*plist)->list[i]);
5227 if (p == proto || _protocol_conformsToProtocol_nolock(p, proto)) {
5235 rwlock_unlock_read(&runtimeLock);
5241 /***********************************************************************
5244 * Locking: runtimeLock must be held by the caller
5245 **********************************************************************/
5247 addMethod(class_t *cls, SEL name, IMP imp, const char *types, BOOL replace)
5251 rwlock_assert_writing(&runtimeLock);
5254 assert(isRealized(cls));
5257 if ((m = getMethodNoSuper_nolock(cls, name))) {
5260 result = _method_getImplementation(m);
5262 result = _method_setImplementation(cls, m, imp);
5266 method_list_t *newlist;
5267 newlist = (method_list_t *)_calloc_internal(sizeof(*newlist), 1);
5268 newlist->entsize_NEVER_USE = (uint32_t)sizeof(method_t) | fixed_up_method_list;
5270 newlist->first.name = name;
5271 newlist->first.types = strdup(types);
5272 if (!ignoreSelector(name)) {
5273 newlist->first.imp = imp;
5275 newlist->first.imp = (IMP)&_objc_ignored_method;
5278 BOOL vtablesAffected = NO;
5279 attachMethodLists(cls, &newlist, 1, NO, &vtablesAffected);
5281 if (vtablesAffected) flushVtables(cls);
5291 class_addMethod(Class cls, SEL name, IMP imp, const char *types)
5293 if (!cls) return NO;
5295 rwlock_write(&runtimeLock);
5296 IMP old = addMethod(newcls(cls), name, imp, types ?: "", NO);
5297 rwlock_unlock_write(&runtimeLock);
5298 return old ? NO : YES;
5303 class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
5305 if (!cls) return NULL;
5307 rwlock_write(&runtimeLock);
5308 IMP old = addMethod(newcls(cls), name, imp, types ?: "", YES);
5309 rwlock_unlock_write(&runtimeLock);
5314 /***********************************************************************
5316 * Adds an ivar to a class.
5317 * Locking: acquires runtimeLock
5318 **********************************************************************/
5320 class_addIvar(Class cls_gen, const char *name, size_t size,
5321 uint8_t alignment, const char *type)
5323 class_t *cls = newcls(cls_gen);
5325 if (!cls) return NO;
5327 if (!type) type = "";
5328 if (name && 0 == strcmp(name, "")) name = NULL;
5330 rwlock_write(&runtimeLock);
5332 assert(isRealized(cls));
5334 // No class variables
5335 if (isMetaClass(cls)) {
5336 rwlock_unlock_write(&runtimeLock);
5340 // Can only add ivars to in-construction classes.
5341 if (!(cls->data()->flags & RW_CONSTRUCTING)) {
5342 rwlock_unlock_write(&runtimeLock);
5346 // Check for existing ivar with this name, unless it's anonymous.
5347 // Check for too-big ivar.
5348 // fixme check for superclass ivar too?
5349 if ((name && getIvar(cls, name)) || size > UINT32_MAX) {
5350 rwlock_unlock_write(&runtimeLock);
5354 class_ro_t *ro_w = make_ro_writeable(cls->data());
5356 // fixme allocate less memory here
5358 ivar_list_t *oldlist, *newlist;
5359 if ((oldlist = (ivar_list_t *)cls->data()->ro->ivars)) {
5360 size_t oldsize = ivar_list_size(oldlist);
5361 newlist = (ivar_list_t *)
5362 _calloc_internal(oldsize + oldlist->entsize, 1);
5363 memcpy(newlist, oldlist, oldsize);
5364 _free_internal(oldlist);
5366 newlist = (ivar_list_t *)
5367 _calloc_internal(sizeof(ivar_list_t), 1);
5368 newlist->entsize = (uint32_t)sizeof(ivar_t);
5371 uint32_t offset = unalignedInstanceSize(cls);
5372 uint32_t alignMask = (1<<alignment)-1;
5373 offset = (offset + alignMask) & ~alignMask;
5375 ivar_t *ivar = ivar_list_nth(newlist, newlist->count++);
5376 ivar->offset = (uintptr_t *)_malloc_internal(sizeof(*ivar->offset));
5377 *ivar->offset = offset;
5378 ivar->name = name ? _strdup_internal(name) : NULL;
5379 ivar->type = _strdup_internal(type);
5380 ivar->alignment = alignment;
5381 ivar->size = (uint32_t)size;
5383 ro_w->ivars = newlist;
5384 ro_w->instanceSize = (uint32_t)(offset + size);
5386 // Ivar layout updated in registerClass.
5388 rwlock_unlock_write(&runtimeLock);
5394 /***********************************************************************
5396 * Adds a protocol to a class.
5397 * Locking: acquires runtimeLock
5398 **********************************************************************/
5399 BOOL class_addProtocol(Class cls_gen, Protocol *protocol_gen)
5401 class_t *cls = newcls(cls_gen);
5402 protocol_t *protocol = newprotocol(protocol_gen);
5403 protocol_list_t *plist;
5404 const protocol_list_t **plistp;
5406 if (!cls) return NO;
5407 if (class_conformsToProtocol(cls_gen, protocol_gen)) return NO;
5409 rwlock_write(&runtimeLock);
5411 assert(isRealized(cls));
5414 plist = (protocol_list_t *)
5415 _malloc_internal(sizeof(protocol_list_t) + sizeof(protocol_t *));
5417 plist->list[0] = (protocol_ref_t)protocol;
5419 unsigned int count = 0;
5420 for (plistp = cls->data()->protocols; plistp && *plistp; plistp++) {
5424 cls->data()->protocols = (const protocol_list_t **)
5425 _realloc_internal(cls->data()->protocols,
5426 (count+2) * sizeof(protocol_list_t *));
5427 cls->data()->protocols[count] = plist;
5428 cls->data()->protocols[count+1] = NULL;
5432 rwlock_unlock_write(&runtimeLock);
5438 /***********************************************************************
5440 * Adds a property to a class.
5441 * Locking: acquires runtimeLock
5442 **********************************************************************/
5444 _class_addProperty(Class cls_gen, const char *name,
5445 const objc_property_attribute_t *attrs, unsigned int count,
5448 class_t *cls = newcls(cls_gen);
5449 chained_property_list *plist;
5451 if (!cls) return NO;
5452 if (!name) return NO;
5454 property_t *prop = class_getProperty(cls_gen, name);
5455 if (prop && !replace) {
5456 // already exists, refuse to replace
5461 rwlock_write(&runtimeLock);
5462 try_free(prop->attributes);
5463 prop->attributes = copyPropertyAttributeString(attrs, count);
5464 rwlock_unlock_write(&runtimeLock);
5468 rwlock_write(&runtimeLock);
5470 assert(isRealized(cls));
5472 plist = (chained_property_list *)
5473 _malloc_internal(sizeof(*plist) + sizeof(plist->list[0]));
5475 plist->list[0].name = _strdup_internal(name);
5476 plist->list[0].attributes = copyPropertyAttributeString(attrs, count);
5478 plist->next = cls->data()->properties;
5479 cls->data()->properties = plist;
5481 rwlock_unlock_write(&runtimeLock);
5488 class_addProperty(Class cls_gen, const char *name,
5489 const objc_property_attribute_t *attrs, unsigned int n)
5491 return _class_addProperty(cls_gen, name, attrs, n, NO);
5495 class_replaceProperty(Class cls_gen, const char *name,
5496 const objc_property_attribute_t *attrs, unsigned int n)
5498 _class_addProperty(cls_gen, name, attrs, n, YES);
5502 /***********************************************************************
5504 * Look up a class by name, and realize it.
5505 * Locking: acquires runtimeLock
5506 **********************************************************************/
5508 look_up_class(const char *name,
5509 BOOL includeUnconnected __attribute__((unused)),
5510 BOOL includeClassHandler __attribute__((unused)))
5512 if (!name) return nil;
5514 rwlock_read(&runtimeLock);
5515 class_t *result = getClass(name);
5516 BOOL unrealized = result && !isRealized(result);
5517 rwlock_unlock_read(&runtimeLock);
5519 rwlock_write(&runtimeLock);
5520 realizeClass(result);
5521 rwlock_unlock_write(&runtimeLock);
5527 /***********************************************************************
5528 * objc_duplicateClass
5530 * Locking: acquires runtimeLock
5531 **********************************************************************/
5533 objc_duplicateClass(Class original_gen, const char *name,
5536 class_t *original = newcls(original_gen);
5539 rwlock_write(&runtimeLock);
5541 assert(isRealized(original));
5542 assert(!isMetaClass(original));
5544 duplicate = (class_t *)
5545 _calloc_class(alignedInstanceSize(original->isa) + extraBytes);
5546 if (unalignedInstanceSize(original->isa) < sizeof(class_t)) {
5547 _objc_inform("busted! %s\n", original->data()->ro->name);
5551 duplicate->isa = original->isa;
5552 duplicate->superclass = original->superclass;
5553 duplicate->cache = (Cache)&_objc_empty_cache;
5554 duplicate->vtable = &_objc_empty_vtable;
5556 duplicate->setData((class_rw_t *)_calloc_internal(sizeof(*original->data()), 1));
5557 duplicate->data()->flags = (original->data()->flags | RW_COPIED_RO) & ~RW_SPECIALIZED_VTABLE;
5558 duplicate->data()->version = original->data()->version;
5559 duplicate->data()->firstSubclass = NULL;
5560 duplicate->data()->nextSiblingClass = NULL;
5562 duplicate->data()->ro = (class_ro_t *)
5563 _memdup_internal(original->data()->ro, sizeof(*original->data()->ro));
5564 *(char **)&duplicate->data()->ro->name = _strdup_internal(name);
5566 if (original->data()->methods) {
5567 duplicate->data()->methods = (method_list_t **)
5568 _memdup_internal(original->data()->methods,
5569 malloc_size(original->data()->methods));
5570 method_list_t **mlistp;
5571 for (mlistp = duplicate->data()->methods; *mlistp; mlistp++) {
5572 *mlistp = (method_list_t *)
5573 _memdup_internal(*mlistp, method_list_size(*mlistp));
5577 // fixme dies when categories are added to the base
5578 duplicate->data()->properties = original->data()->properties;
5579 duplicate->data()->protocols = original->data()->protocols;
5581 if (duplicate->superclass) {
5582 addSubclass(duplicate->superclass, duplicate);
5585 // Don't methodize class - construction above is correct
5587 addNamedClass(duplicate, duplicate->data()->ro->name);
5588 addRealizedClass(duplicate);
5589 // no: duplicate->isa == original->isa
5590 // addRealizedMetaclass(duplicate->isa);
5592 if (PrintConnecting) {
5593 _objc_inform("CLASS: realizing class '%s' (duplicate of %s) %p %p",
5594 name, original->data()->ro->name,
5595 duplicate, duplicate->data()->ro);
5598 rwlock_unlock_write(&runtimeLock);
5600 return (Class)duplicate;
5603 /***********************************************************************
5604 * objc_initializeClassPair
5605 * Locking: runtimeLock must be write-locked by the caller
5606 **********************************************************************/
5608 // &UnsetLayout is the default ivar layout during class construction
5609 static const uint8_t UnsetLayout = 0;
5611 static void objc_initializeClassPair_internal(Class superclass_gen, const char *name, Class cls_gen, Class meta_gen)
5613 rwlock_assert_writing(&runtimeLock);
5615 class_t *superclass = newcls(superclass_gen);
5616 class_t *cls = newcls(cls_gen);
5617 class_t *meta = newcls(meta_gen);
5618 class_ro_t *cls_ro_w, *meta_ro_w;
5620 cls->setData((class_rw_t *)_calloc_internal(sizeof(class_rw_t), 1));
5621 meta->setData((class_rw_t *)_calloc_internal(sizeof(class_rw_t), 1));
5622 cls_ro_w = (class_ro_t *)_calloc_internal(sizeof(class_ro_t), 1);
5623 meta_ro_w = (class_ro_t *)_calloc_internal(sizeof(class_ro_t), 1);
5624 cls->data()->ro = cls_ro_w;
5625 meta->data()->ro = meta_ro_w;
5628 cls->cache = (Cache)&_objc_empty_cache;
5629 meta->cache = (Cache)&_objc_empty_cache;
5630 cls->vtable = &_objc_empty_vtable;
5631 meta->vtable = &_objc_empty_vtable;
5633 cls->data()->flags = RW_CONSTRUCTING | RW_COPIED_RO | RW_REALIZED;
5634 meta->data()->flags = RW_CONSTRUCTING | RW_COPIED_RO | RW_REALIZED;
5635 cls->data()->version = 0;
5636 meta->data()->version = 7;
5638 cls_ro_w->flags = 0;
5639 meta_ro_w->flags = RO_META;
5641 cls_ro_w->flags |= RO_ROOT;
5642 meta_ro_w->flags |= RO_ROOT;
5645 cls_ro_w->instanceStart = unalignedInstanceSize(superclass);
5646 meta_ro_w->instanceStart = unalignedInstanceSize(superclass->isa);
5647 cls_ro_w->instanceSize = cls_ro_w->instanceStart;
5648 meta_ro_w->instanceSize = meta_ro_w->instanceStart;
5650 cls_ro_w->instanceStart = 0;
5651 meta_ro_w->instanceStart = (uint32_t)sizeof(class_t);
5652 cls_ro_w->instanceSize = (uint32_t)sizeof(id); // just an isa
5653 meta_ro_w->instanceSize = meta_ro_w->instanceStart;
5656 cls_ro_w->name = _strdup_internal(name);
5657 meta_ro_w->name = _strdup_internal(name);
5659 cls_ro_w->ivarLayout = &UnsetLayout;
5660 cls_ro_w->weakIvarLayout = &UnsetLayout;
5662 // Connect to superclasses and metaclasses
5665 meta->isa = superclass->isa->isa;
5666 cls->superclass = superclass;
5667 meta->superclass = superclass->isa;
5668 addSubclass(superclass, cls);
5669 addSubclass(superclass->isa, meta);
5672 cls->superclass = Nil;
5673 meta->superclass = cls;
5674 addSubclass(cls, meta);
5678 /***********************************************************************
5679 * objc_initializeClassPair
5680 **********************************************************************/
5681 Class objc_initializeClassPair(Class superclass_gen, const char *name, Class cls_gen, Class meta_gen)
5683 class_t *superclass = newcls(superclass_gen);
5685 rwlock_write(&runtimeLock);
5688 // Common superclass integrity checks with objc_allocateClassPair
5690 if (getClass(name)) {
5691 rwlock_unlock_write(&runtimeLock);
5694 // fixme reserve class against simultaneous allocation
5696 if (superclass) assert(isRealized(superclass));
5698 if (superclass && superclass->data()->flags & RW_CONSTRUCTING) {
5699 // Can't make subclass of an in-construction class
5700 rwlock_unlock_write(&runtimeLock);
5705 // just initialize what was supplied
5706 objc_initializeClassPair_internal(superclass_gen, name, cls_gen, meta_gen);
5708 rwlock_unlock_write(&runtimeLock);
5712 /***********************************************************************
5713 * objc_allocateClassPair
5715 * Locking: acquires runtimeLock
5716 **********************************************************************/
5717 Class objc_allocateClassPair(Class superclass_gen, const char *name,
5720 class_t *superclass = newcls(superclass_gen);
5723 rwlock_write(&runtimeLock);
5726 // Common superclass integrity checks with objc_initializeClassPair
5728 if (getClass(name)) {
5729 rwlock_unlock_write(&runtimeLock);
5732 // fixme reserve class against simmultaneous allocation
5734 if (superclass) assert(isRealized(superclass));
5736 if (superclass && superclass->data()->flags & RW_CONSTRUCTING) {
5737 // Can't make subclass of an in-construction class
5738 rwlock_unlock_write(&runtimeLock);
5744 // Allocate new classes.
5745 size_t size = sizeof(class_t);
5746 size_t metasize = sizeof(class_t);
5748 size = alignedInstanceSize(superclass->isa);
5749 metasize = alignedInstanceSize(superclass->isa->isa);
5751 cls = _calloc_class(size + extraBytes);
5752 meta = _calloc_class(metasize + extraBytes);
5754 objc_initializeClassPair_internal(superclass_gen, name, cls, meta);
5756 rwlock_unlock_write(&runtimeLock);
5762 /***********************************************************************
5763 * objc_registerClassPair
5765 * Locking: acquires runtimeLock
5766 **********************************************************************/
5767 void objc_registerClassPair(Class cls_gen)
5769 class_t *cls = newcls(cls_gen);
5771 rwlock_write(&runtimeLock);
5773 if ((cls->data()->flags & RW_CONSTRUCTED) ||
5774 (cls->isa->data()->flags & RW_CONSTRUCTED))
5776 _objc_inform("objc_registerClassPair: class '%s' was already "
5777 "registered!", cls->data()->ro->name);
5778 rwlock_unlock_write(&runtimeLock);
5782 if (!(cls->data()->flags & RW_CONSTRUCTING) ||
5783 !(cls->isa->data()->flags & RW_CONSTRUCTING))
5785 _objc_inform("objc_registerClassPair: class '%s' was not "
5786 "allocated with objc_allocateClassPair!",
5787 cls->data()->ro->name);
5788 rwlock_unlock_write(&runtimeLock);
5792 // Build ivar layouts
5794 class_t *supercls = getSuperclass(cls);
5795 class_ro_t *ro_w = (class_ro_t *)cls->data()->ro;
5797 if (ro_w->ivarLayout != &UnsetLayout) {
5798 // Class builder already called class_setIvarLayout.
5800 else if (!supercls) {
5801 // Root class. Scan conservatively (should be isa ivar only).
5802 ro_w->ivarLayout = NULL;
5804 else if (ro_w->ivars == NULL) {
5805 // No local ivars. Use superclass's layouts.
5807 _ustrdup_internal(supercls->data()->ro->ivarLayout);
5810 // Has local ivars. Build layouts based on superclass.
5811 layout_bitmap bitmap =
5812 layout_bitmap_create(supercls->data()->ro->ivarLayout,
5813 unalignedInstanceSize(supercls),
5814 unalignedInstanceSize(cls), NO);
5816 for (i = 0; i < ro_w->ivars->count; i++) {
5817 ivar_t *ivar = ivar_list_nth(ro_w->ivars, i);
5818 if (!ivar->offset) continue; // anonymous bitfield
5820 layout_bitmap_set_ivar(bitmap, ivar->type, *ivar->offset);
5822 ro_w->ivarLayout = layout_string_create(bitmap);
5823 layout_bitmap_free(bitmap);
5826 if (ro_w->weakIvarLayout != &UnsetLayout) {
5827 // Class builder already called class_setWeakIvarLayout.
5829 else if (!supercls) {
5830 // Root class. No weak ivars (should be isa ivar only).
5831 ro_w->weakIvarLayout = NULL;
5833 else if (ro_w->ivars == NULL) {
5834 // No local ivars. Use superclass's layout.
5835 ro_w->weakIvarLayout =
5836 _ustrdup_internal(supercls->data()->ro->weakIvarLayout);
5839 // Has local ivars. Build layout based on superclass.
5840 // No way to add weak ivars yet.
5841 ro_w->weakIvarLayout =
5842 _ustrdup_internal(supercls->data()->ro->weakIvarLayout);
5846 // Clear "under construction" bit, set "done constructing" bit
5847 cls->data()->flags &= ~RW_CONSTRUCTING;
5848 cls->isa->data()->flags &= ~RW_CONSTRUCTING;
5849 cls->data()->flags |= RW_CONSTRUCTED;
5850 cls->isa->data()->flags |= RW_CONSTRUCTED;
5852 // Add to realized and uninitialized classes
5853 addNamedClass(cls, cls->data()->ro->name);
5854 addRealizedClass(cls);
5855 addRealizedMetaclass(cls->isa);
5856 addUninitializedClass(cls, cls->isa);
5858 rwlock_unlock_write(&runtimeLock);
5862 static void unload_class(class_t *cls, BOOL isMeta)
5864 // Detach class from various lists
5866 // categories not yet attached to this class
5867 category_list *cats;
5868 cats = unattachedCategoriesForClass(cls);
5869 if (cats) free(cats);
5871 // class tables and +load queue
5873 removeNamedClass(cls, getName(cls));
5874 removeRealizedClass(cls);
5875 removeUninitializedClass(cls);
5877 removeRealizedMetaclass(cls);
5880 // superclass's subclass list
5881 if (isRealized(cls)) {
5882 class_t *supercls = getSuperclass(cls);
5883 if (supercls) removeSubclass(supercls, cls);
5887 // Dispose the class's own data structures
5889 if (isRealized(cls)) {
5892 // Dereferences the cache contents; do this before freeing methods
5893 if (cls->cache != (Cache)&_objc_empty_cache) _cache_free(cls->cache);
5895 if (cls->data()->methods) {
5896 method_list_t **mlistp;
5897 for (mlistp = cls->data()->methods; *mlistp; mlistp++) {
5898 for (i = 0; i < (**mlistp).count; i++) {
5899 method_t *m = method_list_nth(*mlistp, i);
5904 try_free(cls->data()->methods);
5907 const ivar_list_t *ilist = cls->data()->ro->ivars;
5909 for (i = 0; i < ilist->count; i++) {
5910 const ivar_t *ivar = ivar_list_nth(ilist, i);
5911 try_free(ivar->offset);
5912 try_free(ivar->name);
5913 try_free(ivar->type);
5918 const protocol_list_t **plistp;
5919 for (plistp = cls->data()->protocols; plistp && *plistp; plistp++) {
5922 try_free(cls->data()->protocols);
5924 const chained_property_list *proplist = cls->data()->properties;
5926 for (uint32_t i = 0; i < proplist->count; i++) {
5927 const property_t *prop = proplist->list+i;
5928 try_free(prop->name);
5929 try_free(prop->attributes);
5932 const chained_property_list *temp = proplist;
5933 proplist = proplist->next;
5939 if (cls->vtable != &_objc_empty_vtable &&
5940 cls->data()->flags & RW_SPECIALIZED_VTABLE) try_free(cls->vtable);
5941 try_free(cls->data()->ro->ivarLayout);
5942 try_free(cls->data()->ro->weakIvarLayout);
5943 try_free(cls->data()->ro->name);
5944 try_free(cls->data()->ro);
5945 try_free(cls->data());
5950 void objc_disposeClassPair(Class cls_gen)
5952 class_t *cls = newcls(cls_gen);
5954 rwlock_write(&runtimeLock);
5956 if (!(cls->data()->flags & (RW_CONSTRUCTED|RW_CONSTRUCTING)) ||
5957 !(cls->isa->data()->flags & (RW_CONSTRUCTED|RW_CONSTRUCTING)))
5959 // class not allocated with objc_allocateClassPair
5960 // disposing still-unregistered class is OK!
5961 _objc_inform("objc_disposeClassPair: class '%s' was not "
5962 "allocated with objc_allocateClassPair!",
5963 cls->data()->ro->name);
5964 rwlock_unlock_write(&runtimeLock);
5968 if (isMetaClass(cls)) {
5969 _objc_inform("objc_disposeClassPair: class '%s' is a metaclass, "
5970 "not a class!", cls->data()->ro->name);
5971 rwlock_unlock_write(&runtimeLock);
5975 // Shouldn't have any live subclasses.
5976 if (cls->data()->firstSubclass) {
5977 _objc_inform("objc_disposeClassPair: class '%s' still has subclasses, "
5978 "including '%s'!", cls->data()->ro->name,
5979 getName(cls->data()->firstSubclass));
5981 if (cls->isa->data()->firstSubclass) {
5982 _objc_inform("objc_disposeClassPair: class '%s' still has subclasses, "
5983 "including '%s'!", cls->data()->ro->name,
5984 getName(cls->isa->data()->firstSubclass));
5987 // don't remove_class_from_loadable_list()
5988 // - it's not there and we don't have the lock
5989 unload_class(cls->isa, YES);
5990 unload_class(cls, NO);
5992 rwlock_unlock_write(&runtimeLock);
5996 /***********************************************************************
5997 * class_createInstance
6000 **********************************************************************/
6002 _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
6003 __attribute__((always_inline));
6006 _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
6008 if (!cls) return nil;
6010 assert(isRealized(newcls(cls)));
6012 size_t size = alignedInstanceSize(newcls(cls)) + extraBytes;
6014 // CF requires all object be at least 16 bytes.
6015 if (size < 16) size = 16;
6020 obj = (id)auto_zone_allocate_object(gc_zone, size,
6021 AUTO_OBJECT_SCANNED, 0, 1);
6025 obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
6027 obj = (id)calloc(1, size);
6029 if (!obj) return nil;
6031 obj->isa = cls; // need not be object_setClass
6033 if (_class_hasCxxStructors(cls)) {
6034 obj = _objc_constructOrFree(cls, obj);
6042 class_createInstance(Class cls, size_t extraBytes)
6044 return _class_createInstanceFromZone(cls, extraBytes, NULL);
6047 /***********************************************************************
6048 * class_createInstances
6051 **********************************************************************/
6053 class_createInstances(Class cls, size_t extraBytes,
6054 id *results, unsigned num_requested)
6056 return _class_createInstancesFromZone(cls, extraBytes, NULL,
6057 results, num_requested);
6060 static BOOL classOrSuperClassesUseARR(Class cls) {
6062 if (_class_usesAutomaticRetainRelease(cls)) return true;
6063 cls = class_getSuperclass(cls);
6068 static void arr_fixup_copied_references(id newObject, id oldObject)
6070 // use ARR layouts to correctly copy the references from old object to new, both strong and weak.
6071 Class cls = oldObject->isa;
6073 if (_class_usesAutomaticRetainRelease(cls)) {
6074 // FIXME: align the instance start to nearest id boundary. This currently handles the case where
6075 // the the compiler folds a leading BOOL (char, short, etc.) into the alignment slop of a superclass.
6076 size_t instanceStart = _class_getInstanceStart(cls);
6077 const uint8_t *strongLayout = class_getIvarLayout(cls);
6079 id *newPtr = (id *)((char*)newObject + instanceStart);
6081 while ((byte = *strongLayout++)) {
6082 unsigned skips = (byte >> 4);
6083 unsigned scans = (byte & 0x0F);
6086 // ensure strong references are properly retained.
6087 id value = *newPtr++;
6088 if (value) objc_retain(value);
6092 const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
6093 // fix up weak references if any.
6095 id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
6097 while ((byte = *weakLayout++)) {
6098 unsigned skips = (byte >> 4);
6099 unsigned weaks = (byte & 0x0F);
6100 newPtr += skips, oldPtr += skips;
6103 objc_storeWeak(newPtr, objc_loadWeak(oldPtr));
6109 cls = class_getSuperclass(cls);
6113 /***********************************************************************
6114 * object_copyFromZone
6117 **********************************************************************/
6119 _object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
6124 if (!oldObj) return nil;
6125 if (OBJC_IS_TAGGED_PTR(oldObj)) return oldObj;
6127 size = _class_getInstanceSize(oldObj->isa) + extraBytes;
6130 obj = (id) auto_zone_allocate_object(gc_zone, size,
6131 AUTO_OBJECT_SCANNED, 0, 1);
6135 obj = (id) malloc_zone_calloc((malloc_zone_t *)zone, size, 1);
6137 obj = (id) calloc(1, size);
6139 if (!obj) return nil;
6141 // fixme this doesn't handle C++ ivars correctly (#4619414)
6142 objc_memmove_collectable(obj, oldObj, size);
6146 gc_fixup_weakreferences(obj, oldObj);
6147 else if (classOrSuperClassesUseARR(obj->isa))
6148 arr_fixup_copied_references(obj, oldObj);
6150 if (classOrSuperClassesUseARR(obj->isa))
6151 arr_fixup_copied_references(obj, oldObj);
6158 /***********************************************************************
6162 **********************************************************************/
6164 object_copy(id oldObj, size_t extraBytes)
6166 return _object_copyFromZone(oldObj, extraBytes, malloc_default_zone());
6170 #if !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
6172 /***********************************************************************
6173 * class_createInstanceFromZone
6176 **********************************************************************/
6178 class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
6180 return _class_createInstanceFromZone(cls, extraBytes, zone);
6183 /***********************************************************************
6184 * object_copyFromZone
6187 **********************************************************************/
6189 object_copyFromZone(id oldObj, size_t extraBytes, void *zone)
6191 return _object_copyFromZone(oldObj, extraBytes, zone);
6197 /***********************************************************************
6198 * objc_destructInstance
6199 * Destroys an instance without freeing memory.
6200 * Calls C++ destructors.
6201 * Calls ARR ivar cleanup.
6202 * Removes associative references.
6203 * Returns `obj`. Does nothing if `obj` is nil.
6204 * Be warned that GC DOES NOT CALL THIS. If you edit this, also edit finalize.
6205 * CoreFoundation and other clients do call this under GC.
6206 **********************************************************************/
6207 void *objc_destructInstance(id obj)
6210 Class isa_gen = _object_getClass(obj);
6211 class_t *isa = newcls(isa_gen);
6213 // Read all of the flags at once for performance.
6214 bool cxx = hasCxxStructors(isa);
6215 bool assoc = !UseGC && _class_instancesHaveAssociatedObjects(isa_gen);
6217 // This order is important.
6218 if (cxx) object_cxxDestruct(obj);
6219 if (assoc) _object_remove_assocations(obj);
6221 if (!UseGC) objc_clear_deallocating(obj);
6228 /***********************************************************************
6232 **********************************************************************/
6234 object_dispose(id obj)
6236 if (!obj) return nil;
6238 objc_destructInstance(obj);
6242 auto_zone_retain(gc_zone, obj); // gc free expects rc==1
6252 /***********************************************************************
6253 * _objc_getFreedObjectClass
6256 **********************************************************************/
6257 Class _objc_getFreedObjectClass (void)
6264 OBJC_EXTERN id objc_msgSend_fixedup(id, SEL, ...);
6265 OBJC_EXTERN id objc_msgSendSuper2_fixedup(id, SEL, ...);
6266 OBJC_EXTERN id objc_msgSend_stret_fixedup(id, SEL, ...);
6267 OBJC_EXTERN id objc_msgSendSuper2_stret_fixedup(id, SEL, ...);
6268 #if defined(__i386__) || defined(__x86_64__)
6269 OBJC_EXTERN id objc_msgSend_fpret_fixedup(id, SEL, ...);
6271 #if defined(__x86_64__)
6272 OBJC_EXTERN id objc_msgSend_fp2ret_fixedup(id, SEL, ...);
6275 /***********************************************************************
6276 * _objc_fixupMessageRef
6277 * Fixes up message ref *msg.
6278 * obj is the receiver. supr is NULL for non-super messages
6279 * Locking: acquires runtimeLock
6280 **********************************************************************/
6281 OBJC_EXTERN PRIVATE_EXTERN IMP
6282 _objc_fixupMessageRef(id obj, struct objc_super2 *supr, message_ref_t *msg)
6290 rwlock_assert_unlocked(&runtimeLock);
6293 // normal message - search obj->isa for the method implementation
6294 isa = (class_t *) _object_getClass(obj);
6296 if (!isRealized(isa)) {
6297 // obj is a class object, isa is its metaclass
6299 rwlock_write(&runtimeLock);
6300 cls = realizeClass((class_t *)obj);
6301 rwlock_unlock_write(&runtimeLock);
6303 // shouldn't have instances of unrealized classes!
6304 assert(isMetaClass(isa));
6305 // shouldn't be relocating classes here!
6306 assert(cls == (class_t *)obj);
6310 // this is objc_msgSend_super, and supr->current_class->superclass
6311 // is the class to search for the method implementation
6312 assert(isRealized((class_t *)supr->current_class));
6313 isa = getSuperclass((class_t *)supr->current_class);
6316 msg->sel = sel_registerName((const char *)msg->sel);
6318 if (ignoreSelector(msg->sel)) {
6319 // ignored selector - bypass dispatcher
6320 msg->imp = (IMP)&vtable_ignored;
6321 imp = (IMP)&_objc_ignored_method;
6324 else if (msg->imp == (IMP)&objc_msgSend_fixup &&
6325 (vtableIndex = vtable_getIndex(msg->sel)) >= 0)
6328 msg->imp = vtableTrampolines[vtableIndex];
6329 imp = isa->vtable[vtableIndex];
6333 // ordinary dispatch
6334 imp = lookUpMethod((Class)isa, msg->sel, YES/*initialize*/, YES/*cache*/);
6336 if (msg->imp == (IMP)&objc_msgSend_fixup) {
6337 msg->imp = (IMP)&objc_msgSend_fixedup;
6339 else if (msg->imp == (IMP)&objc_msgSendSuper2_fixup) {
6340 msg->imp = (IMP)&objc_msgSendSuper2_fixedup;
6342 else if (msg->imp == (IMP)&objc_msgSend_stret_fixup) {
6343 msg->imp = (IMP)&objc_msgSend_stret_fixedup;
6345 else if (msg->imp == (IMP)&objc_msgSendSuper2_stret_fixup) {
6346 msg->imp = (IMP)&objc_msgSendSuper2_stret_fixedup;
6348 #if defined(__i386__) || defined(__x86_64__)
6349 else if (msg->imp == (IMP)&objc_msgSend_fpret_fixup) {
6350 msg->imp = (IMP)&objc_msgSend_fpret_fixedup;
6353 #if defined(__x86_64__)
6354 else if (msg->imp == (IMP)&objc_msgSend_fp2ret_fixup) {
6355 msg->imp = (IMP)&objc_msgSend_fp2ret_fixedup;
6359 // The ref may already have been fixed up, either by another thread
6360 // or by +initialize via lookUpMethod above.
6372 static class_t *setSuperclass(class_t *cls, class_t *newSuper)
6376 rwlock_assert_writing(&runtimeLock);
6378 oldSuper = cls->superclass;
6379 removeSubclass(oldSuper, cls);
6380 removeSubclass(oldSuper->isa, cls->isa);
6382 cls->superclass = newSuper;
6383 cls->isa->superclass = newSuper->isa;
6384 addSubclass(newSuper, cls);
6385 addSubclass(newSuper->isa, cls->isa);
6388 flushCaches(cls->isa);
6390 flushVtables(cls->isa);
6396 Class class_setSuperclass(Class cls_gen, Class newSuper_gen)
6398 class_t *cls = newcls(cls_gen);
6399 class_t *newSuper = newcls(newSuper_gen);
6402 rwlock_write(&runtimeLock);
6403 oldSuper = setSuperclass(cls, newSuper);
6404 rwlock_unlock_write(&runtimeLock);
6406 return (Class)oldSuper;