forked from macmade/OBJC4-437.1-Runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
objc-runtime-new.m
5320 lines (4393 loc) · 163 KB
/
objc-runtime-new.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2005-2008 Apple Inc. All Rights Reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/***********************************************************************
* objc-runtime-new.m
* Support for new-ABI classes and images.
**********************************************************************/
#if __OBJC2__
#include "objc-private.h"
#include "objc-runtime-new.h"
#include <objc/message.h>
#define newcls(cls) ((struct class_t *)cls)
#define newcat(cat) ((struct category_t *)cat)
#define newmethod(meth) ((struct method_t *)meth)
#define newivar(ivar) ((struct ivar_t *)ivar)
#define newcategory(cat) ((struct category_t *)cat)
#define newprotocol(p) ((struct protocol_t *)p)
#ifdef __LP64__
#define WORD_SHIFT 3UL
#define WORD_MASK 7UL
#else
#define WORD_SHIFT 2UL
#define WORD_MASK 3UL
#endif
static const char *getName(struct class_t *cls);
static uint32_t instanceSize(struct class_t *cls);
static BOOL isMetaClass(struct class_t *cls);
static struct class_t *getSuperclass(struct class_t *cls);
static void unload_class(class_t *cls, BOOL isMeta);
static class_t *setSuperclass(class_t *cls, class_t *newSuper);
static class_t *realizeClass(class_t *cls);
static void flushCaches(class_t *cls);
static void flushVtables(class_t *cls);
static method_t *getMethodNoSuper_nolock(struct class_t *cls, SEL sel);
static method_t *getMethod_nolock(class_t *cls, SEL sel);
static void changeInfo(class_t *cls, unsigned int set, unsigned int clear);
static IMP _method_getImplementation(method_t *m);
/***********************************************************************
* Lock management
* Every lock used anywhere must be managed here.
* Locks not managed here may cause gdb deadlocks.
**********************************************************************/
__private_extern__ rwlock_t runtimeLock = {0};
__private_extern__ rwlock_t selLock = {0};
__private_extern__ mutex_t cacheUpdateLock = MUTEX_INITIALIZER;
__private_extern__ recursive_mutex_t loadMethodLock = RECURSIVE_MUTEX_INITIALIZER;
static int debugger_runtimeLock;
static int debugger_selLock;
static int debugger_cacheUpdateLock;
static int debugger_loadMethodLock;
#define RDONLY 1
#define RDWR 2
__private_extern__ void lock_init(void)
{
rwlock_init(&selLock);
rwlock_init(&runtimeLock);
recursive_mutex_init(&loadMethodLock);
}
/***********************************************************************
* startDebuggerMode
* Attempt to acquire some locks for debugger mode.
* Returns 0 if debugger mode failed because too many locks are unavailable.
*
* Locks successfully acquired are held until endDebuggerMode().
* Locks not acquired are off-limits until endDebuggerMode(); any
* attempt to manipulate them will cause a trap.
* Locks not handled here may cause deadlocks in gdb.
**********************************************************************/
__private_extern__ int startDebuggerMode(void)
{
int result = DEBUGGER_FULL;
// runtimeLock is required (can't do much without it)
if (rwlock_try_write(&runtimeLock)) {
debugger_runtimeLock = RDWR;
} else if (rwlock_try_read(&runtimeLock)) {
debugger_runtimeLock = RDONLY;
result = DEBUGGER_PARTIAL;
} else {
return DEBUGGER_OFF;
}
// cacheUpdateLock is required (must not fail a necessary cache flush)
// must be AFTER runtimeLock to avoid lock inversion
if (mutex_try_lock(&cacheUpdateLock)) {
debugger_cacheUpdateLock = RDWR;
} else {
rwlock_unlock(&runtimeLock, debugger_runtimeLock);
debugger_runtimeLock = 0;
return DEBUGGER_OFF;
}
// selLock is optional
if (rwlock_try_write(&selLock)) {
debugger_selLock = RDWR;
} else if (rwlock_try_read(&selLock)) {
debugger_selLock = RDONLY;
result = DEBUGGER_PARTIAL;
} else {
debugger_selLock = 0;
result = DEBUGGER_PARTIAL;
}
// loadMethodLock is optional
if (recursive_mutex_try_lock(&loadMethodLock)) {
debugger_loadMethodLock = RDWR;
} else {
debugger_loadMethodLock = 0;
result = DEBUGGER_PARTIAL;
}
return result;
}
/***********************************************************************
* endDebuggerMode
* Relinquish locks acquired in startDebuggerMode().
**********************************************************************/
__private_extern__ void endDebuggerMode(void)
{
assert(debugger_runtimeLock != 0);
rwlock_unlock(&runtimeLock, debugger_runtimeLock);
debugger_runtimeLock = 0;
rwlock_unlock(&selLock, debugger_selLock);
debugger_selLock = 0;
assert(debugger_cacheUpdateLock == RDWR);
mutex_unlock(&cacheUpdateLock);
debugger_cacheUpdateLock = 0;
if (debugger_loadMethodLock) {
recursive_mutex_unlock(&loadMethodLock);
debugger_loadMethodLock = 0;
}
}
/***********************************************************************
* isManagedDuringDebugger
* Returns YES if the given lock is handled specially during debugger
* mode (i.e. debugger mode tries to acquire it).
**********************************************************************/
__private_extern__ BOOL isManagedDuringDebugger(void *lock)
{
if (lock == &selLock) return YES;
if (lock == &cacheUpdateLock) return YES;
if (lock == &runtimeLock) return YES;
if (lock == &loadMethodLock) return YES;
return NO;
}
/***********************************************************************
* isLockedDuringDebugger
* Returns YES if the given mutex was acquired by debugger mode.
* Locking a managed mutex during debugger mode causes a trap unless
* this returns YES.
**********************************************************************/
__private_extern__ BOOL isLockedDuringDebugger(mutex_t *lock)
{
assert(DebuggerMode);
if (lock == &cacheUpdateLock) return YES;
if (lock == (mutex_t *)&loadMethodLock) return YES;
return NO;
}
/***********************************************************************
* isReadingDuringDebugger
* Returns YES if the given rwlock was read-locked by debugger mode.
* Read-locking a managed rwlock during debugger mode causes a trap unless
* this returns YES.
**********************************************************************/
__private_extern__ BOOL isReadingDuringDebugger(rwlock_t *lock)
{
assert(DebuggerMode);
// read-lock is allowed even if debugger mode actually write-locked it
if (debugger_runtimeLock && lock == &runtimeLock) return YES;
if (debugger_selLock && lock == &selLock) return YES;
return NO;
}
/***********************************************************************
* isWritingDuringDebugger
* Returns YES if the given rwlock was write-locked by debugger mode.
* Write-locking a managed rwlock during debugger mode causes a trap unless
* this returns YES.
**********************************************************************/
__private_extern__ BOOL isWritingDuringDebugger(rwlock_t *lock)
{
assert(DebuggerMode);
if (debugger_runtimeLock == RDWR && lock == &runtimeLock) return YES;
if (debugger_selLock == RDWR && lock == &selLock) return YES;
return NO;
}
/***********************************************************************
* vtable dispatch
*
* Every class gets a vtable pointer. The vtable is an array of IMPs.
* The selectors represented in the vtable are the same for all classes
* (i.e. no class has a bigger or smaller vtable).
* Each vtable index has an associated trampoline which dispatches to
* the IMP at that index for the receiver class's vtable (after
* checking for NULL). Dispatch fixup uses these trampolines instead
* of objc_msgSend.
* Fragility: The vtable size and list of selectors is chosen at launch
* time. No compiler-generated code depends on any particular vtable
* configuration, or even the use of vtable dispatch at all.
* Memory size: If a class's vtable is identical to its superclass's
* (i.e. the class overrides none of the vtable selectors), then
* the class points directly to its superclass's vtable. This means
* selectors to be included in the vtable should be chosen so they are
* (1) frequently called, but (2) not too frequently overridden. In
* particular, -dealloc is a bad choice.
* Forwarding: If a class doesn't implement some vtable selector, that
* selector's IMP is set to objc_msgSend in that class's vtable.
* +initialize: Each class keeps the default vtable (which always
* redirects to objc_msgSend) until its +initialize is completed.
* Otherwise, the first message to a class could be a vtable dispatch,
* and the vtable trampoline doesn't include +initialize checking.
* Changes: Categories, addMethod, and setImplementation all force vtable
* reconstruction for the class and all of its subclasses, if the
* vtable selectors are affected.
**********************************************************************/
#define X8(x) \
x, x, x, x, x, x, x, x
#define X64(x) \
X8(x), X8(x), X8(x), X8(x), X8(x), X8(x), X8(x), X8(x)
#define X128(x) \
X64(x), X64(x)
#define vtableMax 128
IMP _objc_empty_vtable[vtableMax] = {
X128(objc_msgSend)
};
#ifndef NO_VTABLE
// Trampoline descriptors for gdb.
objc_trampoline_header *gdb_objc_trampolines = NULL;
void gdb_objc_trampolines_changed(objc_trampoline_header *thdr) __attribute__((noinline));
void gdb_objc_trampolines_changed(objc_trampoline_header *thdr)
{
rwlock_assert_writing(&runtimeLock);
assert(thdr == gdb_objc_trampolines);
if (PrintVtables) {
_objc_inform("VTABLES: gdb_objc_trampolines_changed(%p)", thdr);
}
}
// fixme workaround for rdar://6667753
static void appendTrampolines(objc_trampoline_header *thdr) __attribute__((noinline));
static void appendTrampolines(objc_trampoline_header *thdr)
{
rwlock_assert_writing(&runtimeLock);
assert(thdr->next == NULL);
if (gdb_objc_trampolines != thdr->next) {
thdr->next = gdb_objc_trampolines;
}
gdb_objc_trampolines = thdr;
gdb_objc_trampolines_changed(thdr);
}
// Vtable management.
static size_t vtableStrlen;
static size_t vtableCount;
static SEL *vtableSelectors;
static IMP *vtableTrampolines;
static const char * const defaultVtable[] = {
"allocWithZone:",
"alloc",
"class",
"self",
"isKindOfClass:",
"respondsToSelector:",
"isFlipped",
"length",
"objectForKey:",
"count",
"objectAtIndex:",
"isEqualToString:",
"isEqual:",
"retain",
"release",
"autorelease",
};
static const char * const defaultVtableGC[] = {
"allocWithZone:",
"alloc",
"class",
"self",
"isKindOfClass:",
"respondsToSelector:",
"isFlipped",
"length",
"objectForKey:",
"count",
"objectAtIndex:",
"isEqualToString:",
"isEqual:",
"hash",
"addObject:",
"countByEnumeratingWithState:objects:count:",
};
extern id objc_msgSend_vtable0(id, SEL, ...);
extern id objc_msgSend_vtable1(id, SEL, ...);
extern id objc_msgSend_vtable2(id, SEL, ...);
extern id objc_msgSend_vtable3(id, SEL, ...);
extern id objc_msgSend_vtable4(id, SEL, ...);
extern id objc_msgSend_vtable5(id, SEL, ...);
extern id objc_msgSend_vtable6(id, SEL, ...);
extern id objc_msgSend_vtable7(id, SEL, ...);
extern id objc_msgSend_vtable8(id, SEL, ...);
extern id objc_msgSend_vtable9(id, SEL, ...);
extern id objc_msgSend_vtable10(id, SEL, ...);
extern id objc_msgSend_vtable11(id, SEL, ...);
extern id objc_msgSend_vtable12(id, SEL, ...);
extern id objc_msgSend_vtable13(id, SEL, ...);
extern id objc_msgSend_vtable14(id, SEL, ...);
extern id objc_msgSend_vtable15(id, SEL, ...);
static IMP const defaultVtableTrampolines[] = {
objc_msgSend_vtable0,
objc_msgSend_vtable1,
objc_msgSend_vtable2,
objc_msgSend_vtable3,
objc_msgSend_vtable4,
objc_msgSend_vtable5,
objc_msgSend_vtable6,
objc_msgSend_vtable7,
objc_msgSend_vtable8,
objc_msgSend_vtable9,
objc_msgSend_vtable10,
objc_msgSend_vtable11,
objc_msgSend_vtable12,
objc_msgSend_vtable13,
objc_msgSend_vtable14,
objc_msgSend_vtable15,
};
extern objc_trampoline_header defaultVtableTrampolineDescriptors;
static void check_vtable_size(void) __unused;
static void check_vtable_size(void)
{
// Fail to compile if vtable sizes don't match.
int c1[sizeof(defaultVtableTrampolines)-sizeof(defaultVtable)] __unused;
int c2[sizeof(defaultVtable)-sizeof(defaultVtableTrampolines)] __unused;
int c3[sizeof(defaultVtableTrampolines)-sizeof(defaultVtableGC)] __unused;
int c4[sizeof(defaultVtableGC)-sizeof(defaultVtableTrampolines)] __unused;
// Fail to compile if vtableMax is too small
int c5[vtableMax - sizeof(defaultVtable)] __unused;
int c6[vtableMax - sizeof(defaultVtableGC)] __unused;
}
/*
x86_64
monomorphic (self rdi, sel* rsi, temp r10 and r11) {
test %rdi, %rdi
jeq returnZero // nil check
movq 8(%rsi), %rsi // load _cmd (fixme schedule)
movq $xxxx, %r10
cmp 0(%rdi), %r10 // isa check
jeq imp // fixme long branches
movq $yyyy, %r10
cmp 0(%rdi), %r10 // fixme load rdi once for multiple isas
jeq imp2 // fixme long branches
jmp objc_msgSend // fixme long branches
}
*/
extern uint8_t vtable_prototype;
extern uint8_t vtable_ignored;
extern int vtable_prototype_size;
extern int vtable_prototype_index_offset;
static size_t makeVtableTrampoline(uint8_t *dst, size_t index)
{
// copy boilerplate
memcpy(dst, &vtable_prototype, vtable_prototype_size);
// insert index
#if defined(__x86_64__)
uint16_t *p = (uint16_t *)(dst + vtable_prototype_index_offset + 3);
if (*p != 0x7fff) _objc_fatal("vtable_prototype busted");
*p = index * 8;
#else
# warning unknown architecture
#endif
return vtable_prototype_size;
}
static void initVtables(void)
{
if (DisableVtables) {
if (PrintVtables) {
_objc_inform("VTABLES: vtable dispatch disabled by OBJC_DISABLE_VTABLES");
}
vtableCount = 0;
vtableSelectors = NULL;
vtableTrampolines = NULL;
return;
}
const char * const *names;
size_t i;
if (UseGC) {
names = defaultVtableGC;
vtableCount = sizeof(defaultVtableGC) / sizeof(defaultVtableGC[0]);
} else {
names = defaultVtable;
vtableCount = sizeof(defaultVtable) / sizeof(defaultVtable[0]);
}
if (vtableCount > vtableMax) vtableCount = vtableMax;
vtableSelectors = _malloc_internal(vtableCount * sizeof(SEL));
vtableTrampolines = _malloc_internal(vtableCount * sizeof(IMP));
// Built-in trampolines and their descriptors
size_t defaultVtableTrampolineCount =
sizeof(defaultVtableTrampolines) / sizeof(defaultVtableTrampolines[0]);
#ifndef NDEBUG
// debug: use generated code for 3/4 of the table
defaultVtableTrampolineCount /= 4;
#endif
for (i = 0; i < defaultVtableTrampolineCount && i < vtableCount; i++) {
vtableSelectors[i] = sel_registerName(names[i]);
vtableTrampolines[i] = defaultVtableTrampolines[i];
}
appendTrampolines(&defaultVtableTrampolineDescriptors);
// Generated trampolines and their descriptors
if (vtableCount > defaultVtableTrampolineCount) {
// Memory for trampoline code
size_t generatedCount =
vtableCount - defaultVtableTrampolineCount;
const int align = 16;
size_t codeSize =
round_page(sizeof(objc_trampoline_header) + align +
generatedCount * (sizeof(objc_trampoline_descriptor)
+ vtable_prototype_size + align));
void *codeAddr = mmap(0, codeSize, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANON,
VM_MAKE_TAG(VM_MEMORY_OBJC_DISPATCHERS), 0);
uint8_t *t = (uint8_t *)codeAddr;
// Trampoline header
objc_trampoline_header *thdr = (objc_trampoline_header *)t;
thdr->headerSize = sizeof(objc_trampoline_header);
thdr->descSize = sizeof(objc_trampoline_descriptor);
thdr->descCount = (uint32_t)generatedCount;
thdr->next = NULL;
// Trampoline descriptors
objc_trampoline_descriptor *tdesc = (objc_trampoline_descriptor *)(thdr+1);
t = (uint8_t *)&tdesc[generatedCount];
t += align - ((uintptr_t)t % align);
// Dispatch code
size_t tdi;
for (i = defaultVtableTrampolineCount, tdi = 0;
i < vtableCount;
i++, tdi++)
{
vtableSelectors[i] = sel_registerName(names[i]);
if (vtableSelectors[i] == (SEL)kIgnore) {
vtableTrampolines[i] = (IMP)&vtable_ignored;
tdesc[tdi].offset = 0;
tdesc[tdi].flags = 0;
} else {
vtableTrampolines[i] = (IMP)t;
tdesc[tdi].offset =
(uint32_t)((uintptr_t)t - (uintptr_t)&tdesc[tdi]);
tdesc[tdi].flags =
OBJC_TRAMPOLINE_MESSAGE|OBJC_TRAMPOLINE_VTABLE;
t += makeVtableTrampoline(t, i);
t += align - ((uintptr_t)t % align);
}
}
appendTrampolines(thdr);
sys_icache_invalidate(codeAddr, codeSize);
mprotect(codeAddr, codeSize, PROT_READ|PROT_EXEC);
}
if (PrintVtables) {
for (i = 0; i < vtableCount; i++) {
_objc_inform("VTABLES: vtable[%zu] %p %s",
i, vtableTrampolines[i],
sel_getName(vtableSelectors[i]));
}
}
if (PrintVtableImages) {
_objc_inform("VTABLE IMAGES: '#' implemented by class");
_objc_inform("VTABLE IMAGES: '-' inherited from superclass");
_objc_inform("VTABLE IMAGES: ' ' not implemented");
for (i = 0; i <= vtableCount; i++) {
char spaces[vtableCount+1+1];
size_t j;
for (j = 0; j < i; j++) {
spaces[j] = '|';
}
spaces[j] = '\0';
_objc_inform("VTABLE IMAGES: %s%s", spaces,
i<vtableCount ? sel_getName(vtableSelectors[i]) : "");
}
}
if (PrintVtables || PrintVtableImages) {
vtableStrlen = 0;
for (i = 0; i < vtableCount; i++) {
vtableStrlen += strlen(sel_getName(vtableSelectors[i]));
}
}
}
static int vtable_getIndex(SEL sel)
{
int i;
for (i = 0; i < vtableCount; i++) {
if (vtableSelectors[i] == sel) return i;
}
return -1;
}
static BOOL vtable_containsSelector(SEL sel)
{
return (vtable_getIndex(sel) < 0) ? NO : YES;
}
static void printVtableOverrides(class_t *cls, class_t *supercls)
{
char overrideMap[vtableCount+1];
int i;
if (supercls) {
size_t overridesBufferSize = vtableStrlen + 2*vtableCount + 1;
char *overrides =
_calloc_internal(overridesBufferSize, 1);
for (i = 0; i < vtableCount; i++) {
if (vtableSelectors[i] == (SEL)kIgnore) {
overrideMap[i] = '-';
continue;
}
if (getMethodNoSuper_nolock(cls, vtableSelectors[i])) {
strlcat(overrides, sel_getName(vtableSelectors[i]), overridesBufferSize);
strlcat(overrides, ", ", overridesBufferSize);
overrideMap[i] = '#';
} else if (getMethod_nolock(cls, vtableSelectors[i])) {
overrideMap[i] = '-';
} else {
overrideMap[i] = ' ';
}
}
if (PrintVtables) {
_objc_inform("VTABLES: %s%s implements %s",
getName(cls), isMetaClass(cls) ? "(meta)" : "",
overrides);
}
_free_internal(overrides);
}
else {
for (i = 0; i < vtableCount; i++) {
overrideMap[i] = '#';
}
}
if (PrintVtableImages) {
overrideMap[vtableCount] = '\0';
_objc_inform("VTABLE IMAGES: %s %s%s", overrideMap,
getName(cls), isMetaClass(cls) ? "(meta)" : "");
}
}
/***********************************************************************
* updateVtable
* Rebuilds vtable for cls, using superclass's vtable if appropriate.
* Assumes superclass's vtable is up to date.
* Does nothing to subclass vtables.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static void updateVtable(class_t *cls, BOOL force)
{
rwlock_assert_writing(&runtimeLock);
// Keep default vtable until +initialize is complete.
// Default vtable redirects to objc_msgSend, which
// enforces +initialize locking.
if (!force && !_class_isInitialized((Class)cls)) {
/*
if (PrintVtables) {
_objc_inform("VTABLES: KEEPING DEFAULT vtable for "
"uninitialized class %s%s",
getName(cls), isMetaClass(cls) ? "(meta)" : "");
}
*/
return;
}
// Decide whether this class can share its superclass's vtable.
struct class_t *supercls = getSuperclass(cls);
BOOL needVtable = NO;
int i;
if (!supercls) {
// Root classes always need a vtable
needVtable = YES;
}
else if (cls->data->flags & RW_SPECIALIZED_VTABLE) {
// Once you have your own vtable, you never go back
needVtable = YES;
}
else {
for (i = 0; i < vtableCount; i++) {
if (vtableSelectors[i] == (SEL)kIgnore) continue;
method_t *m = getMethodNoSuper_nolock(cls, vtableSelectors[i]);
// assume any local implementation differs from super's
if (m) {
needVtable = YES;
break;
}
}
}
// Build a vtable for this class, or not.
if (!needVtable) {
if (PrintVtables) {
_objc_inform("VTABLES: USING SUPERCLASS vtable for class %s%s",
getName(cls), isMetaClass(cls) ? "(meta)" : "");
}
cls->vtable = supercls->vtable;
}
else {
if (PrintVtables) {
_objc_inform("VTABLES: %s vtable for class %s%s",
(cls->data->flags & RW_SPECIALIZED_VTABLE) ?
"UPDATING SPECIALIZED" : "CREATING SPECIALIZED",
getName(cls), isMetaClass(cls) ? "(meta)" : "");
}
if (PrintVtables || PrintVtableImages) {
printVtableOverrides(cls, supercls);
}
IMP *new_vtable = cls->vtable;
IMP *super_vtable = supercls ? supercls->vtable : _objc_empty_vtable;
// fixme use msgForward (instead of msgSend from empty vtable) ?
if (cls->data->flags & RW_SPECIALIZED_VTABLE) {
// update cls->vtable in place
new_vtable = cls->vtable;
assert(new_vtable != _objc_empty_vtable);
} else {
// make new vtable
new_vtable = malloc(vtableCount * sizeof(IMP));
changeInfo(cls, RW_SPECIALIZED_VTABLE, 0);
}
for (i = 0; i < vtableCount; i++) {
if (vtableSelectors[i] == (SEL)kIgnore) {
new_vtable[i] = (IMP)&vtable_ignored;
} else {
method_t *m = getMethodNoSuper_nolock(cls, vtableSelectors[i]);
if (m) new_vtable[i] = _method_getImplementation(m);
else new_vtable[i] = super_vtable[i];
}
}
if (cls->vtable != new_vtable) {
// don't let other threads see uninitialized parts of new_vtable
OSMemoryBarrier();
cls->vtable = new_vtable;
}
}
}
// ! NO_VTABLE
#else
// NO_VTABLE
static void initVtables(void)
{
if (PrintVtables) {
_objc_inform("VTABLES: no vtables on this architecture");
}
}
static BOOL vtable_containsSelector(SEL sel)
{
return NO;
}
static void updateVtable(class_t *cls, BOOL force)
{
}
// NO_VTABLE
#endif
typedef struct {
category_t *cat;
BOOL fromBundle;
} category_pair_t;
typedef struct {
uint32_t count;
category_pair_t list[0]; // variable-size
} category_list;
#define FOREACH_METHOD_LIST(_mlist, _cls, code) \
do { \
const method_list_t *_mlist; \
if (_cls->data->methods) { \
method_list_t **_mlistp; \
for (_mlistp = _cls->data->methods; *_mlistp; _mlistp++) { \
_mlist = *_mlistp; \
code \
} \
} \
} while (0)
// fixme don't chain property lists
typedef struct chained_property_list {
struct chained_property_list *next;
uint32_t count;
struct objc_property list[0]; // variable-size
} chained_property_list;
/*
Low two bits of mlist->entsize is used as the fixed-up marker.
PREOPTIMIZED VERSION:
Fixed-up method lists get entsize&3 == 3.
dyld shared cache sets this for method lists it preoptimizes.
UN-PREOPTIMIZED VERSION:
Fixed-up method lists get entsize&3 == 1.
dyld shared cache uses 3, but those aren't trusted.
*/
static uint32_t fixed_up_method_list = 3;
__private_extern__ void
disableSelectorPreoptimization(void)
{
fixed_up_method_list = 1;
}
static BOOL isMethodListFixedUp(const method_list_t *mlist)
{
return (mlist->entsize_NEVER_USE & 3) == fixed_up_method_list;
}
static void setMethodListFixedUp(method_list_t *mlist)
{
rwlock_assert_writing(&runtimeLock);
assert(!isMethodListFixedUp(mlist));
mlist->entsize_NEVER_USE = (mlist->entsize_NEVER_USE & ~3) | fixed_up_method_list;
}
/*
static size_t chained_property_list_size(const chained_property_list *plist)
{
return sizeof(chained_property_list) +
plist->count * sizeof(struct objc_property);
}
static size_t protocol_list_size(const protocol_list_t *plist)
{
return sizeof(protocol_list_t) + plist->count * sizeof(protocol_t *);
}
*/
// low bit used by dyld shared cache
static uint32_t method_list_entsize(const method_list_t *mlist)
{
return mlist->entsize_NEVER_USE & ~(uint32_t)3;
}
static size_t method_list_size(const method_list_t *mlist)
{
return sizeof(method_list_t) + (mlist->count-1)*method_list_entsize(mlist);
}
static method_t *method_list_nth(const method_list_t *mlist, uint32_t i)
{
return (method_t *)(i*method_list_entsize(mlist) + (char *)&mlist->first);
}
static size_t ivar_list_size(const ivar_list_t *ilist)
{
return sizeof(ivar_list_t) + (ilist->count-1) * ilist->entsize;
}
static ivar_t *ivar_list_nth(const ivar_list_t *ilist, uint32_t i)
{
return (ivar_t *)(i*ilist->entsize + (char *)&ilist->first);
}
static method_list_t *cat_method_list(const category_t *cat, BOOL isMeta)
{
if (!cat) return NULL;
if (isMeta) return cat->classMethods;
else return cat->instanceMethods;
}
static uint32_t cat_method_count(const category_t *cat, BOOL isMeta)
{
method_list_t *cmlist = cat_method_list(cat, isMeta);
return cmlist ? cmlist->count : 0;
}
static method_t *cat_method_nth(const category_t *cat, BOOL isMeta, uint32_t i)
{
method_list_t *cmlist = cat_method_list(cat, isMeta);
if (!cmlist) return NULL;
return method_list_nth(cmlist, i);
}
// part of ivar_t, with non-deprecated alignment
typedef struct {
uintptr_t *offset;
const char *name;
const char *type;
uint32_t alignment;
} ivar_alignment_t;
static uint32_t ivar_alignment(const ivar_t *ivar)
{
uint32_t alignment = ((ivar_alignment_t *)ivar)->alignment;
if (alignment == (uint32_t)-1) alignment = (uint32_t)WORD_SHIFT;
return 1<<alignment;
}
static void try_free(const void *p)
{
if (p && malloc_size(p)) free((void *)p);
}
/***********************************************************************
* make_ro_writeable
* Reallocates rw->ro if necessary to make it writeable.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static class_ro_t *make_ro_writeable(class_rw_t *rw)
{
rwlock_assert_writing(&runtimeLock);
if (rw->flags & RW_COPIED_RO) {
// already writeable, do nothing
} else {
class_ro_t *ro = _memdup_internal(rw->ro, sizeof(*rw->ro));
rw->ro = ro;
rw->flags |= RW_COPIED_RO;
}
return (class_ro_t *)rw->ro;
}
/***********************************************************************
* unattachedCategories
* Returns the class => categories map of unattached categories.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static NXMapTable *unattachedCategories(void)
{
rwlock_assert_writing(&runtimeLock);
static NXMapTable *category_map = NULL;
if (category_map) return category_map;
// fixme initial map size
category_map = NXCreateMapTableFromZone(NXPtrValueMapPrototype, 16,
_objc_internal_zone());
return category_map;
}
/***********************************************************************
* addUnattachedCategoryForClass
* Records an unattached category.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static void addUnattachedCategoryForClass(category_t *cat, class_t *cls,
header_info *catHeader)
{
rwlock_assert_writing(&runtimeLock);
BOOL catFromBundle = (catHeader->mhdr->filetype == MH_BUNDLE) ? YES: NO;
// DO NOT use cat->cls!
// cls may be cat->cls->isa, or cat->cls may have been remapped.
NXMapTable *cats = unattachedCategories();
category_list *list;
list = NXMapGet(cats, cls);
if (!list) {
list = _calloc_internal(sizeof(*list) + sizeof(list->list[0]), 1);
} else {
list = _realloc_internal(list, sizeof(*list) + sizeof(list->list[0]) * (list->count + 1));
}
list->list[list->count++] = (category_pair_t){cat, catFromBundle};
NXMapInsert(cats, cls, list);
}
/***********************************************************************
* removeUnattachedCategoryForClass
* Removes an unattached category.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static void removeUnattachedCategoryForClass(category_t *cat, class_t *cls)
{
rwlock_assert_writing(&runtimeLock);
// DO NOT use cat->cls!
// cls may be cat->cls->isa, or cat->cls may have been remapped.
NXMapTable *cats = unattachedCategories();
category_list *list;
list = NXMapGet(cats, cls);
if (!list) return;
uint32_t i;
for (i = 0; i < list->count; i++) {
if (list->list[i].cat == cat) {
// shift entries to preserve list order
memmove(&list->list[i], &list->list[i+1],
(list->count-i-1) * sizeof(list->list[i]));
list->count--;
return;
}
}